/Curriculum/Practical & ProjectsComputer Vision

49. NumPy for Image ProcessingAdvanced

Represent RGB images as 3D (Height, Width, 3) arrays, crop, tint, and grayscale.

20 mins

Concept Overview

Every digital image is simply a 3D NumPy array of shape `(Height, Width, Channels)`. Color channels are `0: Red`, `1: Green`, and `2: Blue` with pixel values from 0 to 255.

Hardware Mental Model

An image is a giant mosaic grid of colored tiles. Cropping an image is basic array slicing `img[100:200, 100:200]`. Inverting an image is `255 - img`.

Key Concepts (1)Click snippet to load in editor

`img.shape` = `(Height, Width, 3)`. Data type is `np.uint8` (0 to 255 unsigned 8-bit integers).

gray = (img * [0.299, 0.587, 0.114]).sum(axis=-1)

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:img = img + 50 # uint8 overflow: 250 + 50 wraps around to 44!
✓ Correct:img = np.clip(img.astype(np.int32) + 50, 0, 255).astype(np.uint8)

Adding numbers directly to `uint8` wraps around 255 to 0. Always cast to int32, add, clip to 255, then cast back.

Pro Tip: Use `np.clip` to prevent uint8 overflow when adjusting image brightness.

📌 Quick Revision

Core takeaway points from this topic
Images are 3D ndarrays of shape `(Height, Width, Channels)` with `uint8` data type.
Cropping is basic array slicing: `img[y1:y2, x1:x2]`.
Color inversion: `255 - img`.
Grayscale conversion: weighted average of RGB channels.
Editor: 49. NumPy for Image Processing
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state

🎯 Try It Yourself: Practice Challenge

Hands-on Mode

Solve the objective below using NumPy vectorized syntax

Objective:Invert Image Pixels

Given pixel values `p = np.array([0, 100, 255], dtype=np.uint8)`, invert them with `255 - p` and print.

Expected Output Target:[255 155 0]
Practice Workspace
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state