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

10,684

Solution 1

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)

Solution 2

more easier would be to just add another axis in your Images and append them

    old_image = np.ones((100,100,3))
    new_image = np.ones((100,100,3,1))    
    # lets jsut say you have two Images 
    old_image = np.reshape(old_image , (100,100,3,1))
    new_image = np.reshape(new_image , (100,100,3,1))
    directory = np.append( new_image , old_image , axis = 3)
Share:
10,684
Bavaraa
Author by

Bavaraa

Updated on July 22, 2022

Comments

  • Bavaraa
    Bavaraa almost 2 years

    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?