Python cv2与主图像不匹配模板

问题描述 投票:0回答:1

我有主图像:

enter image description here

还有我的模板:

enter image description here

但是,我正在使用的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,不确定如何解决。

python cv2 template-matching
1个回答
0
投票

我具有的模板匹配代码始终将模板的尺寸与图像的尺寸匹配。如果您已经将源图像转换为灰度,请更改

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

(反正可能不会做您打算做的事]

template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
w, h = template.shape
© www.soinside.com 2019 - 2024. All rights reserved.