We use arrays to change images because images are just grids of numbers. Changing these numbers changes the picture.
Basic image manipulation with arrays in NumPy
import numpy as np # Load or create an image as a 2D (grayscale) or 3D (color) numpy array image = np.array([...]) # Example image array # Example operations: # 1. Brightness change brighter_image = np.clip(image + 50, 0, 255) # Add 50 to all pixels and clip to valid range # 2. Flip image horizontally flipped_image = np.fliplr(image) # 3. Crop image cropped_image = image[10:100, 20:150] # 4. Convert to grayscale (if color image) gray_image = np.mean(image, axis=2).astype(np.uint8)
Images are stored as arrays where each number represents a pixel's brightness or color.
Use numpy functions to easily manipulate these arrays.
import numpy as np # Empty image (all zeros) empty_image = np.zeros((5, 5), dtype=np.uint8) print(empty_image)
import numpy as np # Single pixel image single_pixel_image = np.array([[255]], dtype=np.uint8) print(single_pixel_image)
import numpy as np # Flip a small image horizontally small_image = np.array([[10, 20, 30], [40, 50, 60]], dtype=np.uint8) flipped = np.fliplr(small_image) print(flipped)
import numpy as np # Crop image edge case: cropping beyond image size image = np.arange(100).reshape(10, 10) cropped = image[8:15, 8:15] print(cropped)
This program creates a small grayscale image as a numpy array. It then makes the image brighter, flips it horizontally, and crops the center part. Each step prints the image array so you can see the changes.
import numpy as np # Create a simple 5x5 grayscale image with values from 10 to 210 original_image = np.array([ [10, 50, 90, 130, 170], [20, 60, 100, 140, 180], [30, 70, 110, 150, 190], [40, 80, 120, 160, 200], [50, 90, 130, 170, 210] ], dtype=np.uint8) print("Original Image:\n", original_image) # Increase brightness by 40 (clip max to 255) brighter_image = np.clip(original_image + 40, 0, 255).astype(np.uint8) print("\nBrighter Image:\n", brighter_image) # Flip image horizontally flipped_image = np.fliplr(original_image) print("\nFlipped Image (Left-Right):\n", flipped_image) # Crop the center 3x3 area cropped_image = original_image[1:4, 1:4] print("\nCropped Image (3x3 center):\n", cropped_image)
Brightness change operation runs in O(n*m) time where n and m are image dimensions.
Flipping and cropping also run in O(n*m) time but are very fast with numpy.
Common mistake: Not clipping values after brightness change can cause overflow and wrong colors.
Use cropping to focus on parts of an image; use flipping to mirror images easily.
Images are arrays of numbers representing pixels.
You can change images by adding, flipping, or slicing these arrays.
Numpy makes these operations simple and fast.