首页 > 解决方案 > Python cv2与主图像不匹配模板

问题描述

我有我的主要形象:

在此处输入图像描述

还有我的模板:

在此处输入图像描述

但是,我使用的 cv2 代码没有生成矩形来显示匹配,但我也收到 0 个错误。

这是代码:

# Read the main image 
img_rgb = cv2.imread('main.png')

# Convert it to grayscale 
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) 

# Read the template 
template = cv2.imread('temp.png',0) 
template = np.array(template[:,::-1])

# Store width and height of template in w and h 
w, h = template.shape[::-1] 

# Perform match operations. 
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED) 

# Specify a threshold 
threshold = 0.8

# Store the coordinates of matched area in a numpy array 
loc = np.where( res >= threshold)  

# Draw a rectangle around the matched region. 
for pt in zip(*loc[::-1]): 
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,255), 2) 

# Show the final image with the matched area. 
cv2.imshow('Detected',img_rgb) 
cv2.waitKey()
cv2.destroyAllWindows()

我最初的想法是模板图像太大而无法与主图像匹配,但是这是我第一次使用 cv2,我不确定如何修复它。

标签: pythoncv2template-matching

解决方案


我一直使用的模板匹配代码都是将模板的尺寸与图像的尺寸进行匹配。在您的情况下,您已经将源图像转换为灰度,更改

template = np.array(template[:,::-1])
w, h = template.shape[::-1] 

(这可能不会做你想做的事)

template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
w, h = template.shape

推荐阅读