Python 自动化办公之自动识别并点击按钮

遇到一个需要电脑的体力劳动,找到了Python控制鼠标的库,结合之前用过的OpenCV识别可以屏幕内容,可以实现略微复杂的自动化办公操作。

安装用到的库

库安装方法作用pillow

加载图片pyscreeze

截屏pyautogui

代码操作鼠标键盘opencv-python

识别并匹配图片

使用pyautogui自动点击按钮

检查屏幕上是否有某个按钮,有的话就点击

from time import sleep
import pyautogui
from PIL import ImageGrab, Image

zhengnengliangImg= Image.open("zhengnengliang.png")

msg = pyautogui.locateOnScreen(zhengnengliangImg, grayscale=True,confidence=.9)
if msg==None:
    print ("没找到")
else:
    x,y,width,height=msg
    print ("该图标在屏幕中的位置是:X={},Y={},宽{}像素,高{}像素".format(x,y,width,height))

    pyautogui.click(x,y,button='left')

使用OpenCV和pyscreeze加速

写好上面的程序发现了一个问题,就是使用 pyautogui.locateOnScreen速度太慢了,不如用之前玩过的OpenCV识别图片,所以略微修改程序,同样,为了加速截图速度使用 pyscreeze截图。这样识别位置操作差不多快了10倍左右

from time import sleep
import pyautogui
from PIL import ImageGrab, Image
import pyscreeze
import cv2

screenScale=1

target= cv2.imread(r"zhengnengliang.png",cv2.IMREAD_GRAYSCALE)

screenshot=pyscreeze.screenshot('my_screenshot.png')

temp = cv2.imread(r'my_screenshot.png',cv2.IMREAD_GRAYSCALE)

theight, twidth = target.shape[:2]
tempheight, tempwidth = temp.shape[:2]
print("目标图宽高:"+str(twidth)+"-"+str(theight))
print("模板图宽高:"+str(tempwidth)+"-"+str(tempheight))

scaleTemp=cv2.resize(temp, (int(tempwidth / screenScale), int(tempheight / screenScale)))
stempheight, stempwidth = scaleTemp.shape[:2]
print("缩放后模板图宽高:"+str(stempwidth)+"-"+str(stempheight))

res = cv2.matchTemplate(scaleTemp, target, cv2.TM_CCOEFF_NORMED)
mn_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if(max_val>=0.9):

    top_left = max_loc
    bottom_right = (top_left[0] + twidth, top_left[1] + theight)
    tagHalfW=int(twidth/2)
    tagHalfH=int(theight/2)
    tagCenterX=top_left[0]+tagHalfW
    tagCenterY=top_left[1]+tagHalfH

    pyautogui.click(tagCenterX,tagCenterY,button='left')
else:
    print ("没找到")

这个速度就比较满意了

Original: https://blog.csdn.net/a71468293a/article/details/121251007
Author: SlowFeather
Title: Python 自动化办公之自动识别并点击按钮

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/637213/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球