首页 > 解决方案 > 如何使用 PIL 在 Google Colab 中截屏

问题描述

我希望在 Google Colab 上截取我的屏幕截图以用于屏幕录制的视频,但由于笔记本在 linux 中运行,我不确定这是否可能。

我的设备上的python代码如下

from PIL import ImageGrab
img = ImageGrab.grab(bbox= None)

在 Colab 上运行时,它会返回OSError: X connection failed: error 5ImportError: ImageGrab is macOS and Windows only

寻找其他选项,我首先尝试了mss.mss(),它返回了$DISPLAY not set.。我尝试在方法和使用中设置显示,但os都没有奏效。

然后我尝试gtk.gdk了,但是在尝试了几种方法后我无法正确安装和导入它。

我也尝试过使用pyautogui,但导入后我无法连接到显示器,并且返回了 aDisplayConnectionErrorOSError.

有没有办法修复使用我列出的方法返回的任何错误?还是有另一种我不知道的方法可以在 Colab 中将屏幕内容作为图像返回?

标签: pythonpython-3.xopencvgoogle-colaboratory

解决方案


首先,您需要设置一个虚拟监视器:

!pip install gym pyvirtualdisplay > /dev/null 2>&1
!apt-get install -y xvfb python-opengl ffmpeg > /dev/null 2>&1

DISPLAY_WIDTH = 1920  
DISPLAY_HEIGHT = 1080

from IPython import display as ipythondisplay
from pyvirtualdisplay import Display
display = Display(visible=0, size=(DISPLAY_WIDTH, DISPLAY_HEIGHT))
display.start()

然后安装pyscreenshot:

!pip install pyscreenshot
import pyscreenshot as ImageGrab

最后上图:

frame = np.array(ImageGrab.grab(bbox= None))

ImageGrab.grab(bbox=(x, y, w, h))您还可以指定要抓取的屏幕大小。


推荐阅读