# 模板匹配

模板匹配是一种计算机视觉技术：它用一张小的参考图像（即模板）在更大的图像中定位其出现的位置，方法是给模板与每一个同尺寸图像区域的相似度打分。其输出是一张响应图：对于尺寸为 W×H 的图像和尺寸为 w×h 的模板，OpenCV 的 matchTemplate 返回尺寸为 (W−w+1, H−h+1) 的结果，其中每个元素衡量模板在该位置的匹配程度。<sup>[1](https://docs.opencv.org/5.0/tutorials/imgproc/histograms/template_matching/template_matching.html)</sup> scikit-image 的 match_template 计算的是同一个量，即归一化相关，输出值介于 −1.0 与 1.0 之间。<sup>[2](https://github.com/scikit-image/scikit-image/blob/v0.14.3/skimage/feature/template.py)</sup> 由于它无需训练、仅凭用户提供的单个模板即可工作，在无法对每个物体类别进行离线学习的场合更受青睐 <sup>[3](https://pmc.ncbi.nlm.nih.gov/articles/PMC8706661/)</sup>；在制造业中，它被用来估计零件的位姿，以支持机器人抓取等下游任务。<sup>[4](https://doi.org/10.1007/s41095-023-0333-9)</sup>

| 属性 | 取值 |
|---|---|
| 输出 | 尺寸为 (W−w+1, H−h+1) 的响应图；最佳匹配用 minMaxLoc 求得，多处匹配用阈值化求得（例如在 TM_CCOEFF_NORMED 下取 res ≥ 0.8）<sup>[1](https://docs.opencv.org/5.0/tutorials/imgproc/histograms/template_matching/template_matching.html)</sup> |
| 暴力计算代价 | 对 M×N 图像与 m×n 模板为 \( O(m \cdot n \cdot M \cdot N) \) <sup>[5](https://mail.idosi.org/wasj/wasj33%283%2915/9.pdf)</sup> |
| NCC 取值范围 | −1 到 1；对全局亮度变化不变；相同图像得分为 1.0，图像与其反相得分为 −1.0 <sup>[6](https://docs.fab-image.com/4.11/studio/machine_vision_guide/TemplateMatching.html)</sup> |
| 实测精度 | 一项对五种模板匹配算法的实证研究发现，NCC 在所有测试的图像类别中表现最佳 <sup>[7](https://scribblethink.org/Work/nvisionInterface/nip.html)</sup> |
| 鲁棒性限制 | 当旋转超过约 20° 或尺度差异超过 30% 时，质量显著下降 <sup>[8](https://www.ipb.uni-bonn.de/html/teaching/photo12-2021/2021-pho1-09-matching-cc.pptx.pdf)</sup> |
| FFT 加速 | 完全在傅里叶域求值比空域相关快一到两个数量级 <sup>[9](https://imagemagick.org/docs/AcceleratedTemplateMatchingUsingLocalStatisticsAndFourierTransforms.pdf)</sup> |
| 三维旋转精度 | 在 960×928×230 体素的断层图上，张量模板匹配达到 0.3° 以下，而采样旋转匹配为 4° 至 13° <sup>[10](https://arxiv.org/abs/2408.02398)</sup> |

## 工作原理

模板 T 被放置在图像 I 的每一个偏移 (x, y) 处，并计算 T 与其下方 w×h 窗口之间的相似度或距离得分。该模型假定二者仅相差平移、亮度与对比度。<sup>[8](https://www.ipb.uni-bonn.de/html/teaching/photo12-2021/2021-pho1-09-matching-cc.pptx.pdf)</sup> 常用的距离度量包括差值平方和（SSD），

\[ R(x,y)=\sum_{x',y'}\left(T(x',y')-I(x+x',y+y')\right)^{2} \]

以及绝对差值和（SAD）；两者都不具备对亮度或对比度变化的不变性。<sup>[1](https://docs.opencv.org/5.0/tutorials/imgproc/histograms/template_matching/template_matching.html)</sup> [归一化](https://www.edgepedia.org/zh/normalization)互相关（NCC）通过用特征均值与局部图像均值把图像向量和特征向量归一化为单位长度来解决这一问题，从而得到类似余弦的相关系数。<sup>[7](https://scribblethink.org/Work/nvisionInterface/nip.html)</sup> 其取值范围为 −1 到 1，当滤波器与图像区域在相差一个比例因子的意义下相同时取 1；只有当被比较的向量经均值中心化并归一化（或具有固定且相等的范数）之后，最小化平方距离才等价于最大化归一化相关，因此原始的 SSD 与 NCC 一般并不等价。<sup>[11](https://www.cs.ubc.ca/~aerion1/425_2025W2/Lecture7.pdf)</sup> 在响应峰值附近拟合二次曲面，可获得约 1/10 像素的亚像素精度。<sup>[8](https://www.ipb.uni-bonn.de/html/teaching/photo12-2021/2021-pho1-09-matching-cc.pptx.pdf)</sup>

## 实现方法

实践中步骤是：选定模板与一种度量；让模板在图像上滑动；记录每个偏移处的得分；再定位峰值。OpenCV 提供六种方法：TM_SQDIFF、TM_SQDIFF_NORMED、TM_CCORR、TM_CCORR_NORMED、TM_CCOEFF 与 TM_CCOEFF_NORMED。对 TM_SQDIFF 与 TM_SQDIFF_NORMED，最小值即最佳匹配；对其余方法，最大值最佳。只有 TM_SQDIFF 与 TM_CCORR_NORMED 接受掩膜，掩膜尺寸须与模板一致，深度为 CV_8U 或 CV_32F。<sup>[1](https://docs.opencv.org/5.0/tutorials/imgproc/histograms/template_matching/template_matching.html)</sup> 若存在多处匹配，minMaxLoc 不够用；做法是对结果做阈值化，保留既高于阈值又在局部取极大的位置。<sup>[1](https://docs.opencv.org/5.0/tutorials/imgproc/histograms/template_matching/template_matching.html)</sup><sup> • </sup><sup>[6](https://docs.fab-image.com/4.11/studio/machine_vision_guide/TemplateMatching.html)</sup>

暴力扫描的代价为 \( O(m \cdot n \cdot M \cdot N) \)。<sup>[5](https://mail.idosi.org/wasj/wasj33%283%2915/9.pdf)</sup> 用 \( s(u,v)=f(u,v)+s(u-1,v)+s(u,v-1)-s(u-1,v-1) \) 构建的累加和（积分图）约需 \( 3 \cdot M^{2} \) 次运算，而直接计算局部均值与能量约需 \( 3 \cdot N^{2} \cdot (M-N+1)^{2} \) 次。<sup>[7](https://scribblethink.org/Work/nvisionInterface/nip.html)</sup> 傅里叶域求值比空域相关快一到两个数量级，且其运行时间与模板尺寸无关（一张 500×500 的图像，模板从 10×10 到 450×450）。<sup>[9](https://imagemagick.org/docs/AcceleratedTemplateMatchingUsingLocalStatisticsAndFourierTransforms.pdf)</sup> 已发表的比较研究对于最佳方案划分意见不一：一项研究发现，在所测试的数据集上，完全在变换域计算 NCC 并不比优化的混合算法（分子在傅里叶域计算、分母用求和表计算）更快。<sup>[12](https://pmc.ncbi.nlm.nih.gov/articles/PMC6147431/)</sup> 有界部分相关是 Mattoccia（马托恰）与 Di Stefano（迪斯特凡诺）于 2003 年在《机器视觉与应用》上提出的一种用于 NCC 的快速模板匹配方法。<sup>[13](https://doi.org/10.1007/s00138-002-0070-5)</sup> 金字塔搜索构建高斯金字塔，并在每个尺度上与模板卷积；由图像构建金字塔而非缩放模板，速度快 50 倍以上。<sup>[11](https://www.cs.ubc.ca/~aerion1/425_2025W2/Lecture7.pdf)</sup>

## 起源

模板匹配的根源在于光学相关。光学手段可以对图案进行二维卷积与相关运算，用于模式识别以及度量两个图案的相似性；它定义了互相关函数 \( A(u,v)=\frac{1}{ab}\int_{0}^{a}\int_{0}^{b}\rho(x,y)\rho'(x+u,y+v)\,dx\,dy \) 以及一个“相似性”函数 \( S(\rho\rho')=\frac{1}{ab}\int_{0}^{a}\int_{0}^{b}A^{2}(u,v)\,du\,dv \)，对相同图案取最大值。<sup>[14](https://opg.optica.org/josa/abstract.cfm?uri=josa-52-4-454)</sup> 同时具有振幅与相位响应的空间滤波器可以记录在普通照相胶片上，用于光学模式识别；2012 年的一篇综述纪念了这一匹配滤波器表述提出 50 周年，它构成了基于相关的模式识别的基础。<sup>[15](https://garfield.library.upenn.edu/classics1979/A1979HZ20500001.pdf)</sup><sup> • </sup><sup>[16](https://iopscience.iop.org/article/10.1088/2040-8978/14/10/103001)</sup> 用模板扫描含噪数据、在每个数据点计算互相关系数，并合并为“识别指数”（当两个相关系数均为正时取二者之积），这一方法在 PDP-12 计算机上实现。<sup>[17](https://www.nature.com/articles/238292a0.pdf)</sup>

随后出现了数字化的加速方法：Nagel（内格尔）与 Rosenfeld（罗森菲尔德）发表了模板匹配中的有序搜索技术（《IEEE 会刊》，1972）<sup>[18](https://doi.org/10.1109/proc.1972.8611)</sup>；Barnea（巴尼亚）与 Silverman（西尔弗曼）1972 年的论文提出了一类快速数字图像配准算法 <sup>[19](https://doi.org/10.1109/tc.1972.5008923)</sup>；Fischler（菲施勒）与 Elschlager（埃尔施拉格）1973 年关于图像结构匹配的论文提出了一种线性嵌入算法，其存储量与计算时间随参考分量的数目线性增长而非指数增长 <sup>[20](https://doi.org/10.1109/t-c.1973.223602)</sup>；Vanderbrug（范德布鲁格）与 Rosenfeld 于 1977 年发表了两级模板匹配 <sup>[21](https://doi.org/10.1109/tc.1977.1674847)</sup>；Crow（克罗）1984 年的 SIGGRAPH 论文提出了用于纹理映射的求和面积表 <sup>[22](https://doi.org/10.1145/964965.808600)</sup>；Goshtasby（戈什塔斯比）、Gage（盖奇）与 Bartholic（巴索利克）于 1984 年发表了用于模板匹配的两级互相关方法。<sup>[23](https://doi.org/10.1109/tpami.1984.4767532)</sup> 1976 年的一篇综述将模板匹配描述为一种计算代价高昂的过程，并已为此发展出多种降低代价的技术。<sup>[24](https://www.computer.org/csdl/api/v1/periodical/trans/tc/1976/12/01674602/13rRUwfI0OQ/download-article/pdf)</sup>

## 变体

除单纯的灰度相关之外，还有若干类方法。基于 FFT 的 NCC 与金字塔由粗到细搜索即上文所述的经典加速手段。针对遮挡与形变，可变形多样性相似度（DDIS）对目标窗口与模板之间最近邻特征匹配的多样性进行评分，其设计目标是对复杂形变、背景杂乱和遮挡具有鲁棒性。<sup>[25](https://ar5iv.labs.arxiv.org/html/1612.02190)</sup> 对于三维情形，来自视觉传感器的深度模板可在匹配前针对三维方向与尺寸差异对模板进行校准，这是一种无需训练或递归的闭式解。<sup>[3](https://pmc.ncbi.nlm.nih.gov/articles/PMC8706661/)</sup> 基于边缘的匹配比较边缘处的梯度方向；对绝大多数应用而言，它比基于灰度的匹配既更鲁棒也更高效。<sup>[6](https://docs.fab-image.com/4.11/studio/machine_vision_guide/TemplateMatching.html)</sup> 张量模板匹配（TTM）将模板的所有旋转整合为一个对称张量场，每个模板只计算一次，使计算复杂度与角度精度无关 <sup>[10](https://arxiv.org/abs/2408.02398)</sup>；其基础理论表明，与对称张量模板各独立分量做相关，即可在不对 SO(3) 采样的前提下恢复位置与旋转；对于 \( \mathbb{R}^{4} \) 上的四阶张量，独立分量有 35 个。<sup>[26](https://link.springer.com/article/10.1007/s12190-024-02157-6)</sup> 相关的快速相关工作还包括罗建文（Jianwen Luo）与埃莉萨·E·科诺法古（Elisa E Konofagou）2010 年提出的一种用于运动估计的快速 NCC 计算方法 <sup>[27](https://doi.org/10.1109/tuffc.2010.1554)</sup>，以及艾伦·M·罗斯曼（Alan M Roseman）2003 年提出的用于在电子显微图中寻找颗粒的快速局部相关算法。<sup>[28](https://doi.org/10.1016/s0304-3991%2802%2900333-9)</sup>

## 应用

在制造业中，模板匹配估计零件的位姿，便于机器人抓取等下游任务 <sup>[4](https://doi.org/10.1007/s41095-023-0333-9)</sup>；当检测必须使用用户提供的单个模板、且无法对每个物体类别进行离线学习时，它更受青睐。<sup>[3](https://pmc.ncbi.nlm.nih.gov/articles/PMC8706661/)</sup> 在医学成像中，用 FFT 计算的 NCC 已在 MRI 数据上得到演示：一个一维刚性体模位移的例子恢复出的位移与扫描仪标志点测量值一致，一个二维肠道运动追踪案例达到的最大 NCC 为 0.67。<sup>[12](https://pmc.ncbi.nlm.nih.gov/articles/PMC6147431/)</sup> 在结构生物学中，快速局部相关用于在电子显微图中寻找颗粒。<sup>[28](https://doi.org/10.1016/s0304-3991%2802%2900333-9)</sup>

## 局限与替代方法

模板匹配在存在噪声时表现良好，计算也相对容易，但对空间尺度变化、二维旋转、观察方向与位姿、光照条件以及部分遮挡都很敏感。<sup>[11](https://www.cs.ubc.ca/~aerion1/425_2025W2/Lecture7.pdf)</sup> 当旋转超过约 20° 或尺度差异超过 30% 时，质量显著下降。<sup>[8](https://www.ipb.uni-bonn.de/html/teaching/photo12-2021/2021-pho1-09-matching-cc.pptx.pdf)</sup> SSD、SAD 与 NCC 这类逐像素度量假定模板与目标之间只有平移，并对所有模板像素施加惩罚，因此在遮挡或大形变下会产生误检。<sup>[25](https://ar5iv.labs.arxiv.org/html/1612.02190)</sup> 归一化很重要：在 OpenCV 的教程中，未归一化的 CCORR 与 CCOEFF 给出了错误的最佳匹配，而其归一化版本找到了正确位置 <sup>[1](https://docs.opencv.org/5.0/tutorials/imgproc/histograms/template_matching/template_matching.html)</sup>；近似加速方案还可能产生误报，其比率取决于噪声水平。<sup>[12](https://pmc.ncbi.nlm.nih.gov/articles/PMC6147431/)</sup> 与学习方法相关的应用情境还暴露出更多失效情形：当模板与源图模态不同，或背景杂乱、纹理微弱时，现有方法便难以应对。<sup>[4](https://doi.org/10.1007/s41095-023-0333-9)</sup>

作为替代方案，SIFT 描述子对图像平移、旋转与缩放不变，且对轻微视点变化、噪声、模糊与对比度变化鲁棒 <sup>[29](https://www.ipol.im/pub/art/2014/82/article.pdf)</sup>；一篇 2025 年对 15 种局部特征匹配方法的综述发现，基于学习的方法在光照与雾天条件下表现称职，但在雨天场景下、在低像素误差阈值上手工方法更好，而在剔除离群点之后差距并不显著。<sup>[30](https://link.springer.com/article/10.1007/s00371-025-04278-w)</sup> 在基于学习的模板匹配方法中，TDCM 将模板特征编码为逐通道卷积核，作用于搜索图像的特征，从而无需穷举角度即可实现端到端的位姿感知匹配，并估计旋转与各向异性尺度 <sup>[31](https://arxiv.org/html/2510.01678v1)</sup>；2024 年的一种方法将边缘感知模块与基于 Transformer 的粗对应以及一个可微细化网络相结合，由后者产生亚像素对应以求得最终单应性。<sup>[4](https://doi.org/10.1007/s41095-023-0333-9)</sup>

## References

1. [Template Matching, OpenCV Tutorials (5.0; content merged with 4.5.3/4.7.0 tutorial pages)](https://docs.opencv.org/5.0/tutorials/imgproc/histograms/template_matching/template_matching.html)
2. [skimage.feature.match_template source (normalized correlation via FFT)](https://github.com/scikit-image/scikit-image/blob/v0.14.3/skimage/feature/template.py)
3. [Reliable Template Matching for Image Detection in Vision Sensor Systems](https://pmc.ncbi.nlm.nih.gov/articles/PMC8706661/)
4. [Zhirui Gao and colleagues (2024). Learning accurate template matching with differentiable coarse-to-fine correspondence refinement. Computational Visual Media.](https://doi.org/10.1007/s41095-023-0333-9)
5. [mail.idosi.org](https://mail.idosi.org/wasj/wasj33%283%2915/9.pdf)
6. [Template Matching (FabImage Studio machine vision guide)](https://docs.fab-image.com/4.11/studio/machine_vision_guide/TemplateMatching.html)
7. [Fast Normalized Cross-Correlation (J. P. Lewis)](https://scribblethink.org/Work/nvisionInterface/nip.html)
8. [Image Template Matching Using Cross Correlation (Cyrill Stachniss, Photogrammetry & Robotics Lab)](https://www.ipb.uni-bonn.de/html/teaching/photo12-2021/2021-pho1-09-matching-cc.pptx.pdf)
9. [Accelerated Template Matching Using Local Statistics and Fourier Transforms](https://imagemagick.org/docs/AcceleratedTemplateMatchingUsingLocalStatisticsAndFourierTransforms.pdf)
10. [Tensorial template matching for fast cross-correlation with rotations and its application for tomography](https://arxiv.org/abs/2408.02398)
11. [CPSC 425 Lecture 7: Template Matching and Normalized Correlation (UBC)](https://www.cs.ubc.ca/~aerion1/425_2025W2/Lecture7.pdf)
12. [Computation of the normalized cross-correlation by fast Fourier transform](https://pmc.ncbi.nlm.nih.gov/articles/PMC6147431/)
13. [Stefano Mattoccia, Luigi Di Stefano (2003). Fast template matching using bounded partial correlation. Machine Vision and Applications.](https://doi.org/10.1007/s00138-002-0070-5)
14. [The Role of Optics in Applying Correlation Functions to Pattern Recognition (Dan McLachlan, Jr., JOSA 52(4), 1962)](https://opg.optica.org/josa/abstract.cfm?uri=josa-52-4-454)
15. [This Week's Citation Classic: VanderLugt A. Signal detection by complex spatial filtering. IEEE Transactions on Information Theory, 10(2), 139–145 (1964)](https://garfield.library.upenn.edu/classics1979/A1979HZ20500001.pdf)
16. [Advanced optical correlation and digital methods for pattern matching, 50th anniversary of Vander Lugt matched filter (Millán, J. Opt. 14, 103001, 2012)](https://iopscience.iop.org/article/10.1088/2040-8978/14/10/103001)
17. [The Use of Correlational Analysis for Pattern Recognition (Weinberg & Cooper, Nature 238:292, August 4, 1972)](https://www.nature.com/articles/238292a0.pdf)
18. [R.N. Nagel, A. Rosenfeld (1972). Ordered search techniques in template matching. Proceedings of the IEEE.](https://doi.org/10.1109/proc.1972.8611)
19. [Daniel I. Barnea, Harvey F. Silverman (1972). A Class of Algorithms for Fast Digital Image Registration. IEEE Transactions on Computers.](https://doi.org/10.1109/tc.1972.5008923)
20. [M.A. Fischler, R.A. Elschlager (1973). The Representation and Matching of Pictorial Structures. IEEE Transactions on Computers.](https://doi.org/10.1109/t-c.1973.223602)
21. [Vanderbrug, Rosenfeld (1977). Two-Stage Template Matching. IEEE Transactions on Computers.](https://doi.org/10.1109/tc.1977.1674847)
22. [Franklin C. Crow (1984). Summed-area tables for texture mapping. ACM SIGGRAPH Computer Graphics.](https://doi.org/10.1145/964965.808600)
23. [A. Goshtasby, S. H. Gage, J. F. Bartholic (1984). A Two-Stage Cross Correlation Approach to Template Matching. IEEE Transactions on Pattern Analysis and Machine Intelligence.](https://doi.org/10.1109/tpami.1984.4767532)
24. [Rosenfeld's survey paper on pattern recognition/image processing techniques (IEEE Trans. Computers, 1976)](https://www.computer.org/csdl/api/v1/periodical/trans/tc/1976/12/01674602/13rRUwfI0OQ/download-article/pdf)
25. [Template Matching with Deformable Diversity Similarity (DDIS)](https://ar5iv.labs.arxiv.org/html/1612.02190)
26. [Fast normalized cross-correlation for template matching with rotations](https://link.springer.com/article/10.1007/s12190-024-02157-6)
27. [Jianwen Luo, Elisa E Konofagou (2010). A fast normalized cross-correlation calculation method for motion estimation. IEEE Transactions on Ultrasonics Ferroelectrics and Frequency Control.](https://doi.org/10.1109/tuffc.2010.1554)
28. [Particle finding in electron micrographs using a fast local correlation algorithm (Ultramicroscopy, 2003)](https://doi.org/10.1016/s0304-3991%2802%2900333-9)
29. [Anatomy of the SIFT Method](https://www.ipol.im/pub/art/2014/82/article.pdf)
30. [Local feature-based image matching: a comprehensive review and robustness evaluation](https://link.springer.com/article/10.1007/s00371-025-04278-w)
31. [An Efficient Deep Template Matching and In-Plane Pose Estimation Method via Template-Aware Dynamic Convolution](https://arxiv.org/html/2510.01678v1)

---
*Initially written Sep 29, 2026 · Edited: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 人工智能与数据 › Language and vision AI › Computer vision › Vision methods and geometry › Recognition and matching methods

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/template-matching

English original: https://www.edgepedia.org/template-matching
