【问题标题】:How to find the font size in Python from an image?如何从图像中找到 Python 中的字体大小?
【发布时间】:2019-10-10 07:31:34
【问题描述】:

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

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

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

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

这是我想做的事情:

legal_font = 7

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

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

【问题讨论】:

  • 已经调查过了,但是如果你从答案中查看 cmets,它不再工作了
  • opencv + TensorFlow 也许?
  • 适用于 windows 10 还是其他操作系统?
  • 是的@user12750353,它适用于Windows 10。

标签: python ocr text-recognition


【解决方案1】:

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

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”,并显示了它的大小和其他信息。我期待代码宁愿显示图像中已经存在的文本大小。您能否澄清一下我们如何使用此代码从图像中获取文本大小?谢谢。
  • 我会为生产进行更新,很抱歉之前没有形成这个
猜你喜欢
  • 2018-09-30
  • 2023-01-27
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
  • 2021-01-17
  • 2015-02-13
  • 2020-12-12
相关资源
最近更新 更多