Template matching is to find the matching image to the stator small area in the entire image area,
In OpenCV provided corresponding function completes this operation:
matchTemplate function: find the match between the template and the input image, the image matching result obtained
minMaxLoc function: find the maximum and minimum values in a given matrix, given their location
Several common template matching algorithm:
①TM_SQDIFF match is squared difference; TM_SQDIFF_NORMED standard matching squared difference. Squared difference using matching, the matching is preferably 0. match worse, the larger a matching value.
②TM_CCORR relevant matching; TM_CCORR_NORMED standard correlation matching. Multiplicative operation between the template and the image, the larger number represents a higher degree of match, 0 represents the worst matching effect.
③TM_CCOEFF is a correlation coefficient match; TM_CCOEFF_NORMED match the standard correlation coefficient. The template image and the relative value of the average correlation values subjected to matching their mean, represents a perfect match and -1 for a bad match, 0 indicates no correlation (random sequence).
python achieve
import cv2 import numpy as np __author__ = "boboa" def template_demo(): tpl = cv2.imread("image/tpl.jpg") target = cv2.imread("image/target1.jpg") # cv2.imshow("template_image", tpl) # cv2.imshow("target image", target) methods = [cv2.TM_CCOEFF_NORMED, cv2.TM_SQDIFF_NORMED, cv2.TM_CCORR_NORMED] th, tw = tpl.shape[:2] for md in methods: print(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), target) if __name__ == "__main__": img = cv2.imread("img1.jpg") # cv2.namedWindow("input image", cv2.WINDOW_AUTOSIZE) # cv2.imshow("input image", img) template_demo() cv2.waitKey(0) cv2.destroyAllWindows()
operation result