python 模板匹配
时间: 2023-10-15 11:31:30 浏览: 113
模板匹配
在Python中,可以使用OpenCV库来进行模板匹配。模板匹配是一种在图像中寻找特定模式的方法。以下是一个使用模板匹配的示例代码:
```python
import cv2 as cv
import numpy as np
# 读取图像和模板
img_rgb = cv.imread('./images/Mario.png')
img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
template = cv.imread('./images/mario_c.png', 0)
# 获取模板的尺寸
w, h = template.shape[::-1]
# 使用模板匹配函数进行匹配
res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED)
# 设置阈值并筛选匹配度较高的位置
threshold = 0.7
loc = np.where(res >= threshold)
# 在原图像上标记匹配的位置
for pt in zip(*loc[::-1]):
cv.rectangle(img_rgb, pt, (pt + w, pt + h), (0, 0, 255), 1)
# 显示结果
cv.imshow('res.png', img_rgb)
cv.waitKey(0)
```
这段代码首先读取了原始图像和模板图像,然后将模板转换为灰度图像。接下来,使用`matchTemplate()`函数进行模板匹配,并设置匹配的阈值。最后,通过在原图像上绘制矩形框来标记匹配的位置。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [六、OpenCV-python 之图像处理(Ⅳ)——模板匹配/分水岭/GrabCut](https://blog.csdn.net/DaGongJiGuoMaLu09/article/details/110381381)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *3* [【python版CV】图像轮廓&模板匹配](https://blog.csdn.net/qq_44859533/article/details/126068675)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文