简体   繁体   English

将一维numpy数组转换为3D RGB数组

[英]Transform 1-D numpy array into 3D RGB array

What is the best way to transform an 1D array that contains rgb data into a 3D RGB array ? 将包含rgb数据的1D数组转换为3D RGB数组的最佳方法是什么?

If the array was in this order, it would be easy, (a single reshape) 如果数组按此顺序排列,那就很容易了(一次整形)

RGB RGB RGB RGB... RGB RGB RGB RGB ...

However my array is in the form, 但是我的数组形式是

RRRR...GGGG....BBBB RRRR ... GGGG .... BBBB

or sometimes even, 甚至有时

GGGG....RRRR....BBBB (result still should be RGB not GRB) GGGG .... RRRR .... BBBB(结果仍然应该是RGB而不是GRB)

I could of course derive some Python way to achieve this, I even did try a numpy solution, it works but It is obviously a bad solution, I wonder what is the best way, maybe a built-in numpy function ? 我当然可以派生一些Python的方法来实现这一点,我什至尝试了numpy解决方案,但是它显然是一个不好的解决方案, 我想知道什么是最好的方法,也许是内置的numpy函数?

My solution: 我的解决方案:

for i in range(len(video_string) // 921600 - 1):        # Consecutive frames iterated over.
    frame = video_string[921600 * i: 921600 * (i + 1)]  # One frame
    array = numpy.fromstring(frame, dtype=numpy.uint8)  # Numpy array from one frame.
    r = array[:307200].reshape(480, 640)
    g = array[307200:614400].reshape(480, 640)
    b = array[614400:].reshape(480, 640)
    rgb = numpy.dstack((b, r, g))                       # Bring them together as 3rd dimention

Don't let the for loop confuse you, I just have frames concatenated to each other in a string, like a video, which is not a part of the question. 不要让for循环使您感到困惑,我只是将帧以字符串的形式彼此串联在一起,例如视频,这不是问题的一部分。

What did not help me: In this question, r, g, b values are already 2d arrays so not helping my situation. 什么没有帮助我:在这个问题上,r,g,b值已经是2d数组,因此对我的情况没有帮助。

Edit1: Desired array shape is 640 x 480 x 3 编辑1:所需的数组形状是640 x 480 x 3

Reshape to 2D , transpose and then reshape back to 3D for RRRR...GGGG....BBBB form - 重塑为2D并进行转置,然后重塑为3D以进行RRRR...GGGG....BBBB形式-

a1D.reshape(3,-1).T.reshape(height,-1,3) # assuming height is given

Or use reshape with Fortran order and then swap axes - 或对Fortran顺序使用整形,然后交换轴-

a1D.reshape(-1,height,3,order='F').swapaxes(0,1)

Sample run - 样品运行-

In [146]: np.random.seed(0)

In [147]: a = np.random.randint(11,99,(4,2,3)) # original rgb image

In [148]: a1D = np.ravel([a[...,0].ravel(), a[...,1].ravel(), a[...,2].ravel()])

In [149]: height = 4

In [150]: np.allclose(a, a1D.reshape(3,-1).T.reshape(height,-1,3))
Out[150]: True

In [151]: np.allclose(a, a1D.reshape(-1,height,3,order='F').swapaxes(0,1))
Out[151]: True

For GGGG....RRRR....BBBB form, simply append : [...,[1,0,2]] . 对于GGGG....RRRR....BBBB表格,只需附加: [...,[1,0,2]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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