def template_matching(img_big, img_small, threshold=0.8):
    # 读取大图和小图
    image = img_big
    template = img_small
    # 获取小图的宽度和高度
    template_width, template_height = template.shape[:2]

    # 使用模板匹配方法
    result = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)

    # 使用np.where()函数找到匹配结果
    locations = np.where(result >= threshold)
    res_loc=[]
    # 在大图中标记匹配的小图
    for loc in zip(*locations[::-1]):#列表进行反转,然后通过解包的方式传递给 zip() 函数
        cv2.rectangle(image, loc, (loc[0] + template_width, loc[1] + template_height), (0, 255, 0), 2)
        print('识别区域',loc[0],loc[1], loc[0] + template_width, loc[1] + template_height)
        res_loc.append({'x':loc[0],'y':loc[1],'width':template_width,'height':template_height})

    return res_loc

该代码使用 cv2.matchTemplate 函数进行模板匹配,通过设置阈值 threshold 来过滤匹配结果,并返回所有匹配到的区域坐标信息。代码中使用了 np.where 函数来获取匹配结果的位置,并使用 zip 函数将坐标信息解包。

代码中使用了 cv2.rectangle 函数在原图上标记匹配区域。res_loc 列表存储了每个匹配区域的坐标信息,包括 xywidthheight

注意:

  • 确保输入的 img_bigimg_small 是 OpenCV 支持的图像格式,例如 numpy 数组。
  • threshold 值可以根据实际情况进行调整,值越高,匹配结果越严格。

示例:

import cv2
import numpy as np

# 读取大图和小图
img_big = cv2.imread('big.jpg')
img_small = cv2.imread('small.jpg')

# 进行模板匹配
res_loc = template_matching(img_big, img_small)

# 打印匹配结果
for loc in res_loc:
    print(f'匹配区域坐标:x={loc['x']}, y={loc['y']}, width={loc['width']}, height={loc['height']}')
Python OpenCV 模板匹配识别:使用 `cv2.matchTemplate` 定位图像

原文地址: https://www.cveoy.top/t/topic/qAcp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录