Numpy 图像数组到 pyglet 图像

问题描述 投票:0回答:1

我正在尝试使用 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
python numpy pyglet python-imageio
1个回答
0
投票

Numpy 数组按行主序存储数据。然而,对于图像,数据必须按列主顺序存储。所以你需要

transpose
numpy 数组。此外,您还必须将颜色通道从 BGR 转换为 RGB:

np_image = numpy.transpose(np_image, (1, 0, 2))
np_image[:, :, [0, 2]] = np_image[:, :, [2, 0]]
© www.soinside.com 2019 - 2024. All rights reserved.