Unable to resize numpy array

I have a function that should take a 1D array of integers and form it into a 2D array of 1x3 arrays. Then it should take each 1x3 array and transfer it to the 3x1 array. The result should be a 2D array of 3x1 arrays. Here is my function

def RGBtoLMS(rgbValues, rgbLength): #Method to convert from RGB to LMS print rgbValues lmsValues = rgbValues.reshape(-1, 3) print lmsValues for i in xrange(len(lmsValues)): lmsValues[i] = lmsValues[i].reshape(3, 1) return lmsValues 

The problem occurs when I try to change 1x3 arrays to 3x1 arrays. I get the following output: rgbValues ​​= [14, 25, 19, 24, 25, 28, 58, 87, 43]

 [14 25 19 ..., 58 87 43] [[14 25 19] [24, 25, 28] [58 87 43]] ValueError [on line lmsValues[i] = lmsValues[i].reshape(3, 1)]: could not broadcast input array from shape (3,1) into shape (3) 

How to avoid this error?

+6
source share
1 answer

As mentioned in the comments, you really just change one array with different shapes. It doesn't make sense in numpy to say that you have a 2d array of 1 x 3 arrays. Actually this is really an nx 3 array.

We start with a 1d array of length 3*n (I added three numbers to your example to make the difference between an array of 3 xn and nx 3 ):

 >>> import numpy as np >>> rgbValues = np.array([14, 25, 19, 24, 25, 28, 58, 87, 43, 1, 2, 3]) >>> rgbValues.shape (12,) 

And change it as nx 3 :

 >>> lmsValues = rgbValues.reshape(-1, 3) >>> lmsValues array([[14, 25, 19], [24, 25, 28], [58, 87, 43], [ 1, 2, 3]]) >>> lmsValues.shape (4, 3) 

If you want each element to be formed 3 x 1 , perhaps you just want to move the array. This toggles rows and columns, so form 3 xn

 >>> lmsValues.T array([[14, 24, 58, 1], [25, 25, 87, 2], [19, 28, 43, 3]]) >>> lmsValues.T.shape (3, 4) >>> lmsValues.T[0] array([14, 24, 58, 1]) >>> lmsValues.T[0].shape (4,) 

If you really want each element in lmsValues be a 1 x 3 array, you can do this, but then it should be a three-dimensional array with the form nx 1 x 3 :

 >>> lmsValues = rgbValues.reshape(-1, 1, 3) >>> lmsValues array([[[14, 25, 19]], [[24, 25, 28]], [[58, 87, 43]], [[ 1, 2, 3]]]) >>> lmsValues.shape (4, 1, 3) >>> lmsValues[0] array([[14, 25, 19]]) >>> lmsValues[0].shape (1, 3) 
+5
source

Source: https://habr.com/ru/post/958962/


All Articles