如何在Python中从图片中查找字体大小?

3

我正在尝试找出如何使用tesseract ocr或Python中的其他工具从图像中查找字体大小。

这是我的当前图像:Image 1。在图像中,顶部的字体大小确定为6号字体,底部是7号字体。

我正在启动一个侧项目,扫描这个图像并查看它是否满足最低法定字体要求(即7号字体)。

我该如何确定图像中所有文本的字体大小都是7号,而不是小于7号?

我正在考虑以下做法:

legal_font = 7

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

数字6是一个容易变化的数字,由于图片周围有大量文字。


1
可能是使用Tesseract和Pyocr在Python中获取字体大小的重复问题。 - Phoenix
1
已经研究过了,但是如果你看答案的评论,它不再起作用了。 - Oct2020
1
这是为Windows 10还是其他操作系统设计的? - Bob
你能附上一个样例图片吗? - Bob
文本将像示例中一样与图像轴对齐吗?还是需要处理旋转的文本? - Bob
显示剩余3条评论
1个回答

3
这似乎是你问题的一个有效答案:
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


谢谢你的代码。我尝试了你的代码,但是这个代码只是在我的现有图像中添加了一个新的文本“Hello World”,并显示了它的大小和其他信息。我原本期望这个代码会显示图像中已经存在的文本大小。你能否请澄清一下我们如何使用这个代码来从图像中获取文本大小?谢谢。 - saurav.rox
我将为生产进行更新,很抱歉之前没有通知您。 - Mohit Reddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接