0
0
NumPydata~5 mins

Image as array concept in NumPy

Choose your learning style9 modes available
Introduction

We use arrays to represent images because computers store images as numbers. This helps us easily change or analyze images using math.

When you want to edit or filter a photo on your computer.
When you need to count colors or shapes in an image.
When building apps that recognize faces or objects.
When converting images to black and white or changing brightness.
When you want to create animations or effects by changing pixels.
Syntax
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).

Examples
This shows an image with no pixels but 3 color channels.
NumPy
import numpy as np

# Empty image (0 height and width)
empty_image = np.array([]).reshape(0, 0, 3)
print(empty_image.shape)
An image with just one red pixel.
NumPy
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)
All pixels are white because all color values are 255.
NumPy
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)
Sample Program

This program creates a small 3x3 image with colors, prints it, changes the middle pixel to black, and prints the updated image.

NumPy
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)
OutputSuccess
Important Notes

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.

Summary

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.