简体   繁体   中英

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!

Do you only need to invert the last dimension? Try

framebuffer = framebuffer [:, :, :2:-1] # drops alpha

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM