蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行六种模板匹配度量、多目标阈值框选与亮度平移鲁棒性实验

PYTHONWindows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。explore-matchtemplate.py
explore-matchtemplate.py158 行
"""Offline OpenCV lab for Ch20: template matching across all 6 similarity metrics."""
import json
import platform

import cv2
import numpy as np


def build_template_and_scene():
    """Create a 28x28 high-contrast template and a 160x220 search image containing two instances."""
    tpl = np.full((28, 28), 40, dtype=np.uint8)
    cv2.rectangle(tpl, (3, 3), (24, 24), 210, 2)
    cv2.circle(tpl, (14, 14), 6, 240, -1)
    cv2.line(tpl, (4, 23), (23, 4), 160, 2)

    # Background with gentle spatial gradient + distractor shapes
    y, x = np.mgrid[0:160, 0:220]
    scene = np.clip(35 + 0.15 * x + 0.12 * y, 0, 255).astype(np.uint8)
    cv2.rectangle(scene, (10, 110), (55, 145), 140, -1)
    cv2.circle(scene, (185, 35), 18, 120, -1)

    # Stamp exact copy at (x=45, y=35)
    scene[35:35 + 28, 45:45 + 28] = tpl
    # Stamp brightness-shifted copy (+15) at (x=140, y=95)
    tpl_bright = np.clip(tpl.astype(np.int16) + 15, 0, 255).astype(np.uint8)
    scene[95:95 + 28, 140:140 + 28] = tpl_bright
    return scene, tpl


def run_cases():
    cases = []
    scene, tpl = build_template_and_scene()
    h, w = tpl.shape  # w, h = tpl.shape[::-1]
    exp_res_shape = [scene.shape[0] - h + 1, scene.shape[1] - w + 1]  # [133, 193]

    # Case 1: Compare all 6 OpenCV template matching methods via minMaxLoc
    methods = [
        ("TM_SQDIFF", cv2.TM_SQDIFF, True),
        ("TM_SQDIFF_NORMED", cv2.TM_SQDIFF_NORMED, True),
        ("TM_CCORR", cv2.TM_CCORR, False),
        ("TM_CCORR_NORMED", cv2.TM_CCORR_NORMED, False),
        ("TM_CCOEFF", cv2.TM_CCOEFF, False),
        ("TM_CCOEFF_NORMED", cv2.TM_CCOEFF_NORMED, False),
    ]
    method_results = {}
    all_hit_exact = True
    res_shape_ok = True
    for name, flag, use_min in methods:
        res = cv2.matchTemplate(scene, tpl, flag)
        if list(res.shape) != exp_res_shape:
            res_shape_ok = False
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        best_loc = list(min_loc if use_min else max_loc)
        best_score = round(float(min_val if use_min else max_val), 6)
        method_results[name] = dict(best_loc=best_loc, best_score=best_score)
        # Both (45, 35) exact copy and (140, 95) +15 additive copy are valid template instances;
        # SQDIFF/CCORR_NORMED peak strictly at (45, 35), while zero-mean CCOEFF_NORMED scores ~1.0 at both.
        if name in ("TM_SQDIFF", "TM_SQDIFF_NORMED", "TM_CCORR_NORMED") and best_loc != [45, 35]:
            all_hit_exact = False
        if name in ("TM_CCORR", "TM_CCOEFF", "TM_CCOEFF_NORMED") and best_loc not in ([45, 35], [140, 95]):
            all_hit_exact = False

    c1_ok = res_shape_ok and all_hit_exact
    cases.append(dict(
        name="all_six_matching_methods",
        inputs=dict(scene_shape=[160, 220], template_shape=[28, 28], exact_pos=[45, 35], bright_pos=[140, 95]),
        prerequisites="160×220 含渐变背景与两处目标((45,35) 原版与 (140,95) 增亮 +15 版)的灰度搜索图及 28×28 模板",
        action="遍历全部 6 种 cv2.matchTemplate() 算法并调用 cv2.minMaxLoc(),核对结果矩阵尺寸 (133×193) 与最佳匹配坐标。",
        expected=dict(
            result_matrix_shape=[133, 193],
            sqdiff_normed_loc=[45, 35],
            ccorr_normed_loc=[45, 35],
            all_methods_valid_target=True,
        ),
        actual=dict(
            result_matrix_shape=exp_res_shape if res_shape_ok else [],
            sqdiff_normed_loc=method_results["TM_SQDIFF_NORMED"]["best_loc"],
            ccorr_normed_loc=method_results["TM_CCORR_NORMED"]["best_loc"],
            all_methods_valid_target=all_hit_exact,
        ),
        measurements=method_results,
        passed=c1_ok,
    ))

    # Case 2: Multi-object thresholding (threshold=0.8) & rectangle marking
    res_ccoeff = cv2.matchTemplate(scene, tpl, cv2.TM_CCOEFF_NORMED)
    loc = np.where(res_ccoeff >= 0.8)
    pts = list(zip(*loc[::-1]))
    # Group nearby hits within 8px to count distinct detected instances
    distinct = []
    for pt in pts:
        if all(abs(pt[0] - d[0]) > 8 or abs(pt[1] - d[1]) > 8 for d in distinct):
            distinct.append([int(pt[0]), int(pt[1])])
    distinct.sort()

    canvas = cv2.cvtColor(scene, cv2.COLOR_GRAY2BGR)
    for x, y in distinct:
        cv2.rectangle(canvas, (x, y), (x + w, y + h), (0, 255, 0), 2)
    green_px = int(np.count_nonzero((canvas[:, :, 1] == 255) & (canvas[:, :, 0] == 0)))
    c2_ok = (distinct == [[45, 35], [140, 95]] and green_px > 200)
    cases.append(dict(
        name="multi_target_threshold_and_draw",
        inputs=dict(method="TM_CCOEFF_NORMED", threshold=0.8),
        prerequisites="TM_CCOEFF_NORMED 相似度矩阵与阈值 0.8",
        action="用 np.where(res >= 0.8) 提取全部匹配位置并合并邻域,再调用 cv2.rectangle() 标注两个目标框。",
        expected=dict(
            distinct_matches=[[45, 35], [140, 95]],
            green_box_pixels_gt_200=True,
        ),
        actual=dict(
            distinct_matches=distinct,
            green_box_pixels_gt_200=green_px > 200,
        ),
        measurements=dict(raw_above_threshold_points=len(pts), green_box_pixels=green_px),
        passed=c2_ok,
    ))

    # Case 3: Brightness-shift robustness: TM_CCOEFF_NORMED vs TM_SQDIFF_NORMED at (140, 95)
    res_sq = cv2.matchTemplate(scene, tpl, cv2.TM_SQDIFF_NORMED)
    ccoeff_at_exact = round(float(res_ccoeff[35, 45]), 6)
    ccoeff_at_bright = round(float(res_ccoeff[95, 140]), 6)
    sq_at_exact = round(float(res_sq[35, 45]), 6)
    sq_at_bright = round(float(res_sq[95, 140]), 6)
    c3_ok = (ccoeff_at_exact > 0.999 and ccoeff_at_bright > 0.99
             and sq_at_exact < 0.001 and sq_at_bright > sq_at_exact + 0.005)
    cases.append(dict(
        name="brightness_shift_invariance",
        inputs=dict(brightness_offset=15, exact_pos=[45, 35], bright_pos=[140, 95]),
        prerequisites="原版目标 (45,35) 与亮度整体 +15 目标 (140,95)",
        action="对比 TM_CCOEFF_NORMED 与 TM_SQDIFF_NORMED 在光照平移处的得分变化,验证零均值归一化相关系数的亮度鲁棒性。",
        expected=dict(
            ccoeff_exact_gt_0999=True,
            ccoeff_bright_gt_099=True,
            sqdiff_exact_lt_0001=True,
            sqdiff_degrades_on_shift=True,
        ),
        actual=dict(
            ccoeff_exact_gt_0999=ccoeff_at_exact > 0.999,
            ccoeff_bright_gt_099=ccoeff_at_bright > 0.99,
            sqdiff_exact_lt_0001=sq_at_exact < 0.001,
            sqdiff_degrades_on_shift=sq_at_bright > sq_at_exact + 0.005,
        ),
        measurements=dict(
            ccoeff_at_exact=ccoeff_at_exact,
            ccoeff_at_bright=ccoeff_at_bright,
            sq_at_exact=sq_at_exact,
            sq_at_bright=sq_at_bright,
        ),
        passed=c3_ok,
    ))

    payload = dict(version=platform.python_version(), opencv=cv2.__version__, cases=cases)
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
本例需在 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。

入口文件:projects/opencv-matchtemplate-lab/explore-matchtemplate.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-matchtemplate.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、OpenCV (opencv-python-headless)、NumPy 2.5.4、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:OpenCV

课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a566.zip

下载课程关联工程包:OpenCV

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a593.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习