DeeWBee - 1 year ago 112
Python Question

# Reshape (M, N, 3) numpy array to (M*N, 3)

Suppose I have an RGB (or HSV) image represented by an (M, N, 3) numpy array wherein each dimension (

`[x, y, 0]`
or
`[x, y, 1]`
) represents a color channel value at a specific pixel. I want to reshape the array to (M*N, 3) where the color channels are combined (
`[R1, G1, B1], [R2, G2, B2]`
...) into a flat list (is that the correct terminology in this case?). I understand that one must use the reshape function, but I'm having difficulty understanding how to use the function. Any help is appreciated.

EDIT: Here is an example of what I would like to happen.

Input: (640 x 640 x 3) array representative of image where
`[40, 40, 1]`
would be the G value for a specific pixel. I want to take all 3 color channels and combine them into the following output.

Output:
`([R, G, B], [R, G, B], [R, G, B]...)`

If `img` is your array, you can use `img.reshape(-1, 3)`.

For example,

``````In [50]: img.shape
Out[50]: (5, 2, 3)

In [51]: img
Out[51]:
array([[[2, 0, 4],
[1, 4, 3]],

[[2, 1, 4],
[3, 2, 2]],

[[2, 4, 1],
[4, 0, 2]],

[[1, 4, 2],
[3, 2, 2]],

[[3, 2, 1],
[2, 1, 0]]])

In [53]: x = img.reshape(-1, 3)

In [54]: x.shape
Out[54]: (10, 3)

In [55]: x
Out[55]:
array([[2, 0, 4],
[1, 4, 3],
[2, 1, 4],
[3, 2, 2],
[2, 4, 1],
[4, 0, 2],
[1, 4, 2],
[3, 2, 2],
[3, 2, 1],
[2, 1, 0]])
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download