我想自动化一个流程,我会收到以图像格式的手写每格一个字符的表格,并需要从这些表格中提取文本。每个字母都被框在方格中,我需要从图像表格中提取所有文本。
回答:
您可以使用按大小选择轮廓的方法,找到旋转矩形并进行逆变换操作。
import cv2 import numpy as npimg = cv2.imread('4YAry.jpg')gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 转换为二值图像thresh=cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV )[1]contours,hierarchy = cv2.findContours(thresh, 1, 2)for cnt in contours: x , y , w , h = cv2 . boundingRect ( cnt ) if abs(w-345)<10: # 方框宽度为345像素 rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect)srcTri=np.array( [box[1], box[0], box[2]] ).astype(np.float32)dstTri = np.array( [[0, 0], [0, rect[1][1]], [rect[1][0],0]] ).astype(np.float32)warp_mat = cv2.getAffineTransform(srcTri, dstTri)warp_dst = cv2.warpAffine(img, warp_mat, (np.int0(rect[1][0]), np.int0(rect[1][1])))N=14s=0.99*warp_dst.shape[1]/N # 调整矩形位置for i in range(N): warp_dst = cv2.rectangle ( warp_dst , ( 2+int(i*s) ,2 ), ( 2+int((i+1)*s) , warp_dst.shape[0]-3 ), ( 255 , 255 , 255 ), 2 )cv2.imwrite('chars.png', warp_dst)