一、安装python opencv模块
pip install opencv-python
二、准备好图片
准备好带缺口的图片和缺口图片template.png:
target.png:
三、代码:
def caculate_distance():
otemp = 'F:\\test\\target.png'
oblk = 'F:\\test\\template.png'
# otemp,oblk = oblk,otemp # 这两个路径要是不清楚的话 可以替换一下再尝试
target = cv2.imread(otemp, 0)
template = cv2.imread(oblk, 0)
# 缩小
# target = cv2.resize(target,None,fx=0.6,fy=0.6,interpolation=cv2.INTER_CUBIC)
# template = cv2.resize(template,None,fx=0.6,fy=0.6,interpolation=cv2.INTER_CUBIC)
w, h = target.shape[::-1]
print('w is {},h is {}'.format(w,h))
temp = 'temp.jpg'
targ = 'targ.jpg'
cv2.imwrite(temp, template)
cv2.imwrite(targ, target)
target = cv2.imread(targ)
target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)
target = abs(255 - target)
cv2.imwrite(targ, target)
target = cv2.imread(targ)
template = cv2.imread(temp)
result = cv2.matchTemplate(target, template, cv2.TM_CCOEFF_NORMED)
x, y = np.unravel_index(result.argmax(), result.shape)
# 展示圈出来的区域
cv2.rectangle(template, (y, x), (y + w, x + h), (7, 249, 151), 2)
show(template)
print('x is {},y is {}'.format(x, y))
return x, y
def show(name):
cv2.imshow('Show', name)
cv2.waitKey(0)
cv2.destroyAllWindows()
四、结果:
注意:opencv存在中文路径的问题,在读取写入中文路径的图片时,请使用一下方式:
target = self.cv_imread(template_path)
targ = os.path.join(temp_res_dir,'targ.jpg')
cv2.imencode('.jpg', target)[1].tofile(targ)
def cv_imread(self,file_path):
cv_img=cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),cv2.IMREAD_COLOR)
## imdecode读取的是rgb,如果后续需要opencv处理的话,需要转换成bgr,转换后图片颜色会变化
##cv_img=cv2.cvtColor(cv_img,cv2.COLOR_RGB2BGR)
return cv_img
具体代码需要根据上面的代码稍微改一下,主要就是 imdecode 和 imencode这俩函数