Python 模板匹配算法:在图像中查找目标区域

本示例代码展示了如何使用 OpenCV 的模板匹配算法在图像中查找目标区域,并返回匹配区域的坐标信息。

def template_matching(img_big, img_small, threshold=0.8, isShow=False):
    '''
    使用模板匹配算法来大图中找小图
    :param img_big: 大图数据    例如:cv2.imread('test2.png')
    :param img_small: 小图数据  例如: cv2.imread('X1.png')
    :param threshold: 匹配度阈值 默认 0.8
    :param isShow: 是否显示结果 默认 False
    :return:  结果坐标列表[]
    '''
    # 读取大图和小图
    if type(img_big) == str:
        img_big = cv2.imread(img_big)
    if type(img_small) == str:
        img_small = cv2.imread(img_small)
    image = img_big
    template = img_small
    # 确保输入图像是二维的
    # if len(image.shape) > 2:
    #     image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # # 确保输入图像是二维的
    # if len(template.shape) > 2:
    #     template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)

    # 获取小图的宽度和高度
    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)
        logger.debug(f"符合区域:{loc[0]},{loc[1]}, {loc[0] + template_width}, {loc[1] + template_height}")
        res_loc.append({"x": loc[0], "y": loc[1], "width": loc[0] + template_width, "height": loc[1] + template_height})

    if isShow:
        if res_loc != []:
            cv2.imshow('Matched Template', image)
            cv2.waitKey(0)
            cv2.destroyAllWindows()
    return res_loc

代码说明:

  1. 函数定义

    • template_matching(img_big, img_small, threshold=0.8, isShow=False):该函数接受四个参数:
      • img_big:大图数据
      • img_small:小图数据
      • threshold:匹配度阈值,默认值为 0.8
      • isShow:是否显示匹配结果,默认值为 False
  2. 读取图片

    • 使用 cv2.imread() 读取大图和小图,并确保输入图像是二维的。
  3. 模板匹配

    • 使用 cv2.matchTemplate() 进行模板匹配,使用 cv2.TM_CCOEFF_NORMED 方法计算匹配度。
  4. 找到匹配结果

    • 使用 np.where() 函数找到匹配度大于阈值的区域,并记录其坐标信息。
  5. 绘制匹配区域

    • 使用 cv2.rectangle() 在大图中绘制匹配区域的矩形框,并输出匹配区域的坐标信息。
  6. 显示匹配结果

    • 使用 cv2.imshow()cv2.waitKey() 显示匹配结果。

注意事项:

  • 确保输入的图像路径正确。
  • 可以根据需要调整匹配度阈值和显示结果参数。
  • 确保绘制矩形框的代码 cv2.rectangle() 中的坐标信息正确,确保匹配区域的坐标信息正确,否则会导致矩形框无法正确绘制。

示例:

img_big = cv2.imread('test2.png')
img_small = cv2.imread('X1.png')
res_loc = template_matching(img_big, img_small, isShow=True)
print(res_loc)

输出结果:

  • 匹配区域的坐标信息列表,例如: [{"x": 100, "y": 200, "width": 300, "height": 400}, ...]

  • 显示匹配结果的图像窗口。

其他:

  • 可以根据需要调整代码以实现更多功能,例如:
    • 使用其他模板匹配方法,例如 cv2.TM_SQDIFF_NORMEDcv2.TM_CCORR_NORMED
    • 在匹配区域内进行其他操作,例如提取特征或进行图像识别。
    • 将匹配结果保存为文件。

总结:

本示例代码展示了如何使用 OpenCV 的模板匹配算法在图像中查找目标区域,并提供了详细的代码注释和示例,希望对您理解和使用模板匹配算法有所帮助。

Python 模板匹配算法:在图像中查找目标区域

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

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