Skip to content

Instantly share code, notes, and snippets.

@celestialphineas
Created October 23, 2019 09:11
Show Gist options
  • Save celestialphineas/2a149f5b3a4f2bc9d74fade72769b310 to your computer and use it in GitHub Desktop.
Save celestialphineas/2a149f5b3a4f2bc9d74fade72769b310 to your computer and use it in GitHub Desktop.
Get image of a certain glyph from the given font
#!/usr/bin/env python3
# -*- encoding: utf8 -*-
import os
import numpy as np
from PIL import Image, ImageDraw, ImageFont
dirname = os.path.dirname(__file__)
shs_cn_filename = os.path.join(dirname,
'../../data/fonts/SourceHanSansSC-ExtraLight.otf')
def get_glyph_img(character,
pt = 1024, binarize = True, fontname = shs_cn_filename):
"""Get image of a certain glyph from the given font
Parameters
----------
character: str
The character to draw
pt: int
Number of pixels horizontally and vertically
binarize: boolean
Return a binary image or not
fontname: str
The font file name
Returns
----------
glyph_img: numpy.ndarray
A greyscale image of the glyph, with its foreground in white (255) and
background in black (0).
"""
font = ImageFont.truetype(fontname, pt)
descent = abs(font.getmetrics()[-1])
img = Image.new('L', (pt, pt), 0)
draw = ImageDraw.Draw(img)
draw.text((0, -descent), character, 255, font = font)
img_array = np.array(img, dtype = np.uint8)
if not binarize: return img_array
else: return (img_array > 128).astype(np.uint8)
# visualization
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_axes([0, 0, 1, 1])
ax = fig.axes[0]
ax.imshow(get_glyph_img('棒'), cmap = plt.cm.get_cmap('gray'))
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment