Sibi
Sibi

Reputation: 2421

Reshape array to rgb matrix

I have loaded a 100x100 rgb image in a numpy array. I then converted it to a 30000x1 numpy array to pass through a machine learning model. The output of this model is also a 30000x1 numpy array. How do I convert this array back to a numpy array of 100x100 3-tuples so I can print the generated rgb image?

If the initial array is [r1 g1 b1],[r2 g2 b2],...,[], it is unrolled to [r1 g1 b1 r2 g2 b2 ...]. I need it back in the form [r1 g1 b1],[r2 g2 b2],...,[].

What I used to load the image as array:

im=img.resize((height,width), Image.ANTIALIAS);
im=np.array(im);
im=im.ravel();

I have tried .reshape((100,100,3)) and I'm getting a black output image. The machine learning model is correct and it is not the reason for getting a black output.

Upvotes: 4

Views: 6610

Answers (1)

Priyatham
Priyatham

Reputation: 2897

Try reshape((3, 100, 100))

a = np.random.random((3, 2, 2))
# array([[[ 0.28623689,  0.96406455],
#         [ 0.55002183,  0.73325715]],
#
#        [[ 0.44293834,  0.08118479],
#         [ 0.28732176,  0.94749812]],
#
#        [[ 0.40169829,  0.0265604 ],
#         [ 0.07904701,  0.19342463]]])
x = np.ravel()
# array([ 0.28623689,  0.96406455,  0.55002183,  0.73325715,  0.44293834,
#         0.08118479,  0.28732176,  0.94749812,  0.40169829,  0.0265604 ,
#         0.07904701,  0.19342463])
print(x.reshape((2, 2, 3)))
# array([[[ 0.28623689,  0.96406455,  0.55002183],
#         [ 0.73325715,  0.44293834,  0.08118479]],

#        [[ 0.28732176,  0.94749812,  0.40169829],
#         [ 0.0265604 ,  0.07904701,  0.19342463]]])
print(x.reshape((3, 2, 2)))
# array([[[ 0.28623689,  0.96406455],
#         [ 0.55002183,  0.73325715]],
#
#        [[ 0.44293834,  0.08118479],
#         [ 0.28732176,  0.94749812]],
#
#        [[ 0.40169829,  0.0265604 ],
#         [ 0.07904701,  0.19342463]]])

Upvotes: 3

Related Questions