【问题标题】:How to crop images using Pillow and pytesseract?如何使用 Pillow 和 pytesseract 裁剪图像?
【发布时间】:2021-03-05 12:09:02
【问题描述】:

我试图使用pytesseract 来查找图像中每个字母的框位置。我尝试使用image,并使用 Pillow 对其进行裁剪,但效果很好,但是当我尝试使用较小字符大小的图像 (example) 时,程序可能会识别字符,但使用框坐标裁剪图像会给出我的图像像this。我还尝试将原始图像的大小加倍,但没有任何改变。

img = Image.open('imgtest.png')
data=pytesseract.image_to_boxes(img)
dati= data.splitlines()
corde=[]
for i in dati[0].split()[1:5]: #just trying with the first character
    corde.append(int(i))
im=img.crop(tuple(corde))
im.save('cimg.png')

【问题讨论】:

    标签: python-3.x python-imaging-library python-tesseract


    【解决方案1】:

    如果我们坚持image_to_boxes的源代码,我们会看到,返回的坐标是这样的:

    left bottom right top
    

    Image.crop 的文档中,我们看到,预期的坐标顺序是:

    left upper right lower
    

    现在看来,pytesseract 从下到上迭代图像。因此,我们还需要进一步转换top/upperbottom/lower坐标。

    那就是修改后的代码:

    from PIL import Image
    import pytesseract
    
    img = Image.open('MJwQi9f.png')
    data = pytesseract.image_to_boxes(img)
    dati = data.splitlines()
    corde = []
    for i in dati[0].split()[1:5]:
        corde.append(int(i))
    corde = tuple([corde[0], img.size[1]-corde[3], corde[2], img.size[1]-corde[1]])
    im = img.crop(tuple(corde))
    im.save('cimg.png')
    

    你看,leftright 在同一个地方,但是 top/upperbottom/lower 交换了位置,并且其中也改变了 w.r.t.图片高度。

    而且,这是更新后的输出:

    结果不是最佳的,但我认为这是字体的原因。

    ----------------------------------------
    System information
    ----------------------------------------
    Platform:      Windows-10-10.0.16299-SP0
    Python:        3.9.1
    Pillow:        8.1.0
    pytesseract:   4.00.00alpha
    ----------------------------------------
    

    【讨论】:

    • 谢谢,我注意到了这个细节,但是由于使用大图像它可以工作,所以我认为问题不在于
    猜你喜欢
    • 2013-12-20
    • 2022-06-15
    • 1970-01-01
    • 2020-03-28
    • 2023-03-23
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多