1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python截图黑屏_对Python获取屏幕截图的4种方法详解

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

时间:2020-12-29 22:06:15

相关推荐

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

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种方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

时间: -08-25

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。