【问题标题】:Read text from image using OCR for the image which have two columns or three columns of data using python使用OCR从图像中读取文本,用于使用python具有两列或三列数据的图像
【发布时间】:2018-04-13 18:50:34
【问题描述】:

在示例图像(只是一个参考,我的图像将具有相同的图案)中,一个页面有完整的水平文本,而另一个页面有两个水平的文本列。

如何在python中自动检测文档的模式并逐列读取数据?

我正在使用带有 Psm 6 的 Tesseract OCR,它在水平方向上读取是错误的。

【问题讨论】:

    标签: python python-2.7 ocr tesseract python-tesseract


    【解决方案1】:

    实现此目的的一种方法是使用形态学运算和轮廓检测。

    对于前者,您基本上将所有字符“流血”成一个大块。使用后者,您可以在图像中找到这些斑点并提取看起来有趣的斑点(意思是:足够大)。

    使用的脚本:

    import cv2
    import sys
    
    SCALE = 4
    AREA_THRESHOLD = 427505.0 / 2
    
    def show_scaled(name, img):
        try:
            h, w  = img.shape
        except ValueError:
            h, w, _  = img.shape
        cv2.imshow(name, cv2.resize(img, (w // SCALE, h // SCALE)))
    
    def main():
        img = cv2.imread(sys.argv[1])
        img = img[10:-10, 10:-10] # remove the border, it confuses contour detection
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        show_scaled("original", gray)
    
        # black and white, and inverted, because
        # white pixels are treated as objects in
        # contour detection
        thresholded = cv2.adaptiveThreshold(
                    gray, 255,
                    cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV,
                    25,
                    15
                )
        show_scaled('thresholded', thresholded)
        # I use a kernel that is wide enough to connect characters
        # but not text blocks, and tall enough to connect lines.
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (13, 33))
        closing = cv2.morphologyEx(thresholded, cv2.MORPH_CLOSE, kernel)
    
        im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        show_scaled("closing", closing)
    
        for contour in contours:
            convex_contour = cv2.convexHull(contour)
            area = cv2.contourArea(convex_contour)
            if area > AREA_THRESHOLD:
                cv2.drawContours(img, [convex_contour], -1, (255,0,0), 3)
    
        show_scaled("contours", img)
        cv2.imwrite("/tmp/contours.png", img)
        cv2.waitKey()
    
    if __name__ == '__main__':
        main()
    

    然后你只需要计算轮廓的边界框,并从原始图像中切割它。添加一点边距并将整个内容提供给 tesseract。

    【讨论】:

    • 这个问题怎么处理:两列不是分别被两条轮廓包围而是整体只有一个?
    • 尝试使结构元素更薄。
    • @deets,脚本运行良好,但我如何使用 python 裁剪文本框并从框中创建新图像?
    • 这真的是基本的 OpenCV 和 numpy 的东西。阅读一些教程。
    • @deets,这行代码 im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 在 opencv v4 中让我出错
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    相关资源
    最近更新 更多