Python cv2与主图像不匹配模板

时间:2020-01-08 15:32:42

标签: python cv2 template-matching

我有主图像:

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,我不确定如何修复它。

1 个答案:

答案 0 :(得分:0)

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

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

(反正可能并没有按照您的意图进行)

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