You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用imageio加载numpy数组转pyglet图像显示乱码问题求助

问题解决:pyglet显示numpy数组图像乱码

问题原因

你的代码存在两个关键问题:

  • pg.image.set_data() 要求传入字节流作为图像数据,你直接传入了numpy数组,导致数据格式不匹配。
  • imageio加载的numpy数组,行顺序是从图像底部到顶部,而pyglet期望图像数据是从顶部到底部存储,上下方向错位导致画面乱码。

修复后的代码

import pyglet as pg
import imageio.v3 as im
import numpy as np

window = pg.window.Window()

# 加载图像并裁剪
np_image = im.imread("test.png")[100:400, 100:400]
height = np_image.shape[0]
width = np_image.shape[1]
depth = np_image.shape[2]

# 创建pyglet图像并修正数据格式与行顺序
pg_image = pg.image.create(width, height)
# 翻转数组行并转换为字节流
pg_image.set_data("RGB", width*3, np_image[::-1].tobytes())
pg_image.anchor_x = width//2
pg_image.anchor_y = height//2

# 调试输出
print(np_image.shape)
print(width, height, depth)
print(np_image.dtype)

# 创建精灵并显示
gp_sprite = pg.sprite.Sprite(pg_image, x=window.width//2, y=window.height//2)

@window.event
def on_draw():
    window.clear()
    gp_sprite.draw()

pg.app.run()

关键修改点

  • 将 np_image 替换为 np_image[::-1].tobytes():
    • [::-1] 翻转数组的行,纠正pyglet的图像行顺序要求。
    • tobytes() 将numpy数组转换为pyglet能识别的字节流格式。

内容的提问来源于stack exchange,提问作者Nyxeria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 17:27:28