本文最后更新于:2024年1月14日 晚上

模板匹配是将模板与重叠的图像区域进行比较,以定位重合区域的图像处理方法,本文记录 OpenCV 相关内容实现方法。

简介

模板匹配任务需要将模板在图像中搜索,以确定模板所在位置的一种技术,Python OpenCV 中封装的函数为 cv2.matchTemplate

函数说明

函数引用形式

1
cv2.matchTemplate(image, templ, method[, result]) → result

参数说明

参数 含义
image 被搜索的图像,模板需要在图像中网格计算损失函数(需要 int8 或 float32 格式的图像)
templ 搜索的模板图像,尺寸不能比 image 大,需要和image有相同的图像数据格式
method 指定损失函数计算方法

损失函数

method=CV_TM_SQDIFF

直接计算均方误差作为损失函数

$$ R(x, y)=\sum_{x^{\prime}, y^{\prime}}\left(T\left(x^{\prime}, y^{\prime}\right)-I\left(x+x^{\prime}, y+y^{\prime}\right)\right)^{2} $$
method=CV_TM_SQDIFF_NORMED

按照二者向量模长做归一化后计算均方误差损失函数

$$ R(x, y)=\frac{\sum_{x^{\prime}, y^{\prime}}\left(T\left(x^{\prime}, y^{\prime}\right)-I\left(x+x^{\prime}, y+y^{\prime}\right)\right)^{2}}{\sqrt{\sum_{x^{\prime}, y^{\prime}} T\left(x^{\prime}, y^{\prime}\right)^{2} \cdot \sum_{x^{\prime}, y^{\prime}} I\left(x+x^{\prime}, y+y^{\prime}\right)^{2}}} $$
method=CV_TM_CCORR

计算互相关函数结果作为损失函数

$$ R(x, y)=\sum_{x^{\prime}, y^{\prime}}\left(T\left(x^{\prime}, y^{\prime}\right) \cdot I\left(x+x^{\prime}, y+y^{\prime}\right)\right) $$
method=CV_TM_CCORR_NORMED

计算按照模长归一化后的互相关函数结果作为损失函数,个人比较推荐,效果也较好,如果图像并不适于直接使用该参数可以想办法构造出归一化相关损失函数

$$ R(x, y)=\frac{\sum_{x^{\prime}, y^{\prime}}\left(T\left(x^{\prime}, y^{\prime}\right) \cdot I\left(x+x^{\prime}, y+y^{\prime}\right)\right)}{\sqrt{\sum_{x^{\prime}, y^{\prime}} T\left(x^{\prime}, y^{\prime}\right)^{2} \cdot \sum_{x^{\prime}, y^{\prime}} I\left(x+x^{\prime}, y+y^{\prime}\right)^{2}}} $$
method=CV_TM_CCOEFF

去中心化相关损失函数

$$ R(x, y)=\sum_{x^{\prime}, y^{\prime}}\left(T^{\prime}\left(x^{\prime}, y^{\prime}\right) \cdot I^{\prime}\left(x+x^{\prime}, y+y^{\prime}\right)\right) $$
  • 其中:
$$ \begin{array}{c} \mathrm{T}^{\prime}\left(x^{\prime}, y^{\prime}\right)=\mathrm{T}\left(x^{\prime}, y^{\prime}\right)-1 /(w \cdot h) \cdot \sum_{x^{\prime \prime}, y^{\prime \prime}} \mathrm{T}\left(x^{\prime \prime}, y^{\prime \prime}\right) \\ \mathrm{I}^{\prime}\left(x+x^{\prime}, y+y^{\prime}\right)=\mathrm{I}\left(x+x^{\prime}, y+y^{\prime}\right)-1 /(w \cdot h) \cdot \sum_{x^{\prime \prime}, y^{\prime \prime}} \mathrm{I}\left(x+x^{\prime \prime}, y+y^{\prime \prime}\right) \end{array} $$
method=CV_TM_CCOEFF_NORMED

相关系数损失函数

$$ R(x, y)=\frac{\sum_{x^{\prime}, y^{\prime}}\left(T^{\prime}\left(x^{\prime}, y^{\prime}\right) \cdot I^{\prime}\left(x+x^{\prime}, y+y^{\prime}\right)\right)}{\sqrt{\sum_{x^{\prime}, y^{\prime}} T^{\prime}\left(x^{\prime}, y^{\prime}\right)^{2} \cdot \sum_{x^{\prime}, y^{\prime}} I^{\prime}\left(x+x^{\prime}, y+y^{\prime}\right)^{2}}} $$

示例引用

1
out_v = cv2.matchTemplate(image, template, cv2.TM_CCORR_NORMED)

参考资料



文章链接:
https://www.zywvvd.com/notes/study/image-processing/opencv/opencv-matchTemplate/opencv-matchTemplate/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

OpenCV - 图像模板匹配 matchTemplate
https://www.zywvvd.com/notes/study/image-processing/opencv/opencv-matchTemplate/opencv-matchTemplate/
作者
Yiwei Zhang
发布于
2022年2月23日
许可协议