python模板匹配的掩膜图像无法匹配原图
用的是python3,cv2
代码如下:import cv2
import cv2
import numpy as np
#读取原始图像及模板图像
image = cv2.imread('image01/v111.png')
template = cv2.imread('image01/v123.png')
#制作模板图像的掩膜
w, h = template.shape[:2]
mask = np.zeros((w, h), dtype=np.uint8)
mask[15:40, 15:60] = 255
#生成掩膜图像
result = cv2.bitwise_and(template, template, mask=mask)
#掩膜图像匹配原图
res= cv2.matchTemplate(image, result, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
print(max_val)
top_left = max_loc
bottom_right = (top_left[0] + template.shape[1], top_left[1] + template.shape[0])
cv2.rectangle(image, top_left, bottom_right, (0, 0, 255), 2)
cv2.imshow('Matching3 Result', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
直接用模板图像匹配就行res= cv2.matchTemplate(image, template , cv2.TM_CCOEFF_NORMED)
但是想用res= cv2.matchTemplate(image, result , cv2.TM_CCOEFF_NORMED)模板图像的掩膜图像匹配就无法正确匹配了,
想知道如何才能做模板图像的掩膜图像来正确匹配
问题描述: 我正在使用Python3和OpenCV库的cv2模块进行图像处理。目前,我正在使用模板图像的掩膜图像来匹配原图。但是,我发现当我将掩膜图像作为参数传递给cv2.matchTemplate函数时,匹配的结果并不准确。我想知道如何使用模板图像的掩膜图像进行正确的匹配。
解决方案: 要正确地使用模板图像的掩膜图像进行匹配,可以按照以下步骤操作:
import cv2
image = cv2.imread('原图像路径')
template = cv2.imread('模板图像路径')
mask = cv2.imread('掩膜图像路径')
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
mask_gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
_, binary_mask = cv2.threshold(mask_gray, 1, 255, cv2.THRESH_BINARY)
masked_image = cv2.bitwise_and(image, image, mask=binary_mask)
res = cv2.matchTemplate(masked_image, template_gray, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
locations = np.where(res >= threshold)
for pt in zip(*locations[::-1]):
cv2.rectangle(image, pt, (pt[0] + template.shape[1], pt[1] + template.shape[0]), (0, 255, 0), 2)
完整代码示例:
import cv2
import numpy as np
image = cv2.imread('原图像路径')
template = cv2.imread('模板图像路径')
mask = cv2.imread('掩膜图像路径')
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
mask_gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
_, binary_mask = cv2.threshold(mask_gray, 1, 255, cv2.THRESH_BINARY)
masked_image = cv2.bitwise_and(image, image, mask=binary_mask)
res = cv2.matchTemplate(masked_image, template_gray, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
locations = np.where(res >= threshold)
for pt in zip(*locations[::-1]):
cv2.rectangle(image, pt, (pt[0] + template.shape[1], pt[1] + template.shape[0]), (0, 255, 0), 2)
cv2.imshow('Matched Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
注意:在使用以上代码之前,请确保已经安装了OpenCV库,并且将图像路径替换为实际的图像路径。另外,可以根据实际需求调整阈值参数以获得更准确的匹配结果。