如何从图像中找到Python的字体大小?

时间:2019-10-10 07:31:34

标签: python ocr text-recognition

我目前正在尝试使用tesseract ocr或Python中的其他方法来查找图像的字体大小。

我当前的图片在这里:Image 1。在图片中,我可以肯定地知道它的顶部是字体6,底部是字体7。

我正在开始扫描图像的辅助项目,看它是否具有最低法定字体要求(即7号字体)。

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

这是我想做的事情:

legal_font = 7

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

由于图像周围有大量文本,数字6会引起注意。

1 个答案:

答案 0 :(得分:2)

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

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))
    draw = ImageDraw.Draw(im)
    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