您的位置:首页 > 编程语言 > Python开发

opencv+python 机读卡识别之试错(一)模板匹配的数字识别

2017-07-09 00:00 1726 查看
摘要: 效果一般的模板匹配,多目标

这里是效果不好的系列,但可能还是有丁点启示作用。效果好的系列:https://my.oschina.net/u/3268732/blog/1236298

图像来源于第四部分的数字,用任意截图工具截取部分图像当作模板,比如这样:



将模板与图像对比,这个方法根据matchTemplate函数只能选出整幅图里最匹配的图像,并不能找出所有,若想找出所有,必须不断切割图片。单一图片识别方法:

#读入模板图片
template0=cv2.imread('E:\PyProgramma\pyImg\SummerTrain\source\img0\\1.jpg',0)
w, h = template.shape[::-1]
'''
matchTemplate函数参数选择:
'cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',  
'cv2.TM_CCORR_NORMED', '*cv2.TM_SQDIFF', '*cv2.TM_SQDIFF_NORMED'
后两个区别在于返回坐标信息不太一样
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:  
  top_left = min_loc  
else:  
  top_left = max_loc  
  bottom_right = (top_left[0] + w, top_left[1] + h)  
  cv2.rectangle(img,top_left, bottom_right, 255, 2) 
'''
res = cv2.matchTemplate(img, template, cv2.TM_CCORR_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# 左上角顶点
topleft = min_loc
# 右下角顶点
bottom_right = (topleft[0] + w, topleft[1] + h)
# 在图里绘制矩形
cv2.rectangle(img, topleft, bottom_right, (0, 0, 255), -1)
cv2.imshow('t',img)
cv2.waitKey(0)
print(topleft,bottom_right,min_val, max_val)

若想得到所有相似图片,则需要切图,像这样:

#testnumx存的是图像框框中竖线分割的横坐标
for i in range(len(testnumx)-1):
#用来存储最大可能性
pro=[]
#对图像进行分割
tempimg=img[y1num[0]:y1num[1],testnumx[i]:testnumx[i+1]]
print(testnumx[i+1]-testnumx[i])
#这里没写好,应该转成图像序列就对了……
pro.append(templatematch(tempimg,template0))
pro.append(templatematch(tempimg, template1))
pro.append(templatematch(tempimg, template2))
pro.append(templatematch(tempimg, template3))
pro.append(templatematch(tempimg, template4))
pro.append(templatematch(tempimg, template5))
pro.append(templatematch(tempimg, template6))
pro.append(templatematch(tempimg, template7))
pro.append(templatematch(tempimg, template8))
pro.append(templatematch(tempimg, template9))
pro.append(templatematch(tempimg, templatex))
#输出最有可能的数字
print(pro.index(max(pro)))

这种方法做出来效果不太理想,可能模板加上边框会好些……方法很局限,可以用一个数字包含多个模板的方式来解决推广的问题,但随着模板数量的增加实际上已经变成了一种机器学习的方法……所以还不如直接机器学习……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  机读卡识别