python Opencv和pyautogui实现自动识图点击

python Opencv和pyautogui实现自动识图点击

1.导入python及其他模块
匹配类是上一章博客内容,pyautogui自带的图片匹配效果不是很理想。就使用Opencv的图片匹配来实现图片的定位。

python 使用模版匹配.

import pyautogui as pag
import time
import datetime
import socket
import 匹配类 as IMA
import threading

2主程序

if __name__=="__main__":
    # DoWhile()
    print(datetime.datetime.now()) 
    print(dir(IMA.ImageMatch))
    print("---------------------------------------")
    print(dir(threading))
    DoWhile()
    # shotSCreen()
    print(datetime.datetime.now()) 
    pass

3.shotSCreen()#截取当前屏幕,X,Y=ImageMatch()#通过匹配获取当前模版图片的定位
实现自动点击

#实现定位点击
def DoWhile():
    
    num=0
    num_false=0
    
    while (num<20 and num_false<100):
        lcation={"X1":2000,"Y1":2000}
        # lcation=pag.locateOnScreen(r'D:\mypython\chengjiao\T1.png')
        shotSCreen()#截取当前屏幕
        X,Y=ImageMatch()#通过匹配获取当前模版图片的定位
        if(X!=0):
            point=pag.Point(X,Y)
            print(lcation)
            if lcation!=None:
                num+=1
                # point=pag.center(lcation)
                print("定位成功%d"%(num))
                print(point)
                pag.click(point)
                time.sleep(2)
            else:
                num_false+=1
                print("定位失败%d"%(num_false))
        else:
            num_false+=1
            print("定位失败%d"%(num_false))

4.自动截取当前图片

def shotSCreen():
    image_dir = r'D:\mypython\chengjiao'
    curr_time='2'
    print(curr_time)
    image_file=f"{image_dir}\{curr_time}.jpg"
    print(socket.gethostname(),"save_image:",image_file)
    pag.screenshot(image_file)
    time.sleep(1)

5.使用模版匹配来获取当前坐标

def ImageMatch():
    X=0
    src=r'D:\mypython\chengjiao\2.jpg'
    srctempl=r'D:\mypython\chengjiao\T1.jpg'
    imageMatch= IMA.ImageMatch(src,srctempl)
    X,Y=IMA.ImageMatch.main(imageMatch)
    print(X,Y)
    return(X,Y)```

6.运行效果图:
python Opencv和pyautogui实现自动识图点击_第1张图片
python Opencv和pyautogui实现自动识图点击_第2张图片

python-opencv模版匹配学习

你可能感兴趣的:(python,opencv,开发语言)