python - 如何使用 PIL 在 Google Colab 中截屏
问题描述
我希望在 Google Colab 上截取我的屏幕截图以用于屏幕录制的视频,但由于笔记本在 linux 中运行,我不确定这是否可能。
我的设备上的python代码如下
from PIL import ImageGrab
img = ImageGrab.grab(bbox= None)
在 Colab 上运行时,它会返回OSError: X connection failed: error 5
或ImportError: ImageGrab is macOS and Windows only
。
寻找其他选项,我首先尝试了mss.mss()
,它返回了$DISPLAY not set.
。我尝试在方法和使用中设置显示,但os
都没有奏效。
然后我尝试gtk.gdk
了,但是在尝试了几种方法后我无法正确安装和导入它。
我也尝试过使用pyautogui
,但导入后我无法连接到显示器,并且返回了 aDisplayConnectionError
或OSError
.
有没有办法修复使用我列出的方法返回的任何错误?还是有另一种我不知道的方法可以在 Colab 中将屏幕内容作为图像返回?
解决方案
首先,您需要设置一个虚拟监视器:
!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))
您还可以指定要抓取的屏幕大小。
推荐阅读
- elm - Elm 的余数运算符是什么
- java - 如何在Java中拆分字符串并比较是否相等?
- javascript - 如何将物体隐藏在立方体孔中?
- javascript - 当表单上有未填写的字段时,如何不将值设置为 Google 工作表?
- c++ - 计数输出不正确/尝试使用开放寻址创建 HashTable/Set 时遇到困难
- asp.net-mvc - 来自控制器的 Asp.net 核心将 html 作为字符串或 json 返回到 ajax 调用
- javascript - useCallback 具有空依赖项,那么作为回调参数传递的是什么?
- python - ValueError:无法将字符串转换为浮点数:'Y'
- php - 使用“to”而不是打印数组中的每个数字
- python - 我如何阅读不和谐消息并将其用作变量?Python