Numpy image array to pyglet image

57 views Asked by At

I am trying to load image to a numpy array using imageio, and display it using pyglet. The end result is garbled, though I can see some structure. Code:

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()

End result is:

Garbled image data as result of previous code

What am I doing wrong here?

EDIT:

Debug print is:

(300, 300, 3)
300 300 3
uint8
1

There are 1 answers

0
Rabbid76 On

A PNG has 4 color channels not 3. pyglet.image.ImageData.set_data) supports the "ARGB" format therefore you need to convert the image from RGBA to ARGB:

np_image[:, :, [0, 1, 2, 3]] = np_image[:, :, [3, 0, 1, 2]]

Additionally you have to flip the image:

np_image = np.flip(np_image, 0)

All together:

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)