gpt4 book ai didi

python - pygame中的异步图像加载

转载 作者:行者123 更新时间:2023-12-03 13:12:44 25 4
gpt4 key购买 nike

我正在使用 pygame 在 python 2.7 中编写一个小应用程序,我想在屏幕上流畅地显示动画图 block 。我在 Ubuntu 上写作,但如果相关的话,目标平台是 Raspberry Pi。挑战在于这些动画贴图的纹理存储在 Web 服务器上,并且随着时间的推移动态加载,而不是一次全部加载。我希望能够将这些图像加载到 pygame 中,而我的动画或输入响应中没有明显的障碍。加载频率非常低,就像每 30 秒抓取几张 jpg 文件一样。如果这意味着主输入/动画线程保持畅通,我愿意等待很长时间才能在后台加载图像。

因此,使用多处理模块,我能够将图像从服务器异步下载到缓冲区中,然后通过 multiprocessing.queues.SimpleQueue 对象将此缓冲区传递给我的主 pygame 进程。但是,一旦在 pygame 进程中可以访问缓冲区,当缓冲区被加载到 Surface 以通过 pygame.image.frombuffer() 进行 blitting 时,我的应用程序中仍然存在故障。

有没有办法让这个 pygame.image.load() 调用异步,这样我在游戏中的动画等就不会被阻塞?由于 GIL,我想不出一个明显的解决方案。

如果我在 C 中编写常规 OpenGL 程序,我将能够使用像素缓冲区对象将数据异步写入 GPU,对吗? pygame 是否有机会公开此 API 的任何部分?我似乎在 pygame 文档中找不到它,我很陌生,所以如果答案很明显,请原谅我。任何指出 pygame 的术语如何转换为 OpenGL API 的帮助都会有很大的帮助,任何 pygame 可以异步初始化纹理的相关示例都会非常棒!

如果 pygame 不提供此功能,我有什么选择?有没有办法用 PySDL2 做到这一点?

编辑:好的,所以我尝试使用 pygame.image.frombuffer,它并没有真正减少我看到的搭便车。关于如何使这个图像加载真正异步的任何想法?这是一些代码片段,说明了我目前正在做的事情。

这是我拥有的异步代码,它位于与 pygame 不同的进程中

def _worker(in_queue, out_queue):
done = False
while not done:
if not in_queue.empty():
obj = in_queue.get()
# if a bool is passed down the queue, set the done flag
if isinstance(obj, bool):
done = obj
else:
url, w, h = obj
# grab jpg at given url. It is compressed so we use PIL to parse it
jpg_encoded_str = urllib2.urlopen(url).read()
# PIL.ImageFile
parser = ImageFile.Parser()
parser.feed(jpg_encoded_str)
pil_image = parser.close()
buff = pil_image.tostring()
# place decompressed buffer into queue for consumption by main thread
out_queue.put((url, w, h, buff))

# and so I create a subprocess that runs _worker function

这是我在主线程中运行的更新循环。它查看 _Worker 进程是否已将任何内容放入 out_queue,如果是,则将其加载到 pygame 中:
def update():
if not out_queue.empty():
url, w, h, buff = img_buffer_queue.get()
# This call is where I get a hitch in my application
image = pygame.image.frombuffer(buff, (w, h), "RGB")
# Place loaded image on the pygame.Sprite, etc in the callback
callback = on_load_callbacks.pop(url, None)
if callback:
callback(image, w, h)

最佳答案

也许您可以尝试将图像从缓冲区对象转换为工作函数中更有效的对象,也许是表面,然后将该计算的表面发送到输出队列?
这样,表面对象的生成不会阻塞主线程。

关于python - pygame中的异步图像加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21670897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com