python - 如何从图像中动态提取打印字符?
问题描述
我正在尝试解决学生编写的加法问题,但在初始阶段,我静态裁剪了“1”。有没有其他方法可以为它注入一些光并使其充满活力?如何裁剪整行并提取“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()
此代码可以进一步改进。谢谢
推荐阅读
- c# - 反序列化 .json 和 .xml 文件并验证它们的结构
- java - 调用 makeFancy("JAVA") 的结果是什么?
- bash - 拆分日期和时间与bash中它们之间的空间冲突
- java - Microsoft Sharepoint 在线列出文件夹中的所有文件
- angular - 如何过滤一组照片名称?
- node.js - TypeError:密钥不是“CryptoKey”类型
- sql - 如何将同一列添加两次并强制它显示另一个值?
- spring - Hibernate 生成的 id 导致错误消息:“密钥已存在”
- next.js - 多个插件 Next.js
- java - 关于为什么特定变量需要与其他变量不同的初始化方法的初学者问题