前言

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

过程

安装用到的库

安装方法作用
pillowpip install pillow加载图片
pyscreezepip install pyscreeze截屏
pyautoguipip install pyautogui代码操作鼠标键盘
opencv-pythonpip install 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

# 屏幕缩放系数 mac缩放是2 windows一般是1
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))
# 先缩放屏幕截图 INTER_LINEAR INTER_AREA
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 ("没找到")

这个速度就比较满意了

参考

  1. How can I locate something on my screen quickly in Python?

  2. Python fast screenshots and locateOnScreen

  3. opencv学习笔记十八:模板匹配(cv2.matchTemplate、cv2.minMaxLoc)

  4. 模板匹配-cv2.matchTemplate()、cv2.minMaxLoc()

  5. cv2.matchTemplate模板匹配和cv2.minMaxLoc()函数

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐