python-opencv image processing basics (six) image template matching

1. Template matching
#Template matching is to find a small area that matches a given sub-image in the entire image area
#So template matching first requires a template image T (given sub-image)
#Another image to be detected is required --- -Source Image
#Working method, on the image to be detected, calculate the matching degree between the template image and the overlapping sub-image from left to right and from top to bottom. The greater the degree of matching, the greater the possibility of the two being the same.

#--------------------------模板匹配-------------------------
# 匹配方法:
# 差值平方和匹配:CV_TM_SQDIFF
# 标准化差值平方和匹配:CV_TM_SQDIFF_NORMED
# 相关匹配:CV_TM_CCORR
# 标准相关匹配:CV_TM_CCORR_NORMED
# 相关匹配:CV_TM_CCOEFF
# 标准相关匹配:CV_TM_CCOEFF_NORMED


import cv2
import numpy as np


def template_demo():
	tpl=cv2.imread('../opencv-python-img/roi.jpg')
	target=cv2.imread('../opencv-python-img/target.jpg')
	methods=[cv2.TM_SQDIFF_NORMED,cv2.TM_CCORR_NORMED,cv2.TM_CCOEFF_NORMED]
	th,tw=tpl.shape[:2]
	print(methods)
	for md in methods:
		print(methods)
		print('md',md)
		result=cv2.matchTemplate(target,tpl,md)
		min_val,max_val,min_loc,max_loc=cv2.minMaxLoc(result)
		if md==cv2.TM_SQDIFF_NORMED:
			tl=min_loc
		else:
			tl=max_loc
		br=(tl[0]+tw,tl[1]+th)
		cv2.rectangle(target,tl,br,(0,0,255),2)
		#cv2.imshow('match-'+np.str(md),result)
		cv2.imshow('match-'+np.str(md),target)



if __name__ == '__main__':
	template_demo()

	cv2.waitKey(0)

Guess you like

Origin blog.csdn.net/zml194849/article/details/123395197