[英]python matchtemplate not working properly with mask enabled
我正在嘗試在不同的圖像上匹配相同的文本模板。 圖像的背景各不相同,文本的亮度從灰色 (150) 到純白色 (255) 不等,但它具有相同的圖案,因此我使用了 TM2.CCOEFF_NORMED。 問題是不帶遮罩的匹配模板比帶遮罩的效果好得多,我不明白這背后的任何原因。 有什么我可能會遺漏的嗎?
給黑色背景和白色文本圖像作為蒙版和給透明背景作為蒙版,像下面這樣分別提取基礎和 alpha 通道之間也有什么區別嗎?
具有透明的模板圖像以提取基數和 alpha,Template2
Template2 的文本顏色應該是 255,255,255 但我將其更改為 159,159,159,因此您可以看到文本 import cv2 import numpy as np import matplotlib.pyplot as plt
for i in range(1,6):
# read game image
img = cv2.imread(f'image{i}.png')
# read bananas image template
template = cv2.imread('noitem.png', cv2.IMREAD_UNCHANGED)
hh, ww = template.shape[:2]
print (template.shape)
# extract bananas base image and alpha channel and make alpha 3 channels
base = template[:,:,0:3]
alpha = template[:,:,3]
alpha = cv2.merge([alpha,alpha,alpha])
# do masked template matching and save correlation image
correlation = cv2.matchTemplate(img, base, cv2.TM_CCOEFF_NORMED, mask=alpha)
correlation1 = cv2.matchTemplate(img, base, cv2.TM_CCOEFF_NORMED)
# set threshold and get all matches
threshhold = 0.9
loc = np.where(correlation >= threshhold)
loc1 = np.where(correlation1 >= threshhold)
# draw matches
result = img.copy()
result1 = img.copy()
for pt in zip(*loc[::-1]):
cv2.rectangle(result, pt, (pt[0]+ww, pt[1]+hh), (0,0,255), 1)
print(pt)
for pt in zip(*loc1[::-1]):
cv2.rectangle(result1, pt, (pt[0]+ww, pt[1]+hh), (0,0,255), 1)
print(pt)
plt.subplot(1,2,1)
plt.title('with mask')
plt.imshow(result[:,:,::-1])
plt.subplot(1,2,2)
plt.title('without mask')
plt.imshow(result1[:,:,::-1])
plt.show()
'''
#cv2.imshow('base',base)
#cv2.imshow('alpha',alpha)
cv2.imshow('result',result)
cv2.waitKey(0)
cv2.destroyAllWindows()
'''
正如我在上面的評論中提到的那樣,這是一種方法。 該模板在黑色背景上有白色文本。 所以將其復制為蒙版。 查找最大匹配位置而不是所有高於閾值的位置。 使用 TM_CORR_NORMED 而不是 TM_COEFF_NORMED(如果您的 OpenCV 版本允許后者,則交替使用 TM_SQDIFF 或 TMSQDIFF_NORMED。但隨后找到最小位置)
輸入:
模板和遮罩:
import cv2
import numpy as np
# read image
img = cv2.imread('text_image.png')
# read template
template = cv2.imread('text_template.png')
hh, ww = template.shape[:2]
# copy the template to the mask
mask = template.copy()
# do masked template matching and save correlation image
correlation = cv2.matchTemplate(img, template, cv2.TM_CCORR_NORMED, mask=mask)
# get best match
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(correlation)
max_val_corr = '{:.6f}'.format(max_val)
print("correlation score: " + max_val_corr)
print("match location:", max_loc)
# draw match
result = img.copy()
cv2.rectangle(result, (max_loc), ( max_loc[0]+ww, max_loc[1]+hh), (0,0,255), 1)
# save results
cv2.imwrite('text_image_match.png', result)
cv2.imshow('template',template)
cv2.imshow('result',result)
cv2.waitKey(0)
cv2.destroyAllWindows()
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.