OpenCV实现边缘模板匹配算法
时间: 2023-09-24 09:02:50 浏览: 134
边缘模板匹配算法是在图像处理中广泛使用的一种技术,可以用于在图像中寻找特定的形状或边缘。下面是使用OpenCV库实现边缘模板匹配算法的步骤:
1. 加载原始图像和模板图像:
```
import cv2
img = cv2.imread('image.jpg')
template = cv2.imread('template.jpg')
```
2. 将模板图像转换为灰度图像:
```
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
```
3. 使用Canny边缘检测算法检测模板图像的边缘:
```
edges = cv2.Canny(template_gray, 50, 200)
```
4. 在原始图像中搜索与模板图像匹配的边缘:
```
result = cv2.matchTemplate(img, edges, cv2.TM_CCOEFF_NORMED)
```
5. 使用阈值来确定匹配结果的位置:
```
threshold = 0.8
locations = np.where(result >= threshold)
```
6. 在原始图像中绘制矩形框来标记匹配的位置:
```
for loc in zip(*locations[::-1]):
cv2.rectangle(img, loc, (loc[0] + w, loc[1] + h), (0, 0, 255), 2)
```
其中,`w`和`h`是模板图像的宽度和高度。
完整代码如下:
```
import cv2
import numpy as np
img = cv2.imread('image.jpg')
template = cv2.imread('template.jpg')
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(template_gray, 50, 200)
result = cv2.matchTemplate(img, edges, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
locations = np.where(result >= threshold)
w, h = template_gray.shape[::-1]
for loc in zip(*locations[::-1]):
cv2.rectangle(img, loc, (loc[0] + w, loc[1] + h), (0, 0, 255), 2)
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文
相关推荐


















