Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

100x100 image with random pixel colour

I'm trying to make a 100x100 image with each pixel being a different random colour, like this example:

enter image description here

I've tried to use matplotlib but I'm not having much luck. Should I maybe be using PIL?

like image 844
IceDragon Avatar asked Mar 07 '13 02:03

IceDragon


3 Answers

If you want to create an image file (and display it elsewhere, with or without Matplotlib), you could use NumPy and Pillow as follows:

import numpy
from PIL import Image

imarray = numpy.random.rand(100,100,3) * 255
im = Image.fromarray(imarray.astype('uint8')).convert('RGBA')
im.save('result_image.png')

The idea here is to create a numeric array, convert it to a RGB image, and save it to file. If you want grayscale image, you should use convert('L') instead of convert('RGBA').

like image 82
heltonbiker Avatar answered Sep 23 '22 18:09

heltonbiker


This is simple with numpy and pylab. You can set the colormap to be whatever you like, here I use spectral.

from pylab import imshow, show, get_cmap
from numpy import random

Z = random.random((50,50))   # Test data

imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest')
show()

enter image description here

Your target image looks to have a grayscale colormap with a higher pixel density than 100x100:

import pylab as plt
import numpy as np

Z = np.random.random((500,500))   # Test data
plt.imshow(Z, cmap='gray', interpolation='nearest')
plt.show()

enter image description here

like image 28
Hooked Avatar answered Sep 21 '22 18:09

Hooked


import numpy as np
import matplotlib.pyplot as plt

img = (np.random.standard_normal([28, 28, 3]) * 255).astype(np.uint8)

# see the raw result (it is 'antialiased' by default)
_ = plt.imshow(img, interpolation='none')
# if you are not in a jupyter-notebook
plt.show()

Will give you this 28x28 RGB image:

img

like image 6
banderlog013 Avatar answered Sep 21 '22 18:09

banderlog013