Alex - 1 year ago 78

Python Question

Given a 300 numpy array of values, where the first 100 are Red pixel values , the second 100 Green and the last 100 Blue, is there quick way using reshape to rearrange this initial 1x300 list into a 100x3 matrix where each line contains the matching RGB values ?

Answer Source

To be more manageable, let's suppose that you have a numpy array, `pix`

, with 30 values, the first ten of which are red, then 10 green, then 10 blue. For example:

```
>>> import numpy as np
>>> pix = np.arange(30)
>>> pix
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29])
```

To reshape that into a 10x3 array of RGB values, use:

```
>>> pix.reshape(3, 10).transpose()
array([[ 0, 10, 20],
[ 1, 11, 21],
[ 2, 12, 22],
[ 3, 13, 23],
[ 4, 14, 24],
[ 5, 15, 25],
[ 6, 16, 26],
[ 7, 17, 27],
[ 8, 18, 28],
[ 9, 19, 29]])
```