Created
July 21, 2020 07:03
-
-
Save celestialphineas/8b8d67e6471cff3831817ba8ddc82724 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- encoding: utf8 -*- | |
import os, json | |
import numpy as np | |
from PIL import Image, ImageDraw, ImageFont | |
def get_glyph_img(character, fontname, | |
pt = 1024, binarize = True, | |
descent_offset = True): | |
"""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 = font.getmetrics() | |
start = -descent if descent_offset else 0 | |
img = Image.new('L', (pt, pt), 0) | |
draw = ImageDraw.Draw(img) | |
draw.text((0, start), 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment