OpenCV python 模板匹配(多匹配)
处理图片:[source4.jpg]
模板图片:[temp.jpg]
import cv2
import numpy as np
import matplotlib.pyplot as plt
def main():
# 1.导入图片 与 模板图片
img_src = cv2.imread("source4.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_CCOEFF_NORMED)
# 3.获取模板匹配结果
threshold = 0.9
loc = np.where(result >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_src, pt, (pt[0] + temp_w, pt[1] + temp_h), 255, 1)
# 4.显示结果
plt.figure("显示结果", figsize=(10, 7))
plt.subplot(121)
plt.imshow(result, cmap="gray")
plt.title(" ")
plt.xticks([])
plt.yticks([])
plt.subplot(122)
plt.imshow(img_src, cmap="gray")
plt.title(" ")
plt.xticks([])
plt.yticks([])
plt.show()
cv2.waitKey()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
处理结果: