Numpy图像数组转为pyglet图像
我正在尝试用imageio把图片加载到一个numpy数组里,然后用pyglet显示出来。不过最后的结果看起来很乱,虽然我能看到一些结构。代码如下:
import pyglet as pg
import imageio.v3 as im
import numpy as np
window = pg.window.Window()
#Load image, and get_shape
np_image = im.imread("test.png")[100:400, 100:400] #Get smaller section from much larger image (~3Kx3K)
height = np_image.shape[0]
width = np_image.shape[1]
depth = np_image.shape[2]
#Create pyglet image and load image data to it (+ set anchor for displaying)
pg_image = pg.image.create(width, height)
pg_image.set_data("RGB", width*3, np_image)
pg_image.anchor_x = width//2
pg_image.anchor_y = height//2
#Print shapes and dtype, all should be correct
print(np_image.shape)
print(width, height, depth)
print(np_image.dtype)
#Put into sprite
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()s
pg.app.run()
最后的结果是:
我哪里做错了呢?
补充:
调试打印的内容是:
(300, 300, 3)
300 300 3
uint8
1 个回答
2
PNG格式的图片有4个颜色通道,而不是3个。pyglet.image.ImageData.set_data)
支持“ARGB”格式,所以你需要把图片从RGBA格式转换成ARGB格式:
np_image[:, :, [0, 1, 2, 3]] = np_image[:, :, [3, 0, 1, 2]]
另外,你还需要翻转
这张图片:
np_image = np.flip(np_image, 0)
把这些步骤放在一起:
np_image = im.imread("test.png")
np_image = np_image[100:400, 100:400]
height, width, depth = np_image.shape
np_image[:, :, [0, 1, 2, 3]] = np_image[:, :, [3, 0, 1, 2]]
np_image = np.flip(np_image, 0)
pg_image = pg.image.create(width, height)
pg_image.set_data("ARGB", width*4, np_image)