头图

简单说:findimage项目的find_templatefind_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。

示例

目标

还是在下图中,查找符号'#':
seg_course_menu.png

传入的模板图是:
seg_sharp_resize_1.5.png

方法

可以看出明显比源图中的#要大,如果直接匹配,是找不到结果的,但使用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)

结果

可以看到查找结果图像:
result.png

所有的#都被找到了。如果我们查看控制台输出:

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。


songofhawk
303 声望24 粉丝