opencv模板匹配

程序有一个匹配的框框重叠的情况,未来可以使用iou做阈值优化一下

 

"""
 -*- coding: utf-8 -*-
 author: Hao Hu
 @date   2022/3/17 3:43 PM
"""
import cv2
import numpy as np

def template_match(ori_img_path):
    ori_img = cv2.imread(ori_img_path)
    img_gray = cv2.cvtColor(ori_img, cv2.COLOR_BGR2GRAY)
    template = img_gray[162:2851,227:1828]
    h, w = template.shape[:2]

    res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
    threshold = 0.9
    # 取匹配程度大于%80的坐标

    loc = np.where(res >= threshold)

    # np.where返回的坐标值(x,y)是(h,w),注意h,w的顺序
    index = 0
    for pt in zip(*loc[::-1]):
        index = index +1
       
        bottom_right = (pt[0] + w, pt[1] + h)
        cv2.rectangle(ori_img, pt, bottom_right, (0, 255, 0), 10)
        # if index ==3:
        #     bottom_right = (pt[0] + w, pt[1] + h)
        #     cv2.rectangle(ori_img, pt, bottom_right, (0, 255, 0), 10)

    #cv2.imwrite("img.jpg", img_rgb)
    cv2.imshow('img', ori_img)
    cv2.waitKey(0)
# 1,14

def show_image(ori_img_path):
    import os
    from PIL import Image
    import matplotlib.pyplot as plt
    img = Image.open(ori_img_path)
    plt.figure("Image")  # 图像窗口名称
    plt.imshow(img)
    plt.show()


if __name__ == '__main__':
    ori_img_path = '/Users/huhao/Downloads/template/png/test3.png'
    template_match(ori_img_path)
    #show_image(ori_img_path)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OpenCV 模板匹配是一种基于模板图像和待匹配图像进行匹配的技术。该技术主要用于在待匹配图像中查找与模板图像相似的区域位置。OpenCV 提供了多种模板匹配算法,包括平方差匹配、归一化平方差匹配、相关性匹配和归一化相关性匹配等。 模板匹配的基本流程如下: 1. 加载待匹配图像和模板图像 2. 对模板图像进行预处理,如灰度化、二值化等操作 3. 使用模板图像在待匹配图像中进行滑动窗口搜索,计算匹配度 4. 根据匹配度确定匹配位置 5. 绘制匹配结果或输出匹配位置信息 以下是一个基于归一化平方差匹配的模板匹配示例代码: ```python import cv2 import numpy as np # 加载待匹配图像和模板图像 img = cv2.imread('test.jpg') template = cv2.imread('template.jpg') # 对模板图像进行灰度化和二值化处理 template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY) _, template_thresh = cv2.threshold(template_gray, 0, 255, cv2.THRESH_BINARY) # 获取模板图像大小 h, w = template_thresh.shape[:2] # 使用归一化平方差匹配算法进行模板匹配 res = cv2.matchTemplate(img, template_thresh, cv2.TM_SQDIFF_NORMED) # 获取匹配位置 min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) top_left = min_loc bottom_right = (top_left[0] + w, top_left[1] + h) # 绘制匹配结果 cv2.rectangle(img, top_left, bottom_right, (0, 0, 255), 2) # 显示匹配结果 cv2.imshow('Match result', img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 在上述代码中,我们首先加载了待匹配图像和模板图像,并对模板图像进行了灰度化和二值化处理。然后使用 `cv2.matchTemplate()` 函数进行模板匹配,并获取匹配位置。最后使用 `cv2.rectangle()` 函数绘制匹配结果,并展示出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值