在 Pygame 中,如何以无头模式保存屏幕图像? [英] In Pygame, how can I save a screen image in headless mode?
问题描述
我试图通过将每一帧保存为图像而不是使用 ffmpeg 将它们拼接在一起来捕获我的游戏视频.我遵循了这些脚本的示例:
I'm trying to capture a video of my game by saving each frame as an image than stitching them together using ffmpeg. I followed the example of these scripts:
这是我的代码的基本逻辑:
Here's the basic logic of my code:
os.environ['SDL_VIDEODRIVER'] = 'dummy'
pygame.init()
pygame.display.set_mode((1,1))
screen = pygame.Surface((400, 400)).convert()
# screen becomes attribute of game object: game.screen
game = MyGame(screen)
while game.running:
game.update() # <--- updates game.screen
pygame.display.flip()
pygame.image.save(game.screen, 'frame-%03d.png' % (game.frame_num))
create_video_using_ffmpeg()
如果我将设置视频驱动程序的第一行注释为虚拟",则图像会按预期显示.但是它会打开一个(小)窗口,因此脚本在作为 cronjob 运行时会失败.如果没有注释该行,我只会得到一系列空白的黑色图像.
If I comment out the first line setting video driver to 'dummy', the images turn out as expected. But it opens a (small) window, so the script fails when run as a cronjob. With the line uncommented, I just get a series of blank black images.
知道出了什么问题吗?
推荐答案
我能够通过在用作我的屏幕的基本图像表面绘制一个矩形来解决这个问题:
I was able to work around this by drawing a rectangle to the base image surface serving as my screen:
os.environ['SDL_VIDEODRIVER'] = 'dummy'
pygame.init()
pygame.display.set_mode((1,1))
# surface alone wouldn't work so I needed to add a rectangle
screen = pygame.Surface((400, 400), pygame.SRCALPHA, 32)
pygame.draw.rect(screen, (0,0,0), (0, 0, 400, 400), 0)
# screen becomes attribute of game object: game.screen
game = MyGame(screen)
while game.running:
game.update() # <--- updates game.screen
pygame.display.flip()
pygame.image.save(game.screen, 'frame-%03d.png' % (game.frame_num))
create_video_using_ffmpeg()
也许其他人可以解释为什么这会有所作为.(我原来使用了错误的表面参数吗?)
Perhaps someone else can explain why this makes a difference. (Was I using the wrong surface parameters originally?)
这是一个成功的定时任务.
This worked successfully as a cronjob.
这篇关于在 Pygame 中,如何以无头模式保存屏幕图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!