模糊匹配 是一种用于较大图像中搜索和查找模板图像位置的方法

    1. import cv2 as cv
    2. import numpy as np
    3. from matplotlib import pyplot as plot
    4. # 单匹配方式
    5. def mathTemplate():
    6. # 读取图片
    7. img = cv.imread("images/tg.jpg", 0)
    8. # 复制图片
    9. img2 = img.copy()
    10. template = cv.imread("images/mb.png", 0)
    11. width, height = template.shape[:2]
    12. # 列表中所有的6种比较方法
    13. methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR',
    14. 'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']
    15. for meth in methods:
    16. img = img2.copy()
    17. method = eval(meth)
    18. # 应用模板匹配
    19. res = cv.matchTemplate(img, template, method)
    20. # minMaxLoc寻找矩阵中最大和最小的位置
    21. min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
    22. if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:
    23. top_left = max_loc
    24. else:
    25. top_left = max_loc
    26. bottom_right = (top_left[0] + width, top_left[1] + height)
    27. # 在图片上面绘制矩形边框
    28. cv.rectangle(img, top_left, bottom_right, 255, 3)
    29. plot.xticks([]), plot.yticks([])
    30. plot.subplot(122), plot.imshow(img, cmap='gray')
    31. plot.xticks([]), plot.yticks([])
    32. plot.suptitle(meth)
    33. plot.show()
    34. # 多匹配方式
    35. def matchMore():
    36. # 读取图片
    37. img_rgb = cv.imread('mario.png')
    38. # 转换颜色为灰色
    39. img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
    40. template = cv.imread('mario_coin.png', 0)
    41. # 获取款跟高
    42. w, h = template.shape[::-1]
    43. # 匹配模板 采用TM_CCOEFF_NORMED
    44. res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED)
    45. threshold = 0.8
    46. loc = np.where(res >= threshold)
    47. for pt in zip(*loc[::-1]):
    48. # 绘画方框
    49. cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
    50. cv.imwrite('res.png', img_rgb)
    51. if __name__ == '__main__':
    52. mathTemplate()