@Fu Xianjun.All Rights Reserved.
图像处理技术
所需图片:
代码如图:
import cv2
import numpy as np
def cv_show(name,img):#定义一个函数
cv2.imshow(name,img)#显示图片
cv2.waitKey()#等待按键
cv2.destroyAllWindows()#释放窗口
#定义一个函数,从左到右进行排序
def sort_contours(cnts,method="left-to-right"):
reverse = False
i=0
if method=="right-to-left" or method == "bottom-to-top":#判断
reverse= True
if method =="top-to-bottom" or method =="bottem-to-top":
i=1
boundingBoxes=[cv2.boundingRect(cnt) for cnt in cnts]#用一个最小的矩形,把找到的形状包起来x,y,h,w
cnts,boundingBoxes=zip(*sorted(zip(cnts,boundingBoxes),\
key=lambda b: b[1][i],\
reverse=reverse))#进行反转
return cnts,boundingBoxes
template = cv2.imread("ocr_a_reference.png")#读模板
template_gray = cv2.cvtColor(template,cv2.COLOR_BGR2GRAY)#色彩空间转化,转换成灰度图
ret,template_binary=cv2.threshold(template_gray,127,255,1)#二值化
cv_show("template_binary",template_binary)
cnts,he= cv2.findContours(template_binary,cv2.RETR_EXTERNAL,\
cv2.CHAIN_APPROX_SIMPLE)
#查找外轮廓
template_rect=cv2.drawContours(template,cnts,-1,(0,0,255),2)
#绘制轮廓
# cv_show("template_rect",template_rect)
cnts = sort_contours(cnts)[0]
# print(cnts)
number = {}
for (i,cnt) in enumerate(cnts):
(x,y,w,h)=cv2.boundingRect(cnt)
roi = template_binary[y:y+h,x:x+w]
roi = cv2.resize(roi,(57,88))
number[i] = roi
cv_show("roi",roi)
显示结果:
说明:把各个图像中的数字读取出来(就不一一显示)