Abhay
Abhay

Reputation: 359

1D array to RGB image?

I have a 1D array of images in which 32X32 color image is stored, first 1024 as red, 1024 green and 1024 blue. Image stored in row major order so now the first 32 entries of the array are the red channel values of the first row of the image.

Sample looks like X[0]

(array([255., 252., 253., ..., 173., 231., 248.], dtype=float32)

I tried reshaping the array in to 3 parts but the image constructed doesn't look like anything.

Code

a = X[0].reshape(3,-1).T.reshape(32,-1,3)
Image.fromarray(a, 'RGB')

The resulting image looks like this

enter image description here

Maybe the dataset is just random numbers.

Upvotes: 0

Views: 2831

Answers (1)

Divakar
Divakar

Reputation: 221704

We need to permute axes and for the same we can use np.transpose -

H,W = 32,32 # image dimensions
img_0 = X[0].reshape(3,H,W).transpose(1,2,0)

If you have an array of images stored in rows in a 2D array, i.e. first row denoting X[0], second row being X[1] and so on, we can get back all the images and that would be a 4D array, like so -

img_all = X.reshape(-1,3,H,W).transpose(0,2,3,1)

To verify things, let's create a minimal setup :

# This is what we want as final output
In [46]: a = np.arange(18).reshape(2,3,3)

    In [52]: a
    Out[52]: 
    array([[[ 0,  1,  2],
            [ 3,  4,  5],
            [ 6,  7,  8]],

           [[ 9, 10, 11],
            [12, 13, 14],
            [15, 16, 17]]])

In [47]: H,W = 2,3 # img dimensions

# This is what we have
In [63]: b = np.hstack([a[...,i].ravel() for i in range(3)])

In [64]: b
Out[64]: 
array([ 0,  3,  6,  9, 12, 15,  1,  4,  7, 10, 13, 16,  2,  5,  8, 11, 14,
       17])

# Check if the proposed soln gives us "a" back
In [51]: np.allclose(a, b.reshape(3,H,W).transpose(1,2,0))
Out[51]: True

Upvotes: 4

Related Questions