图像匹配问题
参考
https://www.cnblogs.com/wj-1314/p/9472962.html
OpenCV matchTemplate 函数的输出是以锚点在左上角卷积后的结果,
所以 res.shape= img.shape- template.shape
>>> plt.show()
>>> template.shape
(27, 16)
>>> img_gray.shape
(207, 225)
>>> np.array(img_gray.shape) -np.array( template.shape)
array([180, 209])
>>>
>>> res.shape
(181, 210)
- TM_CCOEFF_NORMED 模式表示相关度,就是线性拟合中常用的相关系数,其绝对值越接近1 ,模式越匹配
试验 Python * 可选参数的用法
- 测试代码
test1 =np.where(res >= 2)
test1
(array([], dtype=int64), array([], dtype=int64))
>>> for xx in zip(*test1):
... print(xx)
...
>>> for xx in zip(test1):
... print(xx)
...
(array([], dtype=int64),)
(array([], dtype=int64),)
>>>
-
当 * 用在zip函数中时候,如果对象为空,则不进行枚举
-
OpenCV 模式匹配完整测试代码
import cv2
import numpy as np
import matplotlib.pyplot as plt
img_path = 'mario.jpg'
img_rgb = cv2.imread(img_path)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('mario_coin.jpg', 0)
template_h, template_w = template.shape[:2]
print(img_gray.shape) # (207, 225)
print(template.shape) # (27, 16)
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
# 取匹配程度大于 80% 的坐标
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]): # *表示可选参数
bottom_right = (pt[0] + template_w, pt[1] + template_h)
cv2.rectangle(img_rgb, pt, bottom_right, (0, 0, 255), 2)
cv2.imshow('img_rgb', img_rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()