python多模板匹配的目标检测方法
时间: 2023-09-02 20:08:42 浏览: 50
多模板匹配是一种目标检测方法,它可以在一幅图像中查找多个目标。在Python中,可以使用OpenCV库实现多模板匹配。
以下是实现多模板匹配的基本步骤:
1. 读取原始图像和模板图像
``` python
import cv2
import numpy as np
img = cv2.imread('image.jpg', 0)
template1 = cv2.imread('template1.jpg', 0)
template2 = cv2.imread('template2.jpg', 0)
```
2. 定义匹配方法
``` python
method = cv2.TM_CCOEFF_NORMED
```
其中,`cv2.TM_CCOEFF_NORMED`是相关系数匹配方法,是一种常用的匹配方法,可以用于检测旋转、缩放和光照变化等情况。
3. 对原始图像进行模板匹配
``` python
res1 = cv2.matchTemplate(img, template1, method)
res2 = cv2.matchTemplate(img, template2, method)
```
4. 设定阈值,得到匹配结果
``` python
threshold = 0.8
loc1 = np.where(res1 >= threshold)
loc2 = np.where(res2 >= threshold)
```
5. 绘制矩形框标记匹配位置
``` python
w, h = template1.shape[::-1]
for pt in zip(*loc1[::-1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
w, h = template2.shape[::-1]
for pt in zip(*loc2[::-1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
```
完整代码如下:
``` python
import cv2
import numpy as np
img = cv2.imread('image.jpg', 0)
template1 = cv2.imread('template1.jpg', 0)
template2 = cv2.imread('template2.jpg', 0)
method = cv2.TM_CCOEFF_NORMED
res1 = cv2.matchTemplate(img, template1, method)
res2 = cv2.matchTemplate(img, template2, method)
threshold = 0.8
loc1 = np.where(res1 >= threshold)
loc2 = np.where(res2 >= threshold)
w, h = template1.shape[::-1]
for pt in zip(*loc1[::-1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
w, h = template2.shape[::-1]
for pt in zip(*loc2[::-1]):
cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意:在实际应用中,需要根据具体情况选择不同的匹配方法和阈值,以达到最佳的匹配效果。