PudgeKim
PudgeKim

Reputation: 153

how to convert 4d numpy array to PIL image?

I'm doing some image machine learning by keras and if i put one picture converted to numpy.array in my model, it returns a 4d numpy array(predicted picture).

I want to convert that array to image by using Image.fromarray in PIL library. but Image.fromarray only accept 2d array or 3d array.

my predicted picture's array shape is (1, 256, 256, 3) 1 means number of data. so 1 is useless data for image. I want to convert it to(256,256,3) with not damaging image data. what should I do? Thanks for your time.

Upvotes: 2

Views: 3342

Answers (1)

Finomnis
Finomnis

Reputation: 22456

1 is not useless data, it is a singular dimension. You can just leave it out, the size of the data wouldn't change.

You can do that with numpy.squeeze.

Also, make sure that your data is in the right format, for Image.fromarray this is uint8.

Example:

import numpy as np
from PIL import Image

data = np.ones((1,16,16,3))
for i in range(16):
    data[0,i,i,1] = 0.0

print("size: %s, type: %s"%(data.shape, data.dtype))
# size: (1, 16, 16, 3), type: float64

data_img = (data.squeeze()*255).astype(np.uint8)

print("size: %s, type: %s"%(data_img.shape, data_img.dtype))
# size: (16, 16, 3), type: uint8

img = Image.fromarray(data_img, mode='RGB')
img.show()

Upvotes: 2

Related Questions