Skip to content

Instantly share code, notes, and snippets.

@celestialphineas
Created July 21, 2020 07:03
Show Gist options
  • Save celestialphineas/8b8d67e6471cff3831817ba8ddc82724 to your computer and use it in GitHub Desktop.
Save celestialphineas/8b8d67e6471cff3831817ba8ddc82724 to your computer and use it in GitHub Desktop.
#!/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