2024-06-01 08:37:22 发布
网友
在示例图像(只是一个参考,我的图像将是相同的模式)中,一个页面有完整的水平文本,其他页面有两个水平列的文本。在
如何在python中自动检测文档的模式并一列接一列地读取数据?。在
我使用的Tesseract OCR与Psm 6,它是水平读取,这是错误的。在
实现这一点的一种方法是使用形态学运算和轮廓检测。在
对于前者,你基本上是把所有的角色“流血”成一个大而粗的斑点。使用后者,您可以在图像中找到这些斑点,并提取出那些看起来有趣的(意思是:足够大)。
使用的脚本:
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上。在
实现这一点的一种方法是使用形态学运算和轮廓检测。在
对于前者,你基本上是把所有的角色“流血”成一个大而粗的斑点。使用后者,您可以在图像中找到这些斑点,并提取出那些看起来有趣的(意思是:足够大)。
使用的脚本:
然后你只需要计算出轮廓的边界框,并从原始图像中切割出来。加上一点空白,把所有的东西都放到tesseract上。在
相关问题 更多 >
编程相关推荐