pyautogui入门学习之截屏、识图

1 screenshot()函数

screenshot()函数会返回Image对象,也可以设置文件名

import pyautogui

im1 = pyautogui.screenshot()
im2 = pyautogui.screenshot('my_screenshot.png')

在一个 1920×1080 的屏幕上,screenshot()函数要消耗100微秒 ——不快也不慢。

如果你不需要截取整个屏幕,还有一个可选的region参数。你可以把截取区域的左上角XY坐标值和宽度、高度传入截取。

img_path = r'C:\Users\Administrator\Desktop\one.png'
# 截图
im = pyautogui.screenshot(region=(0, 0, 300 ,400))
# 保存图片
im.save(img_path)

2 locateOnScreen()和center()函数

locateOnScreen()函数来获得图片坐标,返回元组

注:未成功识别,返回None;成功识别,返回首次发现该图像时左边的x,y坐标、宽度和高度。如果该图像在屏幕上能够找到多处,locateAllOnScreen()函数返回一个list

这个元组可以用pyautogui.center()函数来获取截图屏幕的中心坐标。

代码如下:

In [1]: import pyautogui

In [2]: # 图片保存路径
   ...: img_path = r'C:\Users\Administrator\Desktop\one.png'

In [3]: # 识别图片, 未成功识别,返回None; 成功识别,返回首次发现该图像时左边的x,y坐标,宽度和高度
   ...: pos = pyautogui.locateOnScreen(img_path)

In [4]: pos
Out[4]: Box(left=0, top=0, width=30, height=30)

In [5]: # 返回该区域中心的x,y坐标
   ...: pyautogui.center(pos)
Out[5]: Point(x=15, y=15)

3 灰度值匹配

locateOnScreen()函数可以把grayscale参数设置为True来加速定位(大约提升30%),默认为False。这种去色(desaturate)方法可以加速定位,但是也可能导致假阳性(false-positive)匹配。

In [6]: pyautogui.locateOnScreen(img_path, grayscale=True)
Out[6]: Box(left=0, top=0, width=30, height=30)

4 像素匹配

要获取截屏某个位置的RGB像素值,可以用Image对象的getpixel()方法:

In [1]: import pyautogui

In [2]: im = pyautogui.screenshot()

In [3]: im.getpixel((100, 200))
Out[3]: (255, 255, 255)

也可以用PyAutoGUI的pixel()函数,是之前调用的包装:

In [4]: pyautogui.pixel(100, 200)
Out[4]: (255, 255, 255)

如果你只是要检验一下指定位置的像素值,可以用pixelMatchesColor()函数,把X、Y和RGB元组值传入即可:

扫描二维码关注公众号,回复: 8988043 查看本文章
In [5]: pyautogui.pixelMatchesColor(100, 200, (255, 255, 255))
Out[5]: True

In [6]: pyautogui.pixelMatchesColor(100, 200, (255, 255, 245))
Out[6]: False

tolerance参数可以指定红、绿、蓝3种颜色误差范围:

In [7]: pyautogui.pixelMatchesColor(100, 200, (255, 255, 245), tolerance=10)
Out[7]: True

In [8]: pyautogui.pixelMatchesColor(100, 200, (248, 250, 245), tolerance=10)
Out[8]: True

In [9]: pyautogui.pixelMatchesColor(100, 200, (205, 255, 245), tolerance=10)
Out[9]: False
发布了328 篇原创文章 · 获赞 170 · 访问量 28万+

猜你喜欢

转载自blog.csdn.net/apollo_miracle/article/details/103947116
今日推荐