Home > database >  How to convert Numpy Linear Array of pixels to Numpy multi dimensional image array
How to convert Numpy Linear Array of pixels to Numpy multi dimensional image array

Time:11-03

Hello i have a problem in which there is linear list of pixels like this:

[  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
 131 131 131 134 134 134 137 137 137 139 139 139 141 141]

I want to convert it into :


[[[  0   0   0]
  [  0   0   0]
  [  0   0   0]
  ...
  [145 145 145]
  [148 148 148]
  [149 149 149]]

Like normal numpy image array.

Thank for your help.

CodePudding user response:

numpy reshape is what you are looking for. https://numpy.org/doc/stable/reference/generated/numpy.reshape.html

However notice when you are reshaping a numpy array your new shape must contains same number of elements as the input array:

import numpy as np

a = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              131, 131, 131, 134, 134, 134, 137, 137, 137, 139, 139, 139, 141, 141])

print(a.reshape((10, 5)))

So in your example you cannot convert 50 element array to a 3xm matrix.

CodePudding user response:

Use numpy.reshape() with -1, numpy will try to set first dimension by itself.

>>> import numpy
>>> a = numpy.arange(6)
>>> a
array([0, 1, 2, 3, 4, 5])
>>> a.reshape((-1,3))
array([[0, 1, 2],
       [3, 4, 5]])
  • Related