An Image Is a NumPy Array: Channels, Brightness, Grayscale, Invert and Crop
Treat a picture as a 3D NumPy array: build a 4 by 6 test image, lift out its channels, brighten it without uint8 wraparound, turn it gray, invert and crop it, then check an AI-written pipeline by its values. Plus a sales challenge.
What you will learn
- Build an image as a (height, width, 3) uint8 array with no image library
- Slice out channels, crop, invert and turn an image to grayscale with array maths
- Brighten safely: widen, add, clip and convert back to avoid uint8 wraparound
- Check AI-written array code by testing values, not only shapes and dtypes
Before you start
- NumPy indexing and slicing
- NumPy dtypes and broadcasting
- NumPy aggregation with axis
Every photo on your phone is a NumPy array in disguise, and every edit to it is plain array maths. In this lesson you'll build a tiny image with no image library, change its numbers channel by channel, then write one clear prompt for the whole pipeline and check what comes back.
An image is a 3D array
Think about a wall of small tiles, where each tile has three dials: red, green and blue. That's an image. Four rows, six tiles in each row, three dials on each, so the shape is (4, 6, 3).
import numpy as np
h, w = 4, 6
img = np.zeros((h, w, 3), dtype=np.uint8)
img[:, :, 0] = np.linspace(0, 255, w)
img[:, :, 1] = np.linspace(0, 255, h).reshape(-1, 1)
print(img.shape, img.dtype)
print(img[0, 0])
print(img[3, 5])
print(img[2, 4])
(4, 6, 3) uint8
[0 0 0]
[255 255 0]
[204 170 0]
np.zeros starts with every dial at zero, so the grid is black. uint8 holds whole numbers from 0 to 255. Channel 0 gets six values across, so red grows left to right. Channel 1 gets four values reshaped into a column, and broadcasting copies them across, so green grows top to bottom. Blue is never touched, so it stays 0. One pixel is three numbers: black at the top left, yellow at the bottom right.
image_gray.py.One channel at a time
red = img[:, :, 0]
green = img[:, :, 1]
blue = img[:, :, 2]
print(red.shape)
print(red)
print(green)
print(blue)
(4, 6)
[[ 0 51 102 153 204 255]
[ 0 51 102 153 204 255]
[ 0 51 102 153 204 255]
[ 0 51 102 153 204 255]]
[[ 0 0 0 0 0 0]
[ 85 85 85 85 85 85]
[170 170 170 170 170 170]
[255 255 255 255 255 255]]
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]]
img[:, :, 0] means every row, every column, channel 0. Picking one channel removes that axis, so the shape is (4, 6). A channel is just a slice.
Brightness, wraparound and clip
a = np.array([250, 100], dtype=np.uint8)
print(a + 50)
wide = a.astype(np.int16) + 50
print(wide)
print(np.clip(wide, 0, 255).astype(np.uint8))
bright = np.clip(img.astype(np.int16) + 50, 0, 255)
bright = bright.astype(np.uint8)
print(img[0, :, 0])
print(bright[0, :, 0])
[ 44 150]
[300 150]
[255 150]
[ 0 51 102 153 204 255]
[ 50 101 152 203 254 255]
Look at that first line. 250 + 50 gave 44: a bright pixel just turned dark, with no error and no warning. A uint8 can't hold 300. It counts up to 255, rolls back to 0 and keeps going, like an old trip meter rolling over. That's wraparound.
The safe recipe: widen to int16 so the sum can be 300, np.clip it between 0 and 255, and convert back to uint8. On the whole image, the top row of red goes from 0, 51, 102 to 50, 101, 152, and the last value stays at 255. Widen, add, clip, convert back.
Grayscale
gray = img.mean(axis=2).astype(np.uint8)
print(gray.shape)
print(img[3, 5], gray[3, 5])
print(gray)
(4, 6)
[255 255 0] 170
[[ 0 17 34 51 68 85]
[ 28 45 62 79 96 113]
[ 56 73 90 107 124 141]
[ 85 102 119 136 153 170]]
One brightness number per pixel instead of three. mean(axis=2) averages along the channels, so that axis collapses (the axis you name disappears). The bottom right pixel, 255, 255 and 0, averages to 170. astype turns decimal averages back into whole numbers. Photo tools often weigh green more, but the plain average shows the idea.
Invert and crop
inverted = (255 - img).astype(np.uint8)
print(inverted.shape, inverted.dtype)
print(img[0, 0], inverted[0, 0])
print(img[3, 5], inverted[3, 5])
(4, 6, 3) uint8
[0 0 0] [255 255 255]
[255 255 0] [ 0 0 255]
Black becomes white, and yellow becomes blue. Nothing wraps, because 255 minus a value from 0 to 255 can't leave the range.
cropped = img[1:3, 2:5]
print(cropped.shape)
print(cropped[:, :, 0])
print(cropped[0, 0])
(2, 3, 3)
[[102 153 204]
[102 153 204]]
[102 85 0]
Cropping is only slicing: rows 1 and 2, columns 2 to 4, and all the channels are still there. So invert is maths on each value, and crop is a slice.
One clear prompt
You've seen each operation, so now you can ask for the whole thing. This is image_prompt.txt, in the Role, Context, Task, Format shape:
Role: You are a NumPy teacher for beginners.
Context: I have a 4 x 6 image stored as a uint8
array of shape (4, 6, 3). No image library.
Task: Write one script that brightens it by 50,
turns it to grayscale, inverts it, and crops it.
Format: One .py file, short comments, and a print
of each result's shape and dtype.
Four short lines, and each one is something you can check later. Here's one possible result:
steps = {}
steps["Original"] = img
steps["Red channel"] = img[:, :, 0]
steps["Brightness"] = np.clip(
img.astype(np.int16) + 50, 0, 255).astype(np.uint8)
steps["Grayscale"] = img.mean(axis=2).astype(np.uint8)
steps["Inverted"] = (255 - img).astype(np.uint8)
steps["Cropped"] = img[1:3, 2:5]
for name, arr in steps.items(): # printing only
print(f"{name:12} {arr.shape} {arr.dtype}")
print(len(steps), "operations")
Original (4, 6, 3) uint8
Red channel (4, 6) uint8
Brightness (4, 6, 3) uint8
Grayscale (4, 6) uint8
Inverted (4, 6, 3) uint8
Cropped (2, 3, 3) uint8
6 operations
Each operation is one line, and the only loop is for printing. Yours will look different, and that's fine.
Read the output against the prompt
No image library, four operations, shapes and dtypes printed: it's all there. But here's the catch. If the code had used img + 50, that table would look exactly the same, because wraparound keeps the shape and the dtype. So test what the results should do:
wrapped = img + 50
clipped = np.clip(
img.astype(np.int16) + 50, 0, 255).astype(np.uint8)
gray = img.mean(axis=2).astype(np.uint8)
cropped = img[1:3, 2:5]
print("shape is 4 x 6 x 3:", img.shape == (4, 6, 3))
print("gray has no channels:", gray.ndim == 2)
print("crop is 2 x 3:", cropped.shape[:2] == (2, 3))
print("wrap never darker:", bool((wrapped >= img).all()))
print("clip never darker:", bool((clipped >= img).all()))
shape is 4 x 6 x 3: True
gray has no channels: True
crop is 2 x 3: True
wrap never darker: False
clip never darker: True
A brightened image should never be darker than the original. For the wrapped version that's False: there's the bug. A shape tells you the size; it can't tell you the values are right. Check both. (More on this habit in checking AI-written Python code.)
Challenge: sales
Four items (pens, cups, bags, lamps) over twelve months, from a fixed seed, so the shape is (4, 12). Fill in quarterly totals, the total per item, the top two items, and a running total. One possible result:
import numpy as np
rng = np.random.default_rng(3)
items = np.array(["pens", "cups", "bags", "lamps"])
sales = rng.integers(100, 1000, size=(4, 12))
quarterly = sales.reshape(4, 4, 3).sum(axis=2)
revenue = sales.sum(axis=1)
order = revenue.argsort()[::-1]
running = sales.cumsum(axis=1)
print(quarterly.shape)
print(quarterly[0])
print(revenue)
print(items[order[:2]])
print(running[0])
(4, 4)
[1268 1397 1640 1071]
[5376 6007 7284 6770]
['bags' 'lamps']
[ 830 1007 1268 1581 1844 2665 3547 4170 4305 4489 4887 5376]
reshape(4, 4, 3) means four items, four quarters, three months, and summing axis 2 collapses the months. The running total for pens ends at 5376, which matches their total, and matches the four quarters added up. When three routes land on one number, you can trust it.
Recap
| Operation | Array maths |
|---|---|
| Image | (height, width, 3) of uint8, 0 to 255 |
| Channel | img[:, :, 0], a slice |
| Brighten | Widen to int16, add, np.clip(0, 255), back to uint8 |
| Grayscale | img.mean(axis=2) |
| Invert | 255 - img |
| Crop | img[1:3, 2:5] |
Try it yourself: write one prompt for the sales challenge with Role, Context, Task and Format, without copying this one, and read the output against it. The student-marks version of this practice is in Thinking in arrays: a NumPy student analysis.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
