簡單說:findimage專案的find_template
和find_all_template
方法,都新增了一個引數:autoscale
。
表示是否自動縮放im_template來查詢匹配,如果為None表示不縮放,如果需要縮放,那麼傳一個tuple:(min_scale, max_scale, step),其中min_scale和max_scale分別是縮放倍數的下限和上限,都是小數,min_scale介於0~1之間,max_scale大於1, step表示從min嘗試到max之間的步長, 預設為0.1。
示例
目標
還是在下圖中,查詢符號'#':
傳入的模板圖是:
方法
可以看出明顯比源圖中的#要大,如果直接匹配,是找不到結果的,但使用autoscale引數之後:
from cv2 import cv2
import time
from findimage import find_all_template
image_origin = cv2.imread('seg_course_menu.png')
image_template = cv2.imread('seg_sharp_resize_1.5.png')
start_time = time.time()
match_results = find_all_template(image_origin, image_template, threshold=0.8, auto_scale=(0.6, 1.2), debug=True)
print("total time: {}".format(time.time() - start_time))
img_result = image_origin.copy()
for match_result in match_results:
rect = match_result['rectangle']
cv2.rectangle(img_result, (rect[0][0], rect[0][1]), (rect[3][0], rect[3][1]), (0, 0, 220), 2)
print(match_result)
cv2.imwrite('result.png', img_result)
結果
可以看到查詢結果影像:
所有的#都被找到了。如果我們檢視控制檯輸出:
try resize template in scale 0.7 to find match
matchTemplate time: 0.004000186920166016
find max time: 0.0009999275207519531
found 7 results, top confidence is:0.9912415146827698
total time: 0.05300307273864746
{'result': (45.5, 266.5), 'rectangle': ((36, 257), (36, 276), (55, 257), (55, 276)), 'confidence': 0.9912415146827698}
{'result': (45.5, 146.5), 'rectangle': ((36, 137), (36, 156), (55, 137), (55, 156)), 'confidence': 0.9912384152412415}
{'result': (45.5, 226.5), 'rectangle': ((36, 217), (36, 236), (55, 217), (55, 236)), 'confidence': 0.9912384152412415}
{'result': (45.5, 306.5), 'rectangle': ((36, 297), (36, 316), (55, 297), (55, 316)), 'confidence': 0.9912353157997131}
{'result': (45.5, 346.5), 'rectangle': ((36, 337), (36, 356), (55, 337), (55, 356)), 'confidence': 0.9912353157997131}
{'result': (45.5, 186.5), 'rectangle': ((36, 177), (36, 196), (55, 177), (55, 196)), 'confidence': 0.99123215675354}
{'result': (45.5, 386.5), 'rectangle': ((36, 377), (36, 396), (55, 377), (55, 396)), 'confidence': 0.99123215675354}
可以看到是在縮放到0.7倍的時候,輸出了查詢結果,並且每個位置的匹配度都大於0.9。