Sarthak Gupta
Sarthak Gupta

Reputation: 813

store images of different dimension in numpy array

I have two images , image 1 of dimension (32,43,3) and image2 of dimension (67,86,3) . How can i store this in a numpy array , Whenever i try to append the array

image=cv2.imread(image1,0)
image=cv2.resize(image,(32,43))
x_train=np.array(image.flatten())
x_train=x_train.reshape(-1,3,32,43)
X_train =np.append(X_train,x_train) #X_train is my array

image=cv2.imread(image2,0)
image=cv2.resize(image,(67,86))
x_train=np.array(image.flatten())
x_train=x_train.reshape(-1,3,67,86)
X_train =np.append(X_train,x_train) 

Value Error: total size of new array must be unchanged.

i want the X_train in shape (-1,depth,height,width).So that i can feed it into my neural network. Is there any way to store images of different dimension in array and feed into neural network ?

Upvotes: 4

Views: 4535

Answers (1)

hpaulj
hpaulj

Reputation: 231385

Don't use np.append. If you must join arrays, start with np.concatenate. It'll force you to pay more attention to the compatibility of dimensions.

You can't join 2 arrays with shapes (32,43,3) (67,86,3) to make a larger array of some compatible shape. The only dimension they share is the last.

These reshapes don't make sense either: (-1,3,32,43), (-1,3,67,86).

It works, but it also messes up the 'image'. You aren't just adding a 4th dimension. It looks like you want to do some axis swapping or transpose as well. Practice with some small arrays so you can see what's happening, e.g. (2,4,3).

What final shape do you expect for Xtrain?

You can put these two images in a object dtype array, which is basically the same as the list [image1, image2]. But I doubt if your neuralnet can do anything practical with that.


If you reshaped the (32,43,3) array to (16,86,3) you could concatenate that with (67,86,3) on axis=0 to produce a (83,86,3) array. If you needed the 3 to be first, I'd use np.transpose(..., (2,0,1)).

Conversely reshape (67,86,3) to (2*67,43,3).

Passing the (32,43,3) to (32,86,3) is another option.

Joining them on a new 4th dimension, requires that the number of 'rows' match as well as the number of 'columns'.

Upvotes: 3

Related Questions