如何从图像中动态提取打印字符?

时间:2018-07-27 08:04:23

标签: python opencv

我正在尝试解决由学生编写的加法问题,但是在初始阶段,我静态地裁剪了“ 1”。是否有其他方法可以使它变得动态起来呢?我如何裁剪整行并提取“ 1”“ +”“手写数据”“ =““手写数据”?提出一些有价值的改进建议。

1 个答案:

答案 0 :(得分:1)

我试图找到解决您问题的方法,我可以提取数字和“ +”号。但是由于图像边框的大小和形状相同,所以缺少了“ =”符号。

import cv2, sys, os
import numpy as np
from skimage.segmentation import clear_border

img = cv2.imread("AZnf5.png")
img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("",img_grey)
cv2.waitKey()
thresh = cv2.adaptiveThreshold(img_grey,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY_INV,21,7)
element = cv2.getStructuringElement(cv2.MORPH_RECT,(3, 3))
thresh= cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, element)
cv2.imshow("morpy",thresh)
cv2.waitKey()
thresh = cv2.erode(thresh,element,iterations = 1)
cv2.imshow("erode",thresh)
cv2.waitKey()

thresh = clear_border(thresh)
thresh = cv2.dilate(thresh,element,iterations = 1)
cv2.imshow("dilate",thresh)
cv2.waitKey()

_,contours, h = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE )
contours.sort(key=lambda x:cv2.boundingRect(x)[0])

ct=0
xds=0
digits_arr = []
for cont in contours:
    xd,yd,wd,hd = cv2.boundingRect(cont)
    if (wd >= 8 and wd < 30) and (hd >= 10 and hd <= 40):
        cv2.rectangle(img,(xd,yd),(xd+wd,yd+hd),(0,255,0),3)
        cv2.putText(img, "{}".format(ct+1), (xd,yd-2), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
        ct+=1

cv2.imshow("",img)
cv2.waitKey()

此代码可以进一步改进。谢谢