python-opencv【图像处理-模板匹配】

模板匹配(matchTemplate)

模板匹配,就是在待处理图像中,利用模板进行遍历,找到相似度最大的区域,最终将相似度最高的区域作为最终的结果。
步骤:1.准备模板图像和待处理图像
2.滑动模板图像,与原图像进行对比
3.在每一个位置,都计算与待处理图像的相似度
4.找到相似度最大的图像位置,该位置就是最匹配的区域
5.绘制显示
代码:

import cv2 as cv
import numpy as np
import  matplotlib.pyplot as plot


img=cv.imread(r"F:\z\2\u-net-vgg-bmp\0501.bmp",)
img1=cv.imread(r'C:\Users\Windows\Desktop\0501.bmp',)

img3=cv.matchTemplate(img,img1,cv.TM_CCOEFF)#cv.TM_CCOEFF使用的匹配度函数
plot.imshow(img3,cmap=plot.cm.gray)
plot.show()
a,b,c,d=cv.minMaxLoc(img3)#获得最大值所在的位置
h,w=img1.shape[:2]#获得模板图像长宽
aa=d#获得矩形框的左上角坐标和右下角坐标
bb=(aa[0]+w,aa[1]+h)
cv.rectangle(img,aa,bb,(255,255,0),2)#绘制矩形框
plot.imshow(img[:,:,::-1])
plot.show()

实验结果

1待处理图像:
在这里插入图片描述
2.模板图像:
在这里插入图片描述
3.模板匹配结果:
在这里插入图片描述
小记:模板匹配存在的问题,当待处理图像出现旋转、缩放、光照强度不足等问题,模板匹配的精度会有所下降

好的,以下是使用 Python OpenCV 进行模板匹配的基本流程: 1. 读取模板图像和待匹配图像: ```python import cv2 # 读取模板图像和待匹配图像 template = cv2.imread('template.png', cv2.IMREAD_GRAYSCALE) image = cv2.imread('image.png', cv2.IMREAD_GRAYSCALE) ``` 2. 创建 linemod 模型: ```python # 创建 linemod 模型 num_modalities = 1 threshold = 90 detector = cv2.linemod.getDefaultLINE() detector = cv2.linemod.createLINE(detector, num_modalities, threshold) ``` 3. 添加模板: ```python # 添加模板到 linemod 模型中 template_id = 0 template_modality = 0 detector.addTemplate(template, 'template', template_modality, [template_id]) ``` 4. 进行模板匹配: ```python # 进行模板匹配 matches = detector.match(image, threshold, [cv2.linemod.DEFAULT_NORM]) ``` 5. 处理匹配结果: ```python # 处理匹配结果 for match in matches: template_id, _, (x, y) = match print('Template ID: {}, Location: ({}, {})'.format(template_id, x, y)) ``` 完整代码如下: ```python import cv2 # 读取模板图像和待匹配图像 template = cv2.imread('template.png', cv2.IMREAD_GRAYSCALE) image = cv2.imread('image.png', cv2.IMREAD_GRAYSCALE) # 创建 linemod 模型 num_modalities = 1 threshold = 90 detector = cv2.linemod.getDefaultLINE() detector = cv2.linemod.createLINE(detector, num_modalities, threshold) # 添加模板到 linemod 模型中 template_id = 0 template_modality = 0 detector.addTemplate(template, 'template', template_modality, [template_id]) # 进行模板匹配 matches = detector.match(image, threshold, [cv2.linemod.DEFAULT_NORM]) # 处理匹配结果 for match in matches: template_id, _, (x, y) = match print('Template ID: {}, Location: ({}, {})'.format(template_id, x, y)) ``` 注意,这只是一个简单的示例。在实际应用中,可能需要对 linemod 模型进行更复杂的配置,以获得更好的匹配效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值