使用 OpenCV 删除 OCR 的文本框

Remove text boxes for OCR with OpenCV

我正在尝试 运行 OCR(使用 Google 的 Tesseract)在具有以下格式的文档上:

但是,Tesseract 假定中间的短条为 letters/numbers(l 或 i 或 1)。

作为预处理措施,我尝试使用以下代码删除垂直线和水平线:

import cv2

from pdf2image import convert_from_path

pages = convert_from_path('..\app\1.pdf', 500)
for page in pages:
    page.save('..\app\out.jpg', 'JPEG')

image = cv2.imread('out.jpg')
result = image.copy()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Remove horizontal lines
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (40,1))
remove_horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(remove_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(result, [c], -1, (255,255,255), 5)

# Remove vertical lines
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,40))
remove_vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(remove_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(result, [c], -1, (255,255,255), 5)

cv2.imshow('thresh', thresh)
cv2.imshow('result', result)
cv2.imwrite('result.png', result)
cv2.waitKey()

我 运行 遇到一个问题,该文档的输出删除了文档中的大部分垂直线和水平线,甚至是下图左侧和右侧的开始线和结束线,但没有中间的小条。

我想知道我是否通过尝试预处理和删除行来解决这个问题。有没有更好的预处理方法或其他方法来解决这个问题?

观察到表单字段与字符是分开的,您可以简单地使用轮廓区域进行过滤以隔离文本字符。思路是Gaussian blur, then Otsu's threshold to obtain a binary image. From here we find contours and filter using contour area with some predetermined threshold value. We can effectively remove the lines by drawing in the contours with cv2.drawContours


二进制图像

删除的行

为 OCR 反转准备就绪

OCR 结果使用 Pytesseract

HELLO

代码

import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

# Load image, grayscale, blur, Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours and filter using contour area
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area > 500:
        cv2.drawContours(thresh, [c], -1, 0, -1)

# Invert image and OCR
invert = 255 - thresh
data = pytesseract.image_to_string(invert, lang='eng',config='--psm 6')
print(data)

cv2.imshow('thresh', thresh)
cv2.imshow('invert', invert)
cv2.waitKey()

注意: 如果您仍想使用删除 horizontal/vertical 行的方法,则需要修改垂直内核大小。例如,将 (1,40) 更改为 (1,10)。这将有助于删除较小的线条,但它也可能会删除文本中的一些垂直线,例如 L