import cv2
def image_comparison(templatePath, sourcePath, targetPath='', defaultAccurate=0.7, defaultMethod="cv2.TM_CCOEFF_NORMED"):
result = {"match": False, "maxVal": 0, "maxLocX": 0, "maxLocY": 0, "scaleX": 0, "scaleY": 0}
img_rgb = cv2.imread(sourcePath)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
img_template = cv2.imread(templatePath, 0)
w, h = img_template.shape[::-1]
method = eval(defaultMethod)
res = cv2.matchTemplate(img_gray, img_template, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
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)
if targetPath != '':
cv2.rectangle(img_rgb, top_left, bottom_right, (0, 0, 255), 4)
cv2.imwrite(targetPath, img_rgb)
result["match"] = max_val >= defaultAccurate
result["maxVal"] = max_val
result["maxLocX"] = max_loc[0] + w / float(2)
result["maxLocY"] = max_loc[1] + h / float(2)
return result
result = image_comparison('f:/12.png', 'f:/3.png')
print(result)
print(result["maxVal"])
输出:
{'match': True, 'maxVal': 0.9384326934814453, 'maxLocX': 124.5, 'maxLocY': 256.0, 'scaleX': 0, 'scaleY': 0}
0.9384326934814453
下述两张图片对比