python - 使用Python从具有两列或三列数据的图像中使用OCR读取图像中的文本

标签 python python-2.7 ocr tesseract python-tesseract

在示例图像中(仅作为引用,我的图像将具有相同的图案),一个页面具有完整的水平文本,其他页面具有两个水平文本列。

enter image description here

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

我正在将 Tesseract OCR 与 Psm 6 一起使用,它是水平读取的,这是错误的。

最佳答案

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

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

使用的脚本:

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()

然后你所需要的就是计算轮廓的边界框,并将其从原始图像中剪切出来。添加一点边距并将整个内容提供给超正方体。

关于python - 使用Python从具有两列或三列数据的图像中使用OCR读取图像中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49823451/

相关文章:

Python操作系统命令

python - 将参数限制为 python 中的特定值

python - 值错误: could not convert string to float: 'r'

python - 如何从 Python 以隐身模式打开 chrome

python - 如何绘制事件到达时间间隔的概率密度函数(PDF)?

python - Heroku Python Worker ProcFile

python - 使用python范围生成递减的整数列表

c++ - Tesseract baseapi 错误 : 'strncpy' :this function or variable may be unsafe. 考虑改用 strncpy_s

java - 查找 JPG 图像中文本的边界框

uml - 有没有办法将手写的 UML 图扫描到 UML 工具中?