opencv 找金币,按照金字塔缩小尝试匹配

# Author:Winter Liu is coming!
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt


def match_demo(src1, src2):
    res = cv.matchTemplate(src2, src1, cv.TM_CCOEFF_NORMED)
    # res = cv.matchTemplate(src2, src1, cv.TM_SQDIFF_NORMED)
    # min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
    pt = np.where(res > 0.5)
    h, w, c = src1.shape
    print(len(pt[0]))
    # print(max_val)
    # print(max_loc)
    # cv.rectangle(src2,max_loc, (max_loc[0]+h, max_loc[1]+w), (0, 0, 255), 2)
    a = [(-1, -1)]
    p_zip = zip(pt[1], pt[0])
    p_n = sorted(p_zip, key=lambda x: x[0], reverse=False)
    for p in p_n:
        # print(p)
        if abs(a[-1][0] - p[0]) > 10 or abs(a[-1][1] - p[1]) > 10:
            print(p)
            cv.rectangle(src2, p, (p[0]+w, p[1]+h), (0, 0, 255), 2)
            a.append(p)
    cv.imshow("src2", src2)
    cv.waitKey(0)
    cv.destroyWindow("src2")


src1 = cv.imread(r"C:\PycharmProjects\OpenCV\pic\super_maria_coin.jpg")
src2 = cv.imread(r"C:\PycharmProjects\OpenCV\pic\super_maria.jpg")
match_demo(src1, src2)
down = src1.copy()
for i in range(4):
    down = cv.pyrDown(down)
    cv.imshow("down", down)
    cv.waitKey(0)
    cv.destroyWindow("down")
    match_demo(down, src2)

相关推荐