基于滑窗的模板匹配实现目标检测python
时间: 2023-07-12 10:43:23 浏览: 118
基于滑窗的模板匹配是一种简单但是有效的目标检测方法,在Python中可以使用OpenCV库来实现。下面是一个简单的实现过程:
1. 加载模板图像和待检测图像:
```
import cv2
template = cv2.imread('template.jpg', 0)
image = cv2.imread('image.jpg', 0)
```
2. 定义滑窗大小和步长:
```
(winW, winH) = template.shape[::-1]
stepSize = 10
```
3. 在待检测图像上滑动窗口,并对每个窗口进行模板匹配:
```
for y in range(0, image.shape[0] - winH, stepSize):
for x in range(0, image.shape[1] - winW, stepSize):
roi = image[y:y + winH, x:x + winW]
result = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED)
```
4. 对匹配结果进行阈值处理,并获取匹配位置:
```
(_, maxVal, _, maxLoc) = cv2.minMaxLoc(result)
if maxVal > threshold:
cv2.rectangle(image, (x, y), (x + winW, y + winH), (0, 255, 0), 2)
```
完整代码如下:
```
import cv2
template = cv2.imread('template.jpg', 0)
image = cv2.imread('image.jpg', 0)
(winW, winH) = template.shape[::-1]
stepSize = 10
threshold = 0.8
for y in range(0, image.shape[0] - winH, stepSize):
for x in range(0, image.shape[1] - winW, stepSize):
roi = image[y:y + winH, x:x + winW]
result = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED)
(_, maxVal, _, maxLoc) = cv2.minMaxLoc(result)
if maxVal > threshold:
cv2.rectangle(image, (x, y), (x + winW, y + winH), (0, 255, 0), 2)
cv2.imshow('Result', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文