Python獲取屏幕截圖的四種方式


一. PIL中的Imagegeab模塊(效率低,一次需要0.5秒)

import time

import numpy as np
from PIL import ImageGrab
 
img = ImageGrab.grab(bbox = ( 100 , 161 , 1141 , 610 ))
img = np.array(img.getdata(), np.uint8).reshape(img.size[ 1 ], img.size[ 0 ], 3 )

二. windows API

調用Windows API ,速度快但是復雜

三. pyqt

比調用Windows API簡單,而且速度快,可以指定獲取的窗口,及時窗口被遮擋,但是窗口最小化就無法獲得

1.首先獲取窗口的句柄

import win32gui

hwnd_title = dict ()
def get_all_hwnd(hwnd,mouse):
   if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
     hwnd_title.update({hwnd:win32gui.GetWindowText(hwnd)})
 
win32gui.EnumWindows(get_all_hwnd, 0 )
  
for h,t in hwnd_title.items():
   if t is not "":
     print (h, t)
程序會打印窗口的hwnd和title,有了title就可以進行截圖了
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import *
import win32gui
import sys
 
hwnd = win32gui.FindWindow( None , 'C:\Windows\system32\cmd.exe' )
app = QApplication(sys.argv)
screen = QApplication.primaryScreen()
img = screen.grabWindow(hwnd).toImage()
img.save( "screenshot.jpg" )

四. pyautogui

pyautogui是比較簡單的,但是不能指定獲取程序的窗口,因此窗口也不能遮擋,不過可以指定截屏的位置,0.04s一張截圖,比PyQt稍慢一點,但也很快了pyautogui是比較簡單的,但是不能指定獲取程序的窗口,因此窗口也不能遮擋,不過可以指定截屏的位置,0.04s一張截圖,比PyQt稍慢一點,但也很快了

import pyautogui

import cv2
 
img = pyautogui.screenshot(region = [ 0 , 0 , 100 , 100 ]) # x,y,w,h
# img.save('screenshot.png')
img = cv2.cvtColor(np.asarray(img),cv2.COLOR_RGB2BGR)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM