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 

3 Answers

You can use numpy.random.randint to assemble the required array efficiently, in a single 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:

1

First create your numpy array and then put it into PIL

import numpy as np
from random import randint
from PIL import Image

array = np.array([[[randint(0, 255),randint(0, 255),randint(0, 255)]] for i in range(100)])
array =  np.reshape(array.astype('uint8'), (10, 10, 3))
img = Image.fromarray(np.uint8(array.astype('uint8')))

img.save('pil_color.png')

this worked for me

The PIL Image is an Image object, into which you can't simply inject those values to the specified pixel. Instead, convert to an array and then show it as PIL image.

import random
import numpy as np
from PIL import Image

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

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]
img = Image.fromarray(im, 'RGB')

img.show()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest