We use arrays to represent images because computers store images as numbers. This helps us easily change or analyze images using math.
Image as array concept in NumPy
import numpy as np # Example: Create a simple 3x3 image with 3 color channels (RGB) image_array = np.array([ [[255, 0, 0], [0, 255, 0], [0, 0, 255]], [[255, 255, 0], [0, 255, 255], [255, 0, 255]], [[0, 0, 0], [127, 127, 127], [255, 255, 255]] ])
An image array is usually 3D: height x width x color channels.
Each pixel has values for colors, often Red, Green, and Blue (RGB).
import numpy as np # Empty image (0 height and width) empty_image = np.array([]).reshape(0, 0, 3) print(empty_image.shape)
import numpy as np # Image with one pixel, red color one_pixel_image = np.array([[[255, 0, 0]]]) print(one_pixel_image.shape) print(one_pixel_image)
import numpy as np # Image with 2 rows and 2 columns, all pixels white white_image = np.ones((2, 2, 3), dtype=int) * 255 print(white_image)
This program creates a small 3x3 image with colors, prints it, changes the middle pixel to black, and prints the updated image.
import numpy as np # Create a 3x3 image with RGB colors image_array = np.array([ [[255, 0, 0], [0, 255, 0], [0, 0, 255]], [[255, 255, 0], [0, 255, 255], [255, 0, 255]], [[0, 0, 0], [127, 127, 127], [255, 255, 255]] ]) print("Original image array shape:", image_array.shape) print("Original image array data:") print(image_array) # Change the middle pixel to black image_array[1, 1] = [0, 0, 0] print("\nImage array after changing middle pixel to black:") print(image_array)
Time complexity to access or change one pixel is O(1) because arrays allow direct access.
Space complexity depends on image size: height x width x color channels.
Common mistake: Mixing up the order of dimensions (height, width, channels) can cause wrong results.
Use arrays for images when you want fast, easy pixel-level changes or analysis.
Images are stored as arrays of numbers representing pixels and colors.
Each pixel has color values, usually Red, Green, and Blue.
Using arrays lets us easily view, change, or analyze images with code.