Create Stunning Images with Just 10 Lines of NumPy Code
Learn how to generate grayscale, random color, gradient, and custom visualizations using only NumPy (and optional Matplotlib ColorMaps) with concise Python code, covering array creation, image conversion, pixel manipulation, and advanced colormap techniques for powerful data art.
NumPy can be used for image creation and visualization, allowing you to produce various types of images with just a few lines of code. By importing only NumPy (and optionally PIL for display or saving) and using Matplotlib's ColorMap for richer colors, you can explore interactive programming and generate impressive graphics.
1. Import Modules
Import NumPy, PIL's Image module, and Matplotlib's cm module (optional for color mapping).
import numpy as np
from PIL import Image
from matplotlib import cm as mplcm2. Basic Drawing Process
Use Image.fromarray() to convert a NumPy array to a PIL image. The array must be of type np.uint8 (or np.ubyte). The example creates a 100×300 random grayscale image and displays it.
im = np.random.randint(0, 255, (100, 300), dtype=np.uint8)
im = Image.fromarray(im)
im.show() # or im.save('gray_300_100.jpg')3. Generate Random Color Image
By generating a three‑channel array, you obtain a random RGB image.
im = np.random.randint(0, 255, (100, 300, 3), dtype=np.uint8)
Image.fromarray(im, mode='RGB').show()4. Generate Gradient Image
Use np.linspace() to create linear gradients for each color channel, repeat them with np.tile(), and stack with np.dstack() to form a gradient image.
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()5. Draw Curve on Gradient Background
After locating specific rows and columns, modify their colors to draw a curve.
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()6. Use ColorMap (Color Mapping)
ColorMaps transform numeric data into visually appealing colors. Matplotlib provides 82 maps across several categories (uniform, sequential, diverging, cyclic, etc.). Example code shows how to retrieve a map, query its size, and obtain specific colors.
cm1 = mplcm.get_cmap('jet') # 256 colors
cm1.N
cm1(0) # first color
cm1(128) # middle color
cm1(255) # last color
cm2 = mplcm.get_cmap('Paired') # 12 colors
cm2.N
cm2(0)
cm2(11)7. Demonstrate NumPy's Power
Create coordinate grids for an image of size 9×7, shift them to center at (0,0), and compute Euclidean distances with np.hypot(). These distances can then be mapped to colors using the chosen ColorMaps.
w, h = 9, 7
i = np.repeat(np.arange(h), w).reshape(h, w)
j = np.tile(np.arange(w), (h, 1))
i = i - h//2
j = j - w//2
d = np.hypot(i, j)8. Custom Drawing Function
The function draw_picture combines the previous steps: it builds coordinate grids, computes distances, applies a primary ColorMap to the whole image, selects a region where j*j < 10*i, and recolors that region with a secondary ColorMap.
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')Running the above code reproduces the opening illustration, demonstrating how a few NumPy operations can create complex and colorful visual art.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
