Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save 3D array results to a 4D array in Python/numpy?

I am reading the information about 32 X 32 RGB images. So it is a 3D array with shape (32,32,3) third dimension holds the color R, G and B

Now, I want to read 50 such images and make a array of these images. So I decide to make a 4D array which will have dimension (50, 32, 32, 3) here 50 in first dimension is the number of images and the second, third and fourth dimension are the dimension of the image which are (32, 32, 3)

I tried doing it using concatenate but I get errors. Is there any way to do this?

like image 977
Bavaraa Avatar asked Nov 03 '15 11:11

Bavaraa


People also ask

How do you reshape an array from 3D to 2D in python?

reshape() is an inbuilt function in python to reshape the array. We can reshape into any shape using reshape function. This function gives a new shape to the array.

How do I save a 3D NumPy array to CSV?

You can use the np. savetxt() method to save your Numpy array to a CSV file.


1 Answers

You need to add an axis before concatenation, e.g.

import numpy as np
arrs = [np.random.random((32, 32, 3))
        for i in range(50)]

res = np.concatenate([arr[np.newaxis] for arr in arrs])
res.shape
# (50, 32, 32, 3)

Edit: alternatively, in this case you can simply call np.array on your list of arrays:

res = np.array(arrs)
res.shape
# (50, 32, 32, 3)
like image 170
jakevdp Avatar answered Jan 02 '23 21:01

jakevdp