首页 > 解决方案 > 如何从图像中找到 Python 中的字体大小?

问题描述

我目前正在尝试找出如何从图像中找出字体大小,使用tesseract ocrPython 中的其他方法。

我现在的图片在这里:图片 1。在图像中,我确定顶部是字体 6,底部是字体 7。

我正在开始一个扫描图像并查看它是否具有最低合法字体要求(即字体 7)的副项目。

如何确定图像中的所有文本是否为字体 7 而不是低于 7?

这是我想做的事情:

legal_font = 7

if legal_font > 6:
    print("Illegal")
else:
    print("Legal")

由于图像周围有大量文字,数字 6 会引起警惕。

标签: pythonocrtext-recognition

解决方案


这似乎是您问题的有效答案:

from PIL import ImageFont, ImageDraw, Image

def find_font_size(text, font, image, target_width_ratio):
    tested_font_size = 100
    tested_font = ImageFont.truetype(font, tested_font_size)
    observed_width, observed_height = get_text_size(text, image, tested_font)
    estimated_font_size = tested_font_size / (observed_width / image.width) * target_width_ratio
    return round(estimated_font_size)

def get_text_size(text, image, font):
    im = Image.new('RGB', (image.width, image.height))
    return draw.textsize(text, font)

width_ratio = 0.5
font_family = "arial.ttf"
text = "Hello World"

image = Image.open('pp.png')
editable_image = ImageDraw.Draw(image)
font_size = find_font_size(text, font_family, image, width_ratio)
font = ImageFont.truetype(font_family, font_size)
print(f"Font size found = {font_size} - Target ratio = {width_ratio} - Measured ratio = {get_text_size(text, image, font)[0] / image.width}")

editable_image.text((10, 10), text, font=font)
image.save('output.png')

您必须安装 PIL 软件包,如果您需要帮助,请在此处评论。

您还必须下载:https ://github.com/JotJunior/PHP-Boleto-ZF2/blob/master/public/assets/fonts/arial.ttf?raw=true


推荐阅读