PyAutoGUI 屏幕截图(4)
Grayscale Matching
可以传递一个参数grayscale=True
给定位函数,以加快定位速度,但是可能会导致定位错误。
>>> import pyautogui
>>> button7location = pyautogui.locateOnScreen('calc7key.png', grayscale=True)
>>> button7location
(1416, 562, 50, 41)
Pixel Matching
若要获取屏幕截图中像素的RGB
颜色,使用Image
对象的getpixel()
方法:
>>> import pyautogui
>>> im = pyautogui.screenshot()
>>> im.getpixel((100, 200))
(130, 135, 144)
或者直接调用PyAutoGUI
的pixel()
:
>>> import pyautogui
>>> pix = pyautogui.pixel(100, 200)
>>> pix
RGB(red=130, green=135, blue=144)
>>> pix[0]
130
>>> pix.red
130
如果只需要验证单个像素是否与给定像素匹配,则调用pixelMatchesColor()
函数,将X坐标、Y坐标和RGB元组传递给它:
>>> import pyautogui
>>> pyautogui.pixelMatchesColor(100, 200, (130, 135, 144))
True
>>> pyautogui.pixelMatchesColor(100, 200, (0, 0, 0))
False
可选tolerance
关键字参数指定每个红色、绿色和蓝色值在匹配时的变化程度:
>>> import pyautogui
>>> pyautogui.pixelMatchesColor(100, 200, (130, 135, 144))
True
>>> pyautogui.pixelMatchesColor(100, 200, (140, 125, 134))
False
>>> pyautogui.pixelMatchesColor(100, 200, (140, 125, 134), tolerance=10)
True