0

I am trying to create a random image using NUMPY. First I am creating a random 3D array as it should be in the case of an image e.g. (177,284,3).

random_im = np.random.rand(177,284,3)

data = np.array(random_im)
print(data.shape)
Image.fromarray(data)

But when I am using Image.fromarray(random_array), this is throwing the following error.

enter image description here

Just to check if there is any issue with the shape of the array, I converted an image back to the array and converted it back after copying it to the other variable. And I got the output I was looking for.

img = np.array(Image.open('Sample_imgs/dog4.jpg'))
git = img.copy()
git.shape
Image.fromarray(git)

enter image description here

They both have the same shape, I don't understand where am I making the mistake.

When I am creating a 2D array and then converting it back it is giving me a black canvas of that size (even though the pixels should not be black).

random_im = np.random.randint(0,256,size=(231,177))

print(random_im)
# data = np.array(random_im)
print(data.shape)
Image.fromarray(random_im)

1 Answers1

2

I was able to get this working with the solution detailed here:

import numpy as np
from PIL import Image
random_array = np.random.rand(177,284,3)
random_array = np.random.random_sample(random_array.shape) * 255
random_array = random_array.astype(np.uint8)
random_im = Image.fromarray(random_array)
random_im.show()

----EDIT A more elegant way to get a random array of the correct type without conversions is like so:

import numpy as np
from PIL import Image
random_array = np.random.randint(low=0, high=255,size=(250,250),dtype=np.uint8)
random_im = Image.fromarray(random_array)
random_im.show()

Which is almost what you were doing in your solution, but you have to specify the dtype to be np.uint8:

random_im = np.random.randint(0,256,size=(231,177),dtype=np.uint8)
0x263A
  • 1,807
  • 9
  • 22
  • Yeah I was also using the randint at first. The main issue was dtype after all. Thanks Buddy. Can you explain the reason we need this dtype? – Shashank Chaudhary Jul 17 '21 at 19:29