单独保存模板匹配 OpenCV Python

Saving Template Matches Individually OpenCV Python

使用 cv2.matchTemplate 我正在使用参考图像 (stampRef.jpg) 并在较大的图像(邮票)中找到多个匹配项。我想将这些找到的匹配项中的每一个保存为它们自己的图像。旋转对我很重要,但不重要。我担心它可能会因为重叠匹配而多次保存同一张图像。我不想要这个。每个独特的比赛我只想要一张图片。我只是不确定如何首先保存它们。任何帮助都会很棒,谢谢。

*更新,我找到了一种使用掩码来减少找到的重叠匹配项数量的方法,所以现在我只需要单独保存这些匹配项。我更新了代码。

import cv2
import numpy as np

img = cv2.imread("stamps.jpg")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
template = cv2.imread('stampRef.jpg',0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)

#Counts the number of found matches, which are currently overlapping
number = np.sum(res >= threshold)
print(number)

count = 0
mask = np.zeros(img.shape[:2], np.uint8)
for pt in zip(*loc[::-1]):
    if mask[pt[1] + h//2, pt[0] + w//2] != 255:
        mask[pt[1]:pt[1]+h, pt[0]:pt[0]+w] = 255
        count += 1
        cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0,255,0), 3)

print ("Number of found matches:", count)
small = cv2.resize(img, (0,0), fx=0.3, fy=0.3)

cv2.imshow('Matches',small)
cv2.waitKey(0) & 0xFF== ord('q')
cv2.destroyAllWindows()

此答案解释了如何将每个匹配项保存为单独的图像。您已经通过找到比赛的坐标完成了艰苦的工作。您可以使用这些坐标裁剪出匹配项并将其保存为 .png:

roi = img[pt[1]:pt[1]+h, pt[0]:pt[0]+w]
cv2.imwrite(+ str(count) + '.png', roi)

这段代码应该放在遍历匹配项的循环中:

count = 0

mask = np.zeros(img.shape[:2], np.uint8)
for pt in zip(*loc[::-1]):
    if mask[pt[1] + h//2, pt[0] + w//2] != 255:
        mask[pt[1]:pt[1]+h, pt[0]:pt[0]+w] = 255
        count += 1
        cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0,255,0), 3)
        roi = img[pt[1]:pt[1]+h, pt[0]:pt[0]+w]
        cv2.imwrite(+ str(count) + '.png', roi)
        cv2.imshow('roi', roi)
        cv2.waitKey()