python opencv实现信用卡的数字识别
本项目利用python以及opencv实现信用卡的数字识别
前期准备
- 导入工具包
- 定义功能函数
模板图像处理
- 读取模板图像 cv2.imread(img)
- 灰度化处理 cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
- 二值化 cv2.threshold()
- 轮廓 - 轮廓
信用卡图像处理
- 读取信用卡图像 cv2.imread(img)
- 灰度化处理 cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
- 礼帽处理 cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,rectKernel)
- Sobel边缘检测 cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)
- 闭操作 cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel)
- 计算轮廓 cv2.findContours
- 模板检测 cv2.matchTemplate(roi, digitROI,cv2.TM_CCOEFF)
原始数据展示
结果展示
模板图像转灰度图像
# 转灰度图 ref = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv_show("ref",ref) plt.imshow(ref)
<matplotlib.image.AxesImage at 0x2b2e25d9e48>
计算轮廓
#cv2.findContours()函数接受的参数为二值图,即黑白的(不是灰度图),cv2.RETR_EXTERNAL只检测外轮廓,cv2.CHAIN_APPROX_SIMPLE只保留终点坐标 #返回的list中每个元素都是图像中的一个轮廓 # 在二值化后的图像中计算轮廓 refCnts,hierarchy = cv2.findContours(ref.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) # 在原图上画出轮廓 cv2.drawContours(img,refCnts,-1,(0,0,255),3) cv_show("img",img) plt.imshow(img)
<matplotlib.image.AxesImage at 0x2b2e256f908>
对图像进行预处理操作
# 先对图像进行resize操作 image = resize(image,width=300) # 灰度化处理 gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) cv_show("gray",gray) plt.imshow(gray)
<matplotlib.image.AxesImage at 0x2b2e255d828>
用Sobel算子边缘检测
gradX = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1) gradX = np.absolute(gradX) (minVal, maxVal) = (np.min(gradX), np.max(gradX)) gradX = (255 * ((gradX - minVal) / (maxVal - minVal))) gradX = gradX.astype("uint8") print (np.array(gradX).shape) cv_show("gradX",gradX) plt.imshow(gradX)
(189, 300) <matplotlib.image.AxesImage at 0x2b2e0797400>
#THRESH_OTSU会自动寻找合适的阈值,适合双峰,需把阈值参数设置为0 thresh = cv2.threshold(gradX, 0, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] cv_show("thresh",thresh) plt.imshow(thresh)
<matplotlib.image.AxesImage at 0x2b2e24a0dd8>
计算轮廓
threshCnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cnts = threshCnts cur_img = image.copy() cv2.drawContours(cur_img,cnts,-1,(0,0,255),3) cv_show("img",cur_img) plt.imshow(cur_img)
<matplotlib.image.AxesImage at 0x2b2eb17c780>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。