Search code examples
pythonnumpyjavax.imageio

Best way of converting tuple of uint32's to 3d numpy array of uint8's


I've got image from external api presented as tuple of uint32s, where each uint32 consists of 4 uint8 with r, g, b and alpha (always = 0) and i need to convert it to 3d numpy array with format identical to what I can get from imageio.imread. Problem is that when I use numpy.view order of colors is inverted. This is code I've written that works OK, but I was wondering if there's better way of conversion.

        frame_buffer_tuple = ... # here we have tuple of width*height length
        framebuffer = np.asarray(frame_buffer_tuple).astype(dtype='uint32').view(dtype='uint8').reshape((height, width, 4)) # here I have height x width x 4 numpy array but with inverted colors (red instead of blue) and alpha I don't need
        framebuffer = np.stack((framebuffer[:, :, 2], framebuffer[:, :, 1], framebuffer[:, :, 0]), axis=2) # here I've got correct numpy height x width x 3 array

I'm more concerned about execution time, then memory, but since I can have 7680 × 4320 images, both may be important. Thanks!


Solution

  • @RichieV pointed me in right direction, actually what worked is:

    framebuffer = np.asarray(frame_buffer_tuple).astype('uint32').view('uint8').reshape((height, width, 4))[:, :, 2::-1]
    

    I'll mark this as solution for now, until someone comes up with even solution to this problem.