我正在尝试在图像中检测一个片段,这个片段在以下MATLAB示例中有所表示。
我使用的是OpenCV库。
```python
import cv2
import numpy as np
from imutils.object_detection import non_max_suppression
# 读取图像和模板
img = cv2.imread('SourceImage.png')
temp = cv2.imread('TargetFragment.png')
# 保存图像尺寸
W, H = temp.shape[:2]
# 定义最小阈值
thresh = 0.4
# 转换为灰度图像
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
temp_gray = cv2.cvtColor(temp, cv2.COLOR_BGR2GRAY)
# 将图像传递给matchTemplate方法
match = cv2.matchTemplate(
image=img_gray, templ=temp_gray,
method=cv2.TM_CCOEFF_NORMED)
# 选择置信度大于阈值的矩形
(y_points, x_points) = np.where(match >= thresh)
# 初始化我们的矩形列表
boxes = list()
# 再次遍历起始(x, y)坐标
for (x, y) in zip(x_points, y_points):
# 更新我们的矩形列表
boxes.append((x, y, x + W, y + H))
# 对矩形应用非极大值抑制
# 这将创建一个单一的边界框
boxes = non_max_suppression(np.array(boxes))
# 遍历最终的边界框
for (x1, y1, x2, y2) in boxes:
# 在图像上绘制边界框
cv2.rectangle(img, (x1, y1), (x2, y2),
(255, 0, 0), 3)
cv2.imwrite('result.png', img)
```
大图像是:

要检测的目标片段是:

但是检测到了两个区域,而不是一个。其中一个区域根本不包含目标片段:

我漏了什么吗?
这并不是一个适合使用matchTemplate的好任务。matchTemplate更适合于目标图像中几乎存在模板的完全副本的任务。
查看这个答案,了解特征匹配的示例:如何使用SURF特征(Python OpenCV)匹配和对齐两张图像?
祝你好运!