24 lines
922 B
Python
24 lines
922 B
Python
import cv2
|
|
import numpy as np
|
|
from PIL import Image, ImageDraw, ImageFont
|
|
|
|
from mower import __rootdir__
|
|
from mower.utils import typealias as tp
|
|
from mower.utils.image import cropimg
|
|
|
|
|
|
def generate_image(text: str, font_size: int) -> tp.GrayImage:
|
|
font = ImageFont.truetype(
|
|
f"{__rootdir__}/fonts/SourceHanSansCN-Medium.otf", size=font_size
|
|
)
|
|
img = Image.new(mode="L", size=(300, 70), color=(0,))
|
|
draw = ImageDraw.Draw(img)
|
|
draw.text((20, 0), text, fill=(255,), font=font)
|
|
img = np.array(img, dtype=np.uint8)
|
|
contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
|
rect = [cv2.boundingRect(c) for c in contours]
|
|
left = min(x for x, y, w, h in rect)
|
|
right = max(x + w for x, y, w, h in rect)
|
|
top = min(y for x, y, w, h in rect)
|
|
bottom = max(y + h for x, y, w, h in rect)
|
|
return cropimg(img, ((left - 2, top - 2), (right + 2, bottom + 2)))
|