0

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.

  • Check this once: https://stackoverflow.com/questions/13730468/from-nd-to-1d-arrays – Deepanshu Apr 29 '19 at 04:00
  • What do you mean by `unzipping`? `image[:,:,0]` selects one channel; the result is 2d `(height,width)`. `reshape` or `ravel` can be used to reshape that 2d to 1d. – hpaulj Apr 29 '19 at 04:05
  • `*array` like `list(array)` operates on the first dimension of an array, just as it would on a nested list. – hpaulj Apr 29 '19 at 04:38

1 Answers1

1
red_channel, green_channel, blue_channel = np.transpose(np.reshape(image, (-1, 3)))
yuri kilochek
  • 12,709
  • 2
  • 32
  • 59