如何将pyglet的ColorBufferImage直接转为PIL格式以优化性能?
直接将Pyglet ColorBufferImage转为CNN可用的PIL图像(跳过存盘步骤)
不需要先存盘再读取,直接通过提取像素数据并转换格式就能完成,步骤如下:
- 提取ColorBufferImage的原始像素数据,注意Pyglet默认像素格式为BGRA(带Alpha通道)
- 将像素数据转为numpy数组,调整通道顺序得到RGB格式
- 用PIL直接从numpy数组创建图像,再按需求调整尺寸
完整代码示例:
import pyglet from PIL import Image import numpy as np # 获取截图的ColorBufferImage对象 buffer_img = pyglet.image.get_buffer_manager().get_color_buffer() width, height = buffer_img.width, buffer_img.height # 提取BGRA格式像素数据并转为numpy数组 pixels = np.frombuffer(buffer_img.get_data('BGRA', width * 4), dtype=np.uint8) pixels = pixels.reshape(height, width, 4) # 转换为RGB格式(丢弃Alpha通道,调整通道顺序) rgb_pixels = pixels[..., [2, 1, 0]] # BGRA → RGB # 创建PIL图像并按需求调整尺寸 pil_image = Image.fromarray(rgb_pixels) pil_image = pil_image.resize((256, 256), resample=Image.NEAREST)
注意事项
- 如果你的Pyglet环境像素格式不是BGRA,可修改
get_data的第一个参数(比如'RGBA'),并对应调整通道顺序的索引 - 最终的
pil_image和原代码中load_img得到的图像格式一致,可直接传入CNN模型使用
内容的提问来源于stack exchange,提问作者jsmndr
相关产品推荐
相关产品推荐

