Search code examples
pythonimagepython-imaging-library

Trying to Generate Random Picture with PIL, but get strange result


Generated Pictured

enter image description here

I used this code to generate a random picture by filling out each pixel, but why I got this strange output (picture at the above link)? There are parallel red, green, blue vertical lines in the picture.

#<Python 3.8>
from PIL import Image
import numpy as np
data=np.random.randint(low=0,high=256,size=128*128*3)
data=data.reshape(128,128,3)
Image.fromarray(data,'RGB')

Solution

  • PIL's RGB mode expects 8-bit color channels, but your array most likely has a dtype of int32. 75% of each of your integers are composed of unused 0 bits, which is why 75% of your image is black stripes.

    Try setting your data's dtype to unit8 when you call randint.

    from PIL import Image
    import numpy as np
    data=np.random.randint(low=0,high=256,size=128*128*3, dtype=np.uint8)
    data=data.reshape(128,128,3)
    Image.fromarray(data,'RGB').save("output.png")
    

    Result (one possibility of many):

    enter image description here