OpenCV python 模板匹配
处理图片:[source.jpg]
模板图片:[temp.jpg]
import cv2
import matplotlib.pyplot as plt
def main():
# 1.导入图片 与 模板图片
img_src = cv2.imread("source.jpg", cv2.IMREAD_GRAYSCALE)
img_temp = cv2.imread("temp.jpg", cv2.IMREAD_GRAYSCALE)
temp_h, temp_w = img_temp.shape[:]
# 2.执行模板匹配
result = cv2.matchTemplate(img_src, img_temp, cv2.TM_SQDIFF)
# 3.计算模板匹配矩形
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
left_top = min_loc
bottom_right = (left_top[0] + temp_w, left_top[1] + temp_h)
# 4.显示结果
cv2.rectangle(img_src, left_top, bottom_right, 255, 2)
plt.figure("显示结果", figsize=(10, 7))
plt.subplot(121)
plt.imshow(result, cmap="gray")
plt.title("match result")
plt.xticks([])
plt.yticks([])
plt.subplot(122)
plt.imshow(img_src, cmap="gray")
plt.title("img_src")
plt.xticks([])
plt.yticks([])
plt.show()
cv2.waitKey()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
处理结果: