将uint32的元组转换为uint8的3d numpy数组的最佳方法

问题描述

我从外部api获得了以uint32s元组表示的图像,其中每个uint32包含4个uint8,分别带有r,g,b和alpha(始终= 0),我需要将其转换为格式相同的3d numpy数组从imageio.imread可以得到什么。问题是,当我使用numpy.view时,颜色顺序颠倒了。这是我编写的可以正常工作的代码,但是我想知道是否有更好的转换方法

        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],0]),axis=2) # here I've got correct numpy height x width x 3 array

我更关心执行时间,而不是内存,但是由于我可以拥有7680××4320的图像,所以两者都可能很重要。谢谢!

解决方法

您只需要反转最后一个尺寸?试试

def counter(start,stop):
x = start
if start > stop:
    return_string = "Counting down: "
    while x >= stop:
        return_string += str(x)
        if x != stop :
            return_string += ","
        x -= 1
else:
    return_string = "Counting up: "
    while x <= stop:
        return_string += str(x)
        if x != stop:
            return_string += ","
        x += 1
return return_string

print(counter(1,10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2,1)) # Should be "Counting down: 2,1"
print(counter(5,5)) # Should be "Counting up: 5"
,

@RichieV为我指明了正确的方向,实际上有效的是:

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

我现在将其标记为解决方案,直到有人提出解决该问题的方法。