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

Question:

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 
Asked By: TNTOutburst

||

Answers:

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()
Answered By: kelkka

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 here is the picture

enter image description here

Answered By: ThunderHorn

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:

enter image description here

Answered By: Sayandip Dutta