简体   繁体   English

将Numpy数组的第3维分配给1D数组的Python方法

[英]Pythonic way to assign 3rd Dimension of Numpy array to 1D Array

I'm trying to flatten an image that's been converted to a 3D numpy array into three separate 1D arrays, representing RGB channels. 我试图将已转换为3D numpy数组的图像展平为三个单独的1D数组,分别表示RGB通道。

The image array is shaped (HEIGHT, WIDTH, RGB), and I've tried in vain to use both index slicing and unzipping to just return the 3rd dimension values. 图像数组的形状是(HEIGHT,WIDTH,RGB),并且我尝试使用索引切片和解压缩来仅返回第3维值是徒劳的。

Ideally, three separate arrays represent each RGB channel, 理想情况下,三个独立的阵列代表每个RGB通道,

Example: 例:

print(image)
[
[ [56, 6, 3], [23, 32, 53], [27, 33, 56] ],
[ [57, 2, 3], [23, 246, 49], [29, 253, 58] ]
]


red_channel, green_channel, blue_channel = get_third(image)
print(red_channel)
[56, 23, 27, 57, 23, 29]

I've thought of just using a nested for loop to iterate over the first two dimensions and then add each RGB array to a list or what not, but its my understanding that this would be both inefficient and a bit of an eyesore. 我曾经考虑过使用嵌套的for循环在前两个维度上进行迭代,然后将每个RGB数组添加到列表中,或者不添加到列表中,但这是我的理解,这既效率低下又让人有些费解。

Thanks in advance! 提前致谢!

EDIT 编辑

Clarification: By unzipping I mean using the star operator (*) within the zip function, like so: 说明:通过解压缩,我的意思是在zip函数中使用star运算符(*),如下所示:

zip(*image)

Also to clarify, I don't intend to retain the width and height, I just want to essentially only flatten and return the 3D dimension of the array. 同样要澄清的是,我无意保留宽度和高度,我只想基本上只展平并返回数组的3D尺寸。

red_channel, green_channel, blue_channel = np.transpose(np.reshape(image, (-1, 3)))

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

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