ac.find_template识别图片并定位

这里的ac就是aircv,可以直接用pip安装

pip install aircv

使用的时候就可以用:import aircv as ac
在aircv的init文件中对于find_template函数的解释如下:

def find_template(im_source, im_search, threshold=0.5, rgb=False, bgremove=False):
    '''
    @return find location
    if not found; return None
    '''
    result = find_all_template(im_source, im_search, threshold, 1, rgb, bgremove)
    return result[0] if result else None

举例,找到小图片在大图片中的位置并标记:
在这里插入图片描述

这里任意找了两张图片在这里插入图片描述

import aircv as ac
import pyautogui
import cv2
import time
import os

def match(IMSRC, IMOBJ):
    # 匹配图标位置
    imsrc = cv2.imread(IMSRC)
    imobj = cv2.imread(IMOBJ)
    pos = ac.find_template(imsrc, imobj, 0.2)
    if pos == None:
        print("最终没能匹配到:" + imsrc)
    else:
        try:
            show_and_save(IMSRC, pos)
        except Exception as e:
            print("保存匹配结果show_and_save这里出错,错误原因为{}".format(e))
        print(pos)
        point = pos['result']
        pyautogui.moveTo(point)
        print("匹配成功:{}".format(IMSRC))
        time.sleep(0.5)
        return (point)


def show_and_save(imgPath, pos):
    print("Img:",imgPath)
    img = cv2.imread(imgPath)
     # 画矩形
    cv2.rectangle(img, pos['rectangle'][0], pos['rectangle'][3], (0, 0, 255), 2)  # 红
    # 画中心点
    cv2.circle(img, tuple(map(int, pos['result'])), 3, (255, 0, 0), -1)  # -1表示填充

    time_now = time.strftime('%Y-%m-%d %H%M%S', time.localtime(time.time()))
    save_jpg = os.path.dirname(imgPath) + "/" + time_now + '.jpg'
    print("path:",save_jpg)
    cv2.imwrite(save_jpg, img)


if __name__=='__main__':
    IMSRC="E:/program/python/test/test1/13.png"
    IMOBJ="E:/program/python/test/test1/12.png"
    match(IMSRC,IMOBJ)


运行结果为:


Img: E:/program/python/test/test1/13.png
path: E:/program/python/test/test1/2021-03-09 142504.jpg
{
    
    'result': (234.5, 176.5), 'rectangle': ((150, 143), (150, 210), (319, 143), (319, 210)), 'confidence': 0.5964502096176147}
匹配成功:E:/program/python/test/test1/13.png

result的数据含义为匹配图片在原始图片上的中心坐标点,也就是我们要找的点击点,rectangle为矩形坐标(以左上角为坐标原点),confidence是匹配度。

在这里插入图片描述

注意:find_template(im_source, im_search, threshold=0.5)如果最终得到的confidence<threshold,也会返回None

猜你喜欢

转载自blog.csdn.net/liulanba/article/details/114578093