You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python OpenCV模板匹配:已实现功能及官方示例代码说明

Template Matching Implementation Walkthrough & Experience

Hey everyone, I’ve spent some time working with Template Matching recently—got a clear understanding of how it works, built an implementation tailored to my use case, and it’s running flawlessly!

Here’s the official sample code from the OpenCV documentation that served as the foundation for my work:

import cv2 as cv
import numpy as np

# Load the source RGB image and convert to grayscale
img_rgb = cv.imread('mario.png')
img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)

# Load the template image directly in grayscale mode
template = cv.imread('mario_coin.png', 0)
w, h = template.shape[::-1]  # Extract template width and height (reverse shape to get w,h)

# Execute template matching with normalized coefficient method
res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED)

# Define a threshold to filter out low-confidence matches
threshold = 0.8
loc = np.where(res >= threshold)

# Iterate over all detected match positions (replace ... with your logic, like drawing boxes)
for pt in zip(*loc[::-1]):
    # Example code to draw a red bounding box around matches:
    # cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
    pass

A few key takeaways from my implementation process:

  • Grayscale conversion is crucial here—it cuts down on computational load and eliminates color-related inconsistencies that could throw off matching.
  • cv.TM_CCOEFF_NORMED was my go-to matching method because it normalizes results, making the threshold value more reliable across different lighting conditions.
  • The zip(*loc[::-1]) step rearranges the numpy array coordinates to fit OpenCV’s (x, y) coordinate system, which is essential if you plan to draw bounding boxes or interact with the matched regions.

内容的提问来源于stack exchange,提问作者diatomym

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:29:27