Fundamentals 13 min read

Creating Images with NumPy: Random Grayscale, Color, Gradient, and Colormap Visualizations

This tutorial demonstrates how NumPy can be used to generate and display grayscale, color, gradient, and colormap‑enhanced images in Python with just a few lines of code, covering module import, array creation, image conversion, and advanced color mapping techniques.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Creating Images with NumPy: Random Grayscale, Color, Gradient, and Colormap Visualizations

NumPy can be used for image creation and visualization, allowing quick generation of grayscale, color, gradient, and colormap‑enhanced pictures with just a few lines of Python code.

1. Import Modules

Only NumPy is required for the drawing process; PIL's Image module is used to display or save the result, and Matplotlib's colormap can be optionally used for richer colors.

<code>import numpy as np
from PIL import Image
from matplotlib import cm as mplcm
</code>

2. Basic Drawing Process

Using Image.fromarray() , a NumPy array is converted to a PIL image. The array must be of type np.uint8 . The example creates a 100 × 300 random grayscale image and shows it.

<code>im = np.random.randint(0, 255, (100,300), dtype=np.uint8)
im = Image.fromarray(im)
im.show()  # or im.save(r'd:\gray_300_100.jpg')
</code>

3. Generate Random Color Image

If the random array has three channels, a color image is produced.

<code>>> im = np.random.randint(0, 255, (100,300,3), dtype=np.uint8)
>>> Image.fromarray(im, mode='RGB').show()
</code>

4. Generate Gradient Image

Using np.linspace() and np.tile() to build separate R, G, B channels, then stacking them with np.dstack() yields a smooth gradient picture.

<code>>> r = np.tile(np.linspace(192,255, 300, dtype=np.uint8), (600,1)).T
>>> g = np.tile(np.linspace(192,255, 600, dtype=np.uint8), (300,1))
>>> b = np.ones((300,600), dtype=np.uint8)*224
>>> im = np.dstack((r,g,b))
>>> Image.fromarray(im, mode='RGB').show()
</code>

5. Draw Curve on Gradient Background

By locating specific rows and columns in the image array and modifying their color, a sinusoidal curve is drawn on the gradient.

<code>>> r = np.tile(np.linspace(192,255, 300, dtype=np.uint8), (600,1)).T
>>> g = np.tile(np.linspace(192,255, 600, dtype=np.uint8), (300,1))
>>> b = np.ones((300,600), dtype=np.uint8)*224
>>> im = np.dstack((r,g,b))
>>> x = np.arange(600)
>>> y = np.sin(np.linspace(0, 2*np.pi, 600))
>>> y = np.int32((y+1)*0.9*300/2 + 0.05*300)
>>> for i in range(0, 150, 6):
...     im[y[:-i], (x+i)[:-i]] = np.array([255,0,255])
>>> Image.fromarray(im, mode='RGB').show()
</code>

6. Use Color Maps (ColorMap)

Matplotlib provides 82 colormaps grouped into categories such as visual‑uniform, sequential, diverging, cyclic, and miscellaneous. The example shows how to retrieve a colormap and query its colors.

<code>>> cm1 = mplcm.get_cmap('jet')   # custom class
>>> cm1.N                         # 256 colors
>>> cm1(0)                        # (0.0, 0.0, 0.5, 1.0)
>>> cm1(128)                      # (0.4901960784313725, 1.0, 0.4775458570524984, 1.0)
>>> cm1(255)                      # (0.5, 0.0, 0.0, 1.0)
>>> cm2 = mplcm.get_cmap('Paired') # segmented class
>>> cm2.N                         # 12 colors
>>> cm2(0)                        # (0.6509803921568628, 0.807843137254902, 0.8901960784313725, 1.0)
>>> cm2(11)                       # (0.6941176470588235, 0.34901960784313724, 0.1568627450980392, 1.0)
</code>

7. Showcase NumPy’s Power

The final function draw_picture builds coordinate grids, computes distances, applies two colormaps (jet for the whole image, Paired for a selected region), and displays the result.

<code>def draw_picture(w, h, cm1='jet', cm2='Paired'):
    cm1, cm2 = mplcm.get_cmap(cm1), mplcm.get_cmap(cm2)
    colormap1 = np.array([cm1(k) for k in range(cm1.N)])
    colormap2 = np.array([cm2(k) for k in range(cm2.N)])
    i, j = np.repeat(np.arange(h), w).reshape(h,w)-h//2, np.tile(np.arange(w), (h,1))-w//2
    d = np.hypot(i, j)
    e = d[(j*j/10) < i]
    d = np.int32((cm1.N-1)*(d-d.min())/(d.max()-d.min()))
    d = np.uint8(255*colormap1[d])
    e = np.int32((cm2.N-1)*(e-e.min())/(e.max()-e.min()))
    d[(j*j/10) < i] = np.uint8(255*colormap2[e])
    Image.fromarray(d).show()

draw_picture(1200, 900, cm1='jet', cm2='Paired')
</code>

Running this code reproduces the opening illustration, demonstrating how NumPy can serve as a compact yet powerful tool for image creation and visual data exploration.

image processingData VisualizationMatplotlibNumPyPIL
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.