pyautogui.screenshot()详解

 2023-09-05 阅读 77 评论 0

摘要:1 screenshot()函数 screenshot()函数会返回Image对象,也可以设置文件名 import pyautoguiim1 = pyautogui.screenshot() im2 = pyautogui.screenshot('my_screenshot.png') 在一个 19201080 的屏幕上,screenshot()函数要消耗100微秒 ——不快也

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

import pyautoguiim1 = 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 pyautoguiIn [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 pyautoguiIn [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元组值传入即可:

In [5]: pyautogui.pixelMatchesColor(100, 200, (255, 255, 255))
Out[5]: TrueIn [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]: TrueIn [8]: pyautogui.pixelMatchesColor(100, 200, (248, 250, 245), tolerance=10)
Out[8]: TrueIn [9]: pyautogui.pixelMatchesColor(100, 200, (205, 255, 245), tolerance=10)
Out[9]: False

https://blog.csdn.net/apollo_miracle/article/details/103947116

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://808629.com/791.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 86后生记录生活 Inc. 保留所有权利。

底部版权信息