import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('./resource/opencv/image/messi5.jpg', cv2.IMREAD_GRAYSCALE)
img2 = img.copy()
template = cv2.imread('./resource/opencv/image/messi_face.jpg', cv2.IMREAD_GRAYSCALE)
w,h = template.shape[::-1]
# All the 6 mathods form comparison in a list
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED',
'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED',
'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
img = img2.copy()
# exec 语句用来执行储存在字符串或文件中的 Python 语句。
# 例如,我们可以在运行时生成一个包含 Python 代码的字符串,然后使用 exec 语句执行这些语句。
# eval 语句用来计算存储在字符串中的有效 Python 表达式
method = eval(meth)
# Apply template matching
res = cv2.matchTemplate(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)
cv2.rectangle(img, top_left, bottom_right, 255, 2)
plt.subplot(121), plt.imshow(res, cmap='gray'), plt.title('Mathing Result'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(img, cmap='gray'), plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
plt.suptitle(meth)
plt.show()
程序运行结果:
实测验证 cv2.TM_CCORR 的效果不是太好。
在前面的部分,我们在图片中搜素梅西的脸,而且梅西只在图片中出现了一次。假如你的目标对象只在图像中出现了很多次怎么办呢?函数cv.minMaxLoc() 只会给出最大值和最小值。此时,我们就要使用阈值了。在下面的例子中我们要经典游戏 Mario 的一张截屏图片中找到其中的硬币。
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('./resource/opencv/image/mario.jpg', cv2.IMREAD_COLOR)
img1 = img.copy()
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
template = cv2.imread('./resource/opencv/image/mario_coins.jpg', cv2.IMREAD_GRAYSCALE)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
print(res.shape)
threshold = 0.8
cv2.imshow('res', res)
# numpy.where(condition[, x, y])
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0]+w, pt[1]+h), (0, 0, 255), 1)
cv2.imshow('image',img1)
cv2.imshow('res',res)
cv2.imshow('draw',img)
cv2.waitKey(0)
cv2.destroyAllWindows()