【问题标题】:Why are my drawn bounding boxes inverted?为什么我绘制的边界框是倒置的?
【发布时间】:2021-05-26 01:53:42
【问题描述】:

我认为我错过了一些非常简单的概念,或者可能不理解 PIL.ImageDraw 或 pytesseract 创建的输出读取/绘制事物的方向......无论如何,我的问题是“为什么我的边界盒子倒置了?”

示例代码如下: 从 PIL 导入 Image,ImageDraw 导入 pytesseract from pytesseract 导入输出

input_image = Image.open('input_sample.jpg')
tess_boxes = pytesseract.image_to_boxes(input_image,output_type=Output.DICT)
draw = ImageDraw.Draw(input_image)

for idx,character in enumerate(tess_boxes['char']):

    #Get each point needed to draw the box
    left = tess_boxes['left'][idx]
    right = tess_boxes['right'][idx]
    bottom = tess_boxes['bottom'][idx]
    top = tess_boxes['top'][idx]

    #Re-arranging these seem to have no effect
    # y = (left,top)
    # x = (right,bottom)
    # runs the same as the following: 
    y = (right,bottom)
    x = (left,top)

    #Swapping x and y here has no visible effect
    draw.rectangle((x,y),fill=None,outline="#FF0000",width=3)

input_image.save('output_sample.png', "PNG")

输入图像

输出图像

【问题讨论】:

  • 您似乎在将 Y 坐标视为向上增加的库(正如数学中的约定)和将 Y 坐标视为向下增加的库(在计算机图形学中很常见)之间存在不匹配,因为监视器总是向下扫描)。
  • 我同意你的看法@jasonharper,我只是对如何解决它感到困惑。我没有找到有关 PIL 或 pytesseract 扫描方向的信息。在这个笔记上,我将让 PIL 从 0,0 到 10,10 绘制,看看 pytess 本身是否有任何绘图能力来做同样的事情。这应该直观地向我展示我想发生的事情。任何建议表示赞赏:) 我的意思是......除了倒置,它工作得很好!大声笑
  • 使用前只需从图像的高度减去每个 Y 值。
  • @jasonharper ...你的朋友应该得到一块饼干...我对这个问题的洞察力如此之深,以至于我完全绕过了那个简单的逻辑。谢谢!

标签: python python-imaging-library ocr python-tesseract


【解决方案1】:

PyTesseract 和 PIL 在不同方向上“扫描”,因此 Y 坐标不正确

正如出色的 @jasonharper 所建议的那样

在使用之前,只需从图像的高度中减去每个 Y 值。

代码已经调整到哪里

bottom = tess_boxes['bottom'][idx]
top = tess_boxes['top'][idx]

成为

bottom = h-tess_boxes['bottom'][idx]
top = h-tess_boxes['top'][idx]

其中“h”是图像的高度 (w,h = input_image.size)

在框环绕目标字符的地方,结果是所希望的。

谢谢@jasonhaper

【讨论】:

    【解决方案2】:

    您也可以使用image_to_data。你不需要做算术运算。

    import pytesseract
    
    # Load the image
    img = cv2.imread("cRPKk.jpg")
    
    # Convert to gray-scale
    gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # OCR
    d = pytesseract.image_to_data(gry, output_type=pytesseract.Output.DICT)
    n_boxes = len(d['level'])
    for i in range(n_boxes):
        (x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i])
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
    
    cv2.imshow("img", img)
    cv2.waitKey(0)
    

    结果:

    【讨论】:

    • 非常感谢您提供的附加方法。关于 "image_to_data" 与 "image_to_boxes" 的使用,我可以假设 "image_to_data" 的读取方向与 "Boxes" 选项不同吗?再次感谢您解决问题的变体
    猜你喜欢
    • 2018-04-24
    • 1970-01-01
    • 2018-08-14
    • 2011-03-28
    • 2021-11-22
    • 2017-04-27
    • 2020-06-10
    • 2017-03-17
    • 2014-10-29
    相关资源
    最近更新 更多