Search code examples
pythonimageimage-processingrandomcolors

How do you generate an image where each pixel is a random color in python


I'm trying to make an image with a random color for each pixel then open a window to see the image.

import PIL, random
import matplotlib.pyplot as plt 
import os.path  
import PIL.ImageDraw            
from PIL import Image, ImageDraw, ImageFilter


im = Image.new("RGB", (300,300))

for r in range(0,300):
    for c in range(0,300):
        re = random.randint(0, 255)
        gr = random.randint(0, 255)
        bl = random.randint(0, 255)
        im[r][c]=[re,gr,bl]
im.show()

     14         bl = random.randint(0, 255)
---> 15         im[r][c]=[re,gr,bl]
     16 im.show()
TypeError: 'Image' object does not support indexing 

Solution

  • You can use numpy.random.randint to assemble the required array efficiently, in a single logical line.

    import numpy as np
    from PIL import Image
    
    # numpy.random.randint returns an array of random integers
    # from low (inclusive) to high (exclusive). i.e. low <= value < high
    
    pixel_data = np.random.randint(
        low=0, 
        high=256,
        size=(300, 300, 3),
        dtype=np.uint8
    )
    
    image = Image.fromarray(pixel_data)
    image.show()
    

    Output:

    enter image description here