6 屏幕截圖與圖像定位
PyAutoGUI可以拍攝屏幕截圖,將其保存到文件中,并在屏幕中定位圖像。OSX使用操作系統(tǒng)附帶的screencapture命令。Linux使用scrot命令,可以通過運行sudo-apt-get-install-scrot來安裝該命令。文章來源:http://www.zghlxwxcb.cn/news/detail-627386.html
功能介紹:一個需要點擊的按鈕,并且想在屏幕上找到它。文章來源地址http://www.zghlxwxcb.cn/news/detail-627386.html
6.1 屏幕截圖
import pyautogui
# 截取全屏 在1920 x 1080屏幕上,screenshot()函數(shù)大約需要100毫秒-不快但不慢。
im1 = pyautogui.screenshot()
# 截取全屏,并以圖片保存
im2 = pyautogui.screenshot('my_screenshot.png')
# 截取指定位置,傳遞要捕獲的區(qū)域的左側(cè)、頂部、寬度和高度的四個整數(shù)元組:
im = pyautogui.screenshot(region=(0,0, 300, 400))
6.2 定位單個目標
import pyautogui
# ---------------------------------------------------------------
# 獲取感興趣區(qū)域的 (left, top, width, height)
button7location = pyautogui.locateOnScreen('looksLikeThis.png')
print(button7location)
print(button7location[0])
print(button7location.left)
# 計算感興趣區(qū)域的中心點的xy坐標
button7point = pyautogui.center(button7location)
print(button7point)
print(button7point[0])
print(button7point.x)
# 點擊感興趣區(qū)域的中心點坐標
button7x, button7y = button7point
pyautogui.click(button7x, button7y)
# ---------------------------------------------------------------
# 快速點擊感興趣區(qū)域
pyautogui.click('looksLikeThis.png')
# ---------------------------------------------------------------
# 設(shè)置置信度 需要安裝opencv
button7location = pyautogui.locateOnScreen('looksLikeThis.png', confidence=0.9)
print(button7location)
print(button7location[0])
print(button7location.left)
# ---------------------------------------------------------------
# 獲取感興趣區(qū)域的中心點位置坐標,并且點擊
x, y = pyautogui.locateCenterOnScreen('looksLikeThis.png')
pyautogui.click(x, y)
6.3 定位全部目標的位置
import pyautogui
# 這些“定位”功能相當昂貴;他們可以用整整一秒鐘的時間跑。
for pos in pyautogui.locateAllOnScreen('someButton.png')
print(pos)
# 提高速度的最佳方法:傳遞一個區(qū)域參數(shù)(一個4整型元組(左、上、寬、高)),以僅搜索屏幕的較小區(qū)域,而不是全屏:
pyautogui.locateOnScreen('someButton.png', region=(0,0, 300, 400))
6.4 灰度匹配
import pyautogui
button7location = pyautogui.locateOnScreen('looksLikeThis.png', grayscale=True)
print(button7location)
6.5 像素匹配(獲取屏幕截圖中像素的RGB顏色)
import pyautogui
# 獲取屏幕截圖中像素的RGB顏色方案①
im = pyautogui.screenshot()
color_RGB = im.getpixel((100, 200))
print(color_RGB) #(130, 135, 144)
# 獲取屏幕截圖中像素的RGB顏色方案②
pix = pyautogui.pixel(100, 200)
print(pix) # RGB(red=130, green=135, blue=144)
print(pix[0]) # 130
print(pix.red) # 130
# 如果只需要驗證單個像素是否與給定像素匹配,請調(diào)用pixelMatchesColor()函數(shù),將其表示的顏色的X坐標、Y坐標和RGB元組傳遞給它:
pyautogui.pixelMatchesColor(100, 200, (130, 135, 144)) # True
pyautogui.pixelMatchesColor(100, 200, (0, 0, 0)) # False
# tolerance關(guān)鍵字參數(shù)指定紅色、綠色和藍色值在仍匹配時可以變化多少:
pyautogui.pixelMatchesColor(100, 200, (140, 125, 134)) # False
pyautogui.pixelMatchesColor(100, 200, (140, 125, 134), tolerance=10) # True
到了這里,關(guān)于【PyAutoGUI操作指南】05 屏幕截圖與圖像定位:截圖+定位單個目標+定位全部目標+灰度匹配+像素匹配+獲取屏幕截圖中像素的RGB顏色的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!