由于您没有提供任何示例图像,我只是生成了一个简单的图像来测试:
h, w = 100, 600
img = np.zeros((h, w), dtype=np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'OCR with OpenCV', (30, h-30), font, 2, 255, 2, cv2.LINE_AA)
正如我在评论中提到的,如果你只是dilate https://docs.opencv.org/3.3.0/d9/d61/tutorial_py_morphological_ops.html图像,然后白色区域将会扩大。如果您使用足够大的内核来执行此操作,以便附近的字母合并,但又足够小以防止单独的单词合并,那么您将能够提取每个单词的轮廓,并使用它一次屏蔽一个单词以用于 OCR 目的。
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15))
dilated = cv2.dilate(img, kernel)
要单独获取每个单词的掩码,只需找到这些较大斑点的轮廓即可。您也可以对轮廓进行排序;垂直、水平或两者兼而有之,以便您按照正确的顺序获得单词。因为我只有一行,所以我将在x
方向:
contours = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[1]
contours = sorted(contours, key=lambda c: min(min(c[:, :, 0])))
for i in range(len(contours)):
mask = np.zeros((h, w), dtype=np.uint8)
# i is the contour to draw, -1 means fill the contours
mask = cv2.drawContours(mask, contours, i, 255, -1)
masked_img = cv2.bitwise_and(img, img, mask=mask)
cv2.imshow('Masked single word', masked_img)
cv2.waitKey()
# do your OCR here on the masked image