NumPy: Project — Image Processing

Last updated: 2026-08-26

1. Project: Image Processing with NumPy

(1) Scenario

You're working on a computer vision pipeline. You need to manipulate images at the pixel level — convert to grayscale, apply filters, and compute statistics — all using NumPy array operations.

(2) Tasks

1. Create a Synthetic Image

PYTHON
import numpy as np

# Create a 100x100 RGB image
rng = np.random.default_rng(42)
image = rng.integers(0, 256, size=(100, 100, 3), dtype=np.uint8)
print(f"Image shape: {image.shape}")  # (100, 100, 3)
print(f"Image dtype: {image.dtype}")  # uint8

2. Convert to Grayscale

PYTHON
# Grayscale: weighted average of RGB channels
# Standard weights: 0.299 R + 0.587 G + 0.114 B
gray = np.dot(image[..., :3], [0.299, 0.587, 0.114]).astype(np.uint8)
print(f"Gray shape: {gray.shape}")  # (100, 100)

3. Apply a Simple Filter (Horizontal Edge Detection)

PYTHON
# Edge detection: subtract adjacent rows
edges = np.abs(gray[:-1] - gray[1:])
print(f"Edge map shape: {edges.shape}")  # (99, 100)
print(f"Edge intensity: mean={edges.mean():.1f}, max={edges.max()}")

4. Extract Color Channels

PYTHON
# Extract individual channels
red = image[:, :, 0]
green = image[:, :, 1]
blue = image[:, :, 2]

print(f"Red channel: mean={red.mean():.1f}, min={red.min()}, max={red.max()}")
print(f"Green channel: mean={green.mean():.1f}, min={green.min()}, max={green.max()}")
print(f"Blue channel: mean={blue.mean():.1f}, min={blue.min()}, max={blue.max()}")

5. Image Statistics

PYTHON
# Histogram (simplified: count pixels in each intensity range)
bins = np.array([0, 50, 100, 150, 200, 256])
indices = np.digitize(gray.ravel(), bins)
hist = np.bincount(indices, minlength=len(bins)+1)[1:-1]

for i in range(len(bins)-1):
    print(f"Intensity {bins[i]:3d}-{bins[i+1]:3d}: {hist[i]:4d} pixels")

▶ Example: Creating a synthetic image (Difficulty ⭐)

PYTHON
import numpy as np

# Create a 50x50 RGB image with a gradient
x = np.arange(50)
y = np.arange(50)
xx, yy = np.meshgrid(x, y)

red = np.zeros((50, 50), dtype=np.uint8)
green = (xx * 5).astype(np.uint8)
blue = (yy * 5).astype(np.uint8)

image = np.stack([red, green, blue], axis=-1)
print("Shape:", image.shape)
print("Red channel:", image[:, :, 0].min(), "-", image[:, :, 0].max())
print("Green channel:", image[:, :, 1].min(), "-", image[:, :, 1].max())
print("Blue channel:", image[:, :, 2].min(), "-", image[:, :, 2].max())

Output:

TEXT 📖 Display only
Shape: (50, 50, 3)
Red channel: 0 - 0
Green channel: 0 - 245
Blue channel: 0 - 245

▶ Example: Grayscale conversion (Difficulty ⭐)

PYTHON
import numpy as np

# Simulate an RGB image
rng = np.random.default_rng(42)
image = rng.integers(0, 256, size=(10, 10, 3), dtype=np.uint8)

# Standard grayscale weights
gray = (0.299 * image[:, :, 0] + 0.587 * image[:, :, 1] + 0.114 * image[:, :, 2]).astype(np.uint8)
print("Original shape:", image.shape)
print("Gray shape:", gray.shape)
print("Gray pixel [0, 0]:", gray[0, 0])
print("Gray mean:", gray.mean())

Output:

TEXT 📖 Display only
Original shape: (10, 10, 3)
Gray shape: (10, 10)
Gray pixel [0, 0]: 72
Gray mean: 129.0

▶ Example: Simple edge detection (Difficulty ⭐⭐)

PYTHON
import numpy as np

# Create a simple image with a vertical edge
image = np.zeros((10, 10), dtype=np.uint8)
image[:, 5:] = 255

# Horizontal edge detection
h_edges = np.abs(image[:-1, :] - image[1:, :])
print("Horizontal edges:\n", h_edges)

# Vertical edge detection
v_edges = np.abs(image[:, :-1] - image[:, 1:])
print("Vertical edges:\n", v_edges)

Output:

TEXT 📖 Display only
Horizontal edges:
 [[0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]]
Vertical edges:
 [[  0   0   0   0 255   0   0   0   0]
 [  0   0   0   0 255   0   0   0   0]
 [  0   0   0   0 255   0   0   0   0]
 [  0   0   0   0 255   0   0   0   0]
 [  0   0   0   0 255   0   0   0   0]
 [  0   0   0   0 255   0   0   0   0]
 [  0   0   0   0 255   0   0   0   0]
 [  0   0   0   0 255   0   0   0   0]
 [  0   0   0   0 255   0   0   0   0]]


❓ FAQ

Q Why use 0.299 R + 0.587 G + 0.114 B for grayscale?
A These weights match human perception — we're most sensitive to green, least to blue. Simple averaging (R+G+B)/3 ignores this and produces washed-out results.
Q Can I process real images with NumPy?
A Yes — load images with matplotlib.pyplot.imread() or imageio.imread(), which return NumPy arrays. Then apply the same operations shown here.
Q What's the difference between uint8 and float32 for images?
A uint8 (0-255) is the standard format for storage and display. float32 is used for computation (filters, transformations) to avoid overflow and rounding errors.

📖 Summary

In this project you applied:


📝 Exercises

  1. Beginner (Difficulty ⭐): Swap the red and blue channels of the image. What color cast does this create?

  2. Intermediate (Difficulty ⭐⭐): Implement a vertical edge detector by subtracting adjacent columns instead of rows. Compare the results.

  3. Advanced (Difficulty ⭐⭐⭐): Implement a simple blur filter: replace each pixel with the average of its 3x3 neighborhood. Use broadcasting and slicing — no loops.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏