PySDL2 display grayscale numpy array on window surface

393 views Asked by At

I have a grayscale image converted into numpy array. I am trying to render this image on the sdl2 window surface.

sdl2.ext.init()
self.window = sdl2.ext.Window("Hello World!", size=(W, H)) 
self.window.show()
self.events = sdl2.ext.get_events()
    for event in self.events:
        if event.type == sdl2.SDL_QUIT:
            exit(0)
self.windowsurface = sdl2.SDL_GetWindowSurface(self.window.window)
self.windowArray = sdl2.ext.pixels2d(self.windowsurface.contents)
self.windowArray[:] = frame[:,:,1].swapaxes(0,1)
self.window.refresh()

Right now I see the image in blue form. I want to render it as grayscale image. I have also tried to explore the sdl2.ext.colorpalettes but no success.

How can I display the grayscale numpy array on the sdl2 window surface

1

There are 1 answers

0
Apeiron On

I've been playing around with this today, and from what I can tell the reason is a difference in dtypes, the surface is a numpy.uint32 while an image loaded from a gray scale image is only numpy.uint8. so full white in uint8 is 0xff when stored as auin32 it becomes 0x000000ff which is blue.

My dummy approach for testing is some numpy bit shifting:

self.windowArray[:] = self.windowArray[:] + (self.windowArray[:] << 8) + (self.windowArray[:] << 16)

I'm sure there is a better approach but at least it identifies the problem