我们来学习一下如何使用模板匹配寻找目标位置

In [1]:
import cv2
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline

先打印一下原图看看,因为OpenCV读取到的是BGR格式所以我们需要转换一下颜色空间

In [2]:
img_bgr = cv2.imread('images/mario.jpg')
img_rgb = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
Out[2]:
<matplotlib.image.AxesImage at 0x7f9c6edca9e8>

转换成灰度图片

In [3]:
img_gray = cv2.cvtColor(img_bgr,cv2.COLOR_BGR2GRAY)
plt.imshow(img_gray,cmap='gray')
Out[3]:
<matplotlib.image.AxesImage at 0x7f9c6ed6b978>

打印一下矮人的模板

In [4]:
dwarf = cv2.imread('images/dwarf.png',0)
plt.imshow(dwarf,cmap='gray')
Out[4]:
<matplotlib.image.AxesImage at 0x7f9c6ecd95c0>

使用cv2.matchTemplate函数将图片和模板比较,返回相似度

然后使用cv2.minMaxLoc函数可以找到最相似的坐标

In [5]:
res = cv2.matchTemplate(img_gray,dwarf,cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

w,h = dwarf.shape[::-1]
cv2.rectangle(img_rgb, max_loc, (max_loc[0] + w, max_loc[1] + h), (0,0,255), 2)

plt.imshow(img_rgb)
Out[5]:
<matplotlib.image.AxesImage at 0x7f9c6c2b3208>

我们再来试一试找出图片中的所有蘑菇

In [6]:
mushroom = cv2.imread('images/mushroom.png',0)
plt.imshow(mushroom,cmap='gray')
Out[6]:
<matplotlib.image.AxesImage at 0x7f9c6c2940f0>
In [7]:
res = cv2.matchTemplate(img_gray,mushroom,cv2.TM_CCOEFF_NORMED)

w,h = mushroom.shape[::-1]
threshold = 0.4
loc = np.where( res >= threshold)

for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

plt.imshow(img_rgb)
Out[7]:
<matplotlib.image.AxesImage at 0x7f9c6c266f60>
In [ ]:
 
posted @ 2018-05-24 14:36:38
评论加载中...

发表评论