python - 单独保存模板匹配 OpenCV Python
问题描述
使用 cv2.matchTemplate 我正在使用参考图像(stampRef.jpg)并在更大的图像(邮票)中找到多个匹配项。我想将每个找到的匹配项保存为他们自己的图像。旋转对我来说很重要,但不是规模。我担心它可能会因为重叠匹配而多次保存同一张图像。我不想要这个。我只想要每个独特匹配的 1 张图片。我只是不确定如何首先保存它们。任何帮助都会很棒,谢谢。
*更新,我找到了一种方法来通过使用掩码减少找到的重叠匹配的数量,所以现在我需要单独保存这些匹配。我已经更新了代码。
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()
推荐阅读
- django - 如何解决我的 Django 项目中的完整性错误
- docker - 为什么 kubernetes pod 无法运行 docker image
- javascript - 标题中的 ReactNativeElements 按钮在 iPhone 上不可点击。(剩下)
- html - 在 R Viewer 中显示多个 DT 表
- c# - 如何将实际的 ConfigurationSection 保存到给定的文件中?
- php - 如何比较相同元素(输入文本字段)的值并删除重复项(如果存在)?
- c# - wpf xaml island 无法在视图之间导航
- arrays - 如何将这些值添加到数组中?
- swift - 为什么我的 NSMenuItem 在有操作时被禁用?
- fonts - UFO 字体中的字形点是如何给出的?