首页 > 解决方案 > 如何从图像中动态提取打印字符?

问题描述

我正在尝试解决学生编写的加法问题,但在初始阶段,我静态裁剪了“1”。有没有其他方法可以为它注入一些光并使其充满活力?如何裁剪整行并提取“1”“+”“手写数据”“=”“手写数据”?提出一些有价值的改进建议。

标签: pythonopencv

解决方案


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

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()

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


推荐阅读