对Python获取屏幕截图的4种方法详解

yipeiwu_com6年前Python基础

Python获取电脑截图有多种方式,具体如下:

PIL中的ImageGrab模块

windows API

PyQt

pyautogui

PIL中的ImageGrab模块

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)

使用PIL中的ImageGrab模块简单,但是效率有点低,截屏一次需0.5s。

windows API

调用windows API,速度快但是使用较复杂,这里就不做详细介绍了,因为有更好用的PyQt。

PyQt

PyQt比调用windows API简单很多,而且有windows API的很多优势,比如速度快,可以指定获取的窗口,即使窗口被遮挡。需注意的是,窗口最小化时无法获取截图。

首先需要获取窗口的句柄。

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稍慢一点,但也很快了。

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)

以上这篇对Python获取屏幕截图的4种方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python3 使用map()批量的转换数据类型,如str转float的实现

我们知道map() 会根据提供的函数对指定序列做映射。 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新...

JavaScript实现一维数组转化为二维数组

啥也不说了,上代码吧! <!DOCTYPE html> <html lang="en"> <head> <meta charse...

python实现文件快照加密保护的方法

本文实例讲述了python实现文件快照加密保护的方法。分享给大家供大家参考。具体如下: 这段代码可以对指定的目录进行扫描,包含子目录,对指定扩展名的文件进行SHA-1加密后存储在cvs文...

pytorch中tensor.expand()和tensor.expand_as()函数详解

tensor.expend()函数 >>> import torch >>> a=torch.tensor([[2],[3],[4]]) >...

python3+PyQt5+Qt Designer实现扩展对话框

python3+PyQt5+Qt Designer实现扩展对话框

本文是对《Python Qt GUI快速编程》的第9章的扩展对话框例子Find and replace用Python3+PyQt5+Qt Designer进行改写。 第一部分无借用Qt...