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.

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.

Ideally, three separate arrays represent each RGB channel,

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.

Thanks in advance!

EDIT

Clarification: By unzipping I mean using the star operator (*) within the zip function, like so:

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.

Upvotes: 0

Views: 508

Answers (1)

yuri kilochek
yuri kilochek

Reputation: 13486

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

Upvotes: 1

Related Questions