跳到主要内容

模板匹配算法

模板匹配是在一项在以复图像中寻找另一幅模板图像最匹配(相似)的算法。

模板匹配的原理

在要检测的图像上,从左到右,从上到下遍历这一幅图像,从上到下计算模板雨重叠子图像的像素匹配度,如果匹配的程度越大,这说明相同的可能性越大。

mo

R(x,y)表示R坐标(x,y)处的像素值,同理T(x,,y,)I(x+x,,y+y,)均表示对应坐标处的像素值R(x,y) 表示 R 坐标 (x,y) 处的像素值,同理 T(x^,,y^,) 和 I(x+x^,,y+y^,) 均表示对应坐标处的像素值

  1. 平方差匹配。method=CV_TM_SQDIFF

    这类方法利用平方差来进行匹配,最好匹配为 0,匹配越差,匹配值越大。

    R(x,y)=x,,y,(T(x,,y,)I(x+x,,y+y,))2R(x,y)=\sum_{x^,,y^,}^{}(T(x^,,y^,)-I(x+x^,,y+y^,))^2

  2. 归一化平方差匹配。method = CV_TM_SQDIFF_NORMED

    R(x,y)=x,,y,(T(x,,y,)I(x+x,,y+y,))2x,,y,T(x,,y,)2x,,y,I(x+x,,y+y,)2R(x,y)=\frac{\sum_{x^,,y^,}^{}(T(x^,,y^,)-I(x+x^,,y+y^,))^2}{\sqrt{\sum_{x^,,y^,}^{}T(x^,,y^,)^2*\sum_{x^,,y^,}^{}I(x+x^,,y+y^,)^2}}

    和平方差差不多,只是加以标准化,但是准确度提高了,牺牲了计算量

  3. 相关匹配 method = CV_TMCCORR

    这类方法采用模板和图像间的乘法操作,所以较大的数表示匹配程度较高,0 标识最坏的匹配结果。

    R(x,y)=x,,y,(T(x,,y,)I(x+x,,y+y,))R(x,y)=\sum_{x^,,y^,}^{}(T(x^,,y^,)*I(x+x^,,y+y^,))

  4. 归一化相关匹配 method = CV_TM_CCORR_NORMED

    R(x,y)=x,,y,(T(x,,y,)I(x+x,,y+y,))x,,y,T(x,,y,)2x,,y,I(x+x,,y+y,)2R(x,y)=\frac{\sum_{x^,,y^,}^{}(T(x^,,y^,)*I(x+x^,,y+y^,))}{\sqrt{\sum_{x^,,y^,}^{}T(x^,,y^,)^2*\sum_{x^,,y^,}^{}I(x+x^,,y+y^,)^2}}

  5. 相关系数匹配 method = CV_TM_CCOEFF

    这类方法将模板对其均值的相对值与图像对其均值的相关值进行匹配,1 表示完美匹配,-1 表示糟糕的匹配,0 表示没有任何相关性。

    R(x,y)=x,,y,(T,(x,,y,)I,(x+x,,y+y,))R(x,y)=\sum_{x^,,y^,}^{}(T^,(x^,,y^,)*I^,(x+x^,,y+y^,))

    其中

    T,(x,,y,)=T(x,,y,)1(wh)x,,,y,,I(x+x,,,y+y,,)T^,(x^,,y^,)=T(x^,,y^,)-\frac{1}{(w*h)*\sum_{x^{,,},y^{,,}}^{}I(x+x^{,,},y+y^{,,})}

    I,(x+x,,y+y,)=I(x+x,,y+y,)1(wh)x,,,y,,T(x,,,y,,)I^,(x+x^,,y+y^,)=I(x+x^,,y+y^,)-\frac{1}{(w*h)*\sum_{x^{,,},y^{,,}}^{}T(x^{,,},y^{,,})}

  6. 归一化相关系数匹配 method = CV_TM_CCOEFF_NORMED

    R(x,y)=x,,y,(T(x,,y,)I(x+x,,y+y,))x,,y,T(x,,y,)2x,,y,I(x+x,,y+y,)2R(x,y)=\frac{\sum_{x^,,y^,}^{}(T(x^,,y^,)*I(x+x^,,y+y^,))}{\sqrt{\sum_{x^,,y^,}^{}T(x^,,y^,)^2*\sum_{x^,,y^,}^{}I(x+x^,,y+y^,)^2}}

代码实现

ss

应用

利用模板匹配进行图像拼接

Python 计算机视觉——图像拼接 pufferflip 的博客