In computer vision and machine learning pipelines, digital images are represented fundamentally as 3D NumPy arrays with dimensions corresponding to (Height, Width, Color Channels). By leveraging direct array slicing and matrix arithmetic, you can perform image transformations, pixel thresholding, cropping, color channel extraction, and contrast scaling from scratch without heavy graphics frameworks.
An RGB raster image is stored as an 8-bit unsigned integer (uint8) tensor with pixel intensities ranging from 0 to 255:
| Dimension Axis | Property | Description |
|---|---|---|
| Axis 0 | Height (Rows) | Vertical pixel index count |
| Axis 1 | Width (Columns) | Horizontal pixel index count |
| Axis 2 | Color Channels | RGB indices: 0: Red, 1: Green, 2: Blue |
Generate a synthetic 300 × 300 RGB test image and crop a sub-region using standard array indexing:
import numpy as np
# Create synthetic 300x300 RGB image (3D array)
img_tensor = np.random.randint(0, 256, size=(300, 300, 3), dtype=np.uint8)
# Crop central 100x100 region
cropped_img = img_tensor[100:200, 100:200, :]
print("Cropped Image Tensor Shape:", cropped_img.shape)
Perform direct pixel-level color inversion and apply logical boolean masks:
# Invert colors (255 - pixel value)
inverted_img = 255 - img_tensor
# Binary thresholding: set bright pixels (> 200) to max 255, others to 0
thresholded = np.where(img_tensor > 200, np.uint8(255), np.uint8(0))
print("Thresholding complete. Bright pixels isolated.")
Extract individual RGB channels and compute weighted luminance grayscale arrays:
red_channel = img_tensor[:, :, 0] # Extract Red matrix (2D)
# ITU-R BT.601 standard weighted grayscale conversion
gray_img = (0.2989 * img_tensor[:, :, 0] + 0.5870 * img_tensor[:, :, 1] + 0.1140 * img_tensor[:, :, 2]).astype(np.uint8)
print("Grayscale Matrix Shape:", gray_img.shape)
Adjust image brightness and stretch dynamic contrast range using matrix scaling and clipping:
# Increase brightness by +40 and scale contrast by 1.25x
img_float = img_tensor.astype(np.float32)
adjusted_img = np.clip(img_float * 1.25 + 40, 0, 255).astype(np.uint8)
print("Brightness & contrast adjusted without uint8 overflow.")
TypeError: Cannot cast ufunc 'subtract' output from dtype('int32'): Occurs when performing math on uint8 without handling overflow. Solution: Cast array to float32 before arithmetic, then clip to [0, 255] using np.clip().NumPy arrays enable fast C-compiled batch processing and seamless integration with PyTorch, TensorFlow, and OpenCV tensor architectures.
Create a 100x100x3 uint8 array filled with zero (black). Set a central 50x50 square to red (Red channel = 255), and calculate the average intensity across the entire image.
import numpy as np
img = np.zeros((100, 100, 3), dtype=np.uint8)
img[25:75, 25:75, 0] = 255
assert img[50, 50, 0] == 255
print("Average image intensity:", np.mean(img))
Manipulate image tensors, isolate RGB color channels, adjust contrast, and apply thresholding filters interactively.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.