Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

Image Array Processing Project Using NumPy

In this practical project, we will understand how digital images are represented as NumPy arrays and how basic image-processing operations can be performed using array manipulation. We will explore RGB channels, grayscale conversion, brightness adjustment, cropping, flipping, thresholding, and saving image data. We will use NumPy for numerical operations and Pillow for loading and displaying image files.

1. Project Objectives

After completing this project, you will be able to:

  • Understand how digital images are represented as arrays.
  • Load an image and convert it into a NumPy array.
  • Inspect image shape, dimensions, and data type.
  • Understand RGB color channels.
  • Convert an RGB image to grayscale.
  • Adjust brightness and crop image regions.
  • Flip images horizontally and vertically.
  • Apply a simple threshold to create a binary image.
  • Save processed images and NumPy array data.

2. How Does NumPy Represent an Image?

A digital image consists of pixels. Each pixel stores information about the color or intensity at a particular position. NumPy represents image data using arrays containing these pixel values.

Grayscale Image

A grayscale image is usually represented by a two-dimensional array. Each element stores the intensity of one pixel, typically between 0 and 255 for an 8-bit image.

import numpy as np grayscale_image = np.array([ [0, 50, 100], [120, 180, 220], [30, 150, 255] ], dtype=np.uint8) print(grayscale_image) print("Shape:", grayscale_image.shape)

Expected Output

[[ 0 50 100] [120 180 220] [ 30 150 255]] Shape: (3, 3)

A value of 0 represents black, while 255 represents white. Values between them represent different shades of gray.

RGB Color Image

A standard RGB image is commonly represented by a three-dimensional array with dimensions for height, width, and three color channels: Red, Green, and Blue.

Red Channel Green Channel Blue Channel R values G values B values
An RGB image contains three values for each pixel: red, green, and blue.
Remember: An RGB image usually has shape (height, width, 3). The last dimension stores the three color channels.

3. Install the Required Libraries

NumPy handles the array operations. Pillow, imported through the PIL package, provides convenient functions for opening and saving common image formats.

pip install numpy pillow

Run the installation command in your terminal or Python environment. If NumPy and Pillow are already installed, you can continue to the next step.

Note: pip install is a terminal command, not a Python statement to place directly inside a normal Python script.

4. Load an Image and Convert It into a NumPy Array

Pillow can open an image file. Converting the image to RGB before creating the NumPy array gives us a consistent three-channel representation.

from PIL import Image import numpy as np image = Image.open("sample.jpg").convert("RGB") image_array = np.array(image) print("Image shape:", image_array.shape) print("Number of dimensions:", image_array.ndim) print("Data type:", image_array.dtype) print("Total array elements:", image_array.size)

Example Output

Image shape: (480, 640, 3) Number of dimensions: 3 Data type: uint8 Total array elements: 921600

These dimensions are an example. Your output depends on the actual image file. In this example, the image is 480 pixels high and 640 pixels wide, with three color values per pixel.

File requirement: Keep sample.jpg in the program's current working directory or provide the correct file path. Otherwise, Image.open() will raise a file-not-found error.

5. Inspect Image Pixels and RGB Values

Because an RGB image is a three-dimensional array, we can access individual pixels using row, column, and channel indices.

from PIL import Image import numpy as np image = Image.open("sample.jpg").convert("RGB") image_array = np.array(image) # Pixel at row 0, column 0 first_pixel = image_array[0, 0] print("First pixel RGB:", first_pixel) # Access individual color channels red_value = image_array[0, 0, 0] green_value = image_array[0, 0, 1] blue_value = image_array[0, 0, 2] print("Red:", red_value) print("Green:", green_value) print("Blue:", blue_value)

The pixel coordinates above refer to the top-left pixel. NumPy uses zero-based indexing, so the first row and column both have index 0.

Channel indexing: image_array[:, :, 0] selects all red-channel values, image_array[:, :, 1] selects green, and image_array[:, :, 2] selects blue.

6. Separate the RGB Channels

You can select each color channel using slicing. Each selected channel becomes a two-dimensional array.

red_channel = image_array[:, :, 0] green_channel = image_array[:, :, 1] blue_channel = image_array[:, :, 2] print("Red channel shape:", red_channel.shape) print("Green channel shape:", green_channel.shape) print("Blue channel shape:", blue_channel.shape)

Example Output

Red channel shape: (480, 640) Green channel shape: (480, 640) Blue channel shape: (480, 640)

All three channels have the same height and width. Combining the corresponding red, green, and blue values produces the color of each pixel.

7. Convert an RGB Image to Grayscale

Grayscale conversion reduces the three color values of each pixel to a single intensity value. A commonly used luminance approximation gives more weight to green than to blue.

from PIL import Image import numpy as np image = Image.open("sample.jpg").convert("RGB") image_array = np.array(image, dtype=np.float32) red = image_array[:, :, 0] green = image_array[:, :, 1] blue = image_array[:, :, 2] grayscale = ( 0.299 * red + 0.587 * green + 0.114 * blue ) grayscale = np.clip( np.round(grayscale), 0, 255 ).astype(np.uint8) print("Original shape:", image_array.shape) print("Grayscale shape:", grayscale.shape) Image.fromarray(grayscale).save("grayscale_image.png")

Example Output

Original shape: (480, 640, 3) Grayscale shape: (480, 640)

The grayscale image has two dimensions because each pixel now contains one intensity value instead of three RGB values. The formula is an approximation suitable for demonstrating a basic grayscale conversion.

Why use float32? The conversion formula multiplies values by decimal weights. Floating-point calculations preserve these fractional values until we round and convert the result back to 8-bit integers.

8. Adjust Image Brightness

Brightness can be adjusted by multiplying pixel values by a factor. A factor above 1 increases brightness, while a factor between 0 and 1 decreases it.

from PIL import Image import numpy as np image = Image.open("sample.jpg").convert("RGB") image_array = np.array(image, dtype=np.float32) brightness_factor = 1.3 brightened = image_array * brightness_factor brightened = np.clip( brightened, 0, 255 ).astype(np.uint8) Image.fromarray(brightened).save("brightened_image.png") print("Brightened image saved.")

Expected Output

Brightened image saved.

The np.clip() function keeps pixel values within the valid 8-bit range. Without clipping, multiplication could produce values above 255, which cannot be represented correctly as standard 8-bit image channels.

Important: Increasing brightness may cause bright areas to lose detail because values above 255 are clipped to 255.

9. Darken an Image

We can use the same multiplication method with a factor below 1 to darken the image.

darkness_factor = 0.6 darkened = image_array * darkness_factor darkened = np.clip( darkened, 0, 255 ).astype(np.uint8) Image.fromarray(darkened).save("darkened_image.png") print("Darkened image saved.")

A factor of 0.6 retains 60% of the original channel values. Smaller factors generally produce a darker result.

10. Crop an Image Using Array Slicing

Cropping selects a rectangular region from an image. Since the first two dimensions represent rows and columns, we can use standard NumPy slicing to select a region.

from PIL import Image import numpy as np image = Image.open("sample.jpg").convert("RGB") image_array = np.array(image) # Select rows 50 to 249 and columns 100 to 349 cropped_array = image_array[50:250, 100:350] print("Original shape:", image_array.shape) print("Cropped shape:", cropped_array.shape) Image.fromarray(cropped_array).save("cropped_image.png")

Example Output

Original shape: (480, 640, 3) Cropped shape: (200, 250, 3)

Python slice endpoints are exclusive. Therefore, 50:250 selects 200 rows, while 100:350 selects 250 columns.

Remember: The crop coordinates must fit within the image dimensions. If the image is smaller than expected, adjust the slice boundaries accordingly.

11. Flip an Image Horizontally and Vertically

NumPy provides np.flip() and np.flipud() for reversing array directions. For an image array, reversing columns creates a horizontal flip, while reversing rows creates a vertical flip.

from PIL import Image import numpy as np image = Image.open("sample.jpg").convert("RGB") image_array = np.array(image) horizontal_flip = np.flip(image_array, axis=1) vertical_flip = np.flip(image_array, axis=0) Image.fromarray(horizontal_flip).save("horizontal_flip.png") Image.fromarray(vertical_flip).save("vertical_flip.png") print("Flipped images saved.")

Expected Output

Flipped images saved.
Operation NumPy Expression Effect
Horizontal flip np.flip(array, axis=1) Reverses the column order.
Vertical flip np.flip(array, axis=0) Reverses the row order.

12. Resize an Image with Pillow

NumPy is excellent for array manipulation, but resizing images requires interpolation to estimate pixel values at new coordinates. Pillow provides convenient resizing methods for this task.

from PIL import Image import numpy as np image = Image.open("sample.jpg").convert("RGB") resized_image = image.resize( (320, 240), Image.Resampling.LANCZOS ) resized_array = np.array(resized_image) print("Resized array shape:", resized_array.shape) resized_image.save("resized_image.png")

Example Output

Resized array shape: (240, 320, 3)

Pillow expects the new size as (width, height), while the resulting NumPy array uses the shape order (height, width, channels).

13. Create a Binary Image Using Thresholding

Thresholding converts a grayscale image into a binary image. Pixels above the threshold become white, while pixels at or below it become black.

from PIL import Image import numpy as np image = Image.open("sample.jpg").convert("L") grayscale_array = np.array(image) threshold = 128 binary_array = np.where( grayscale_array > threshold, 255, 0 ).astype(np.uint8) Image.fromarray(binary_array).save("binary_image.png") print("Binary image saved.")

The expression grayscale_array > threshold produces a Boolean array. np.where() replaces each True position with 255 and each False position with 0.

Use case: Thresholding is a basic technique for separating brighter regions from darker regions. More complex image segmentation may require adaptive thresholds or other image-processing methods.

14. Extract Pixels Above a Threshold

Boolean indexing can select pixels that satisfy a condition. For example, we can extract all grayscale intensity values greater than 200.

bright_pixels = grayscale_array[grayscale_array > 200] print("Number of bright pixels:", bright_pixels.size) if bright_pixels.size > 0: print("Average bright-pixel intensity:", np.mean(bright_pixels)) else: print("No pixels exceeded the threshold.")

The selected values form a one-dimensional array. The size of this array tells us how many pixels satisfy the condition.

15. Save Image Arrays as NumPy Files

You can save the numerical image array using NumPy's NPY format. This preserves the array values and data type without converting the image into a conventional image file format.

import numpy as np from PIL import Image image = Image.open("sample.jpg").convert("RGB") image_array = np.array(image) np.save("image_array.npy", image_array) loaded_array = np.load("image_array.npy") print("Original shape:", image_array.shape) print("Loaded shape:", loaded_array.shape) print("Arrays match:", np.array_equal(image_array, loaded_array))

Example Output

Original shape: (480, 640, 3) Loaded shape: (480, 640, 3) Arrays match: True

NPY is useful when you want to preserve the array itself for future numerical processing. PNG and JPEG, by contrast, are image formats intended for viewing and sharing images.

16. Save Multiple Arrays in an NPZ Archive

An NPZ file can store multiple arrays in one archive. This is useful for keeping the original image and processed results together.

np.savez_compressed( "image_processing_results.npz", original=image_array, grayscale=grayscale_array, binary=binary_array ) print("Image arrays saved.") with np.load("image_processing_results.npz") as data: loaded_original = data["original"] loaded_grayscale = data["grayscale"] loaded_binary = data["binary"] print("Original shape:", loaded_original.shape) print("Grayscale shape:", loaded_grayscale.shape) print("Binary shape:", loaded_binary.shape)

The arrays stored in an NPZ archive may have different shapes. Each array is retrieved by the key used when saving it.

File size note: Image arrays can be large. Compression may reduce the saved file size, depending on the image data, but compressed NPZ files are not always smaller than every alternative image format.

17. Complete Image Processing Program

This script combines image loading, array inspection, grayscale conversion, brightness adjustment, cropping, flipping, thresholding, and file saving. Keep sample.jpg in the current working directory before running it.

import numpy as np from PIL import Image # 1. Load and convert the image image = Image.open("sample.jpg").convert("RGB") image_array = np.array(image) print("Original shape:", image_array.shape) print("Data type:", image_array.dtype) # 2. Convert to grayscale image_float = image_array.astype(np.float32) red = image_float[:, :, 0] green = image_float[:, :, 1] blue = image_float[:, :, 2] grayscale = ( 0.299 * red + 0.587 * green + 0.114 * blue ) grayscale = np.clip( np.round(grayscale), 0, 255 ).astype(np.uint8) # 3. Adjust brightness brightened = np.clip( image_float * 1.2, 0, 255 ).astype(np.uint8) # 4. Crop a region height, width = image_array.shape[:2] crop_top = min(50, height) crop_bottom = min(250, height) crop_left = min(100, width) crop_right = min(350, width) cropped = image_array[ crop_top:crop_bottom, crop_left:crop_right ] # 5. Flip image arrays horizontal_flip = np.flip(image_array, axis=1) vertical_flip = np.flip(image_array, axis=0) # 6. Create a binary image binary = np.where( grayscale > 128, 255, 0 ).astype(np.uint8) # 7. Save processed image files Image.fromarray(grayscale).save("grayscale_image.png") Image.fromarray(brightened).save("brightened_image.png") Image.fromarray(cropped).save("cropped_image.png") Image.fromarray(horizontal_flip).save("horizontal_flip.png") Image.fromarray(vertical_flip).save("vertical_flip.png") Image.fromarray(binary).save("binary_image.png") # 8. Save arrays np.savez_compressed( "image_processing_results.npz", original=image_array, grayscale=grayscale, brightened=brightened, cropped=cropped, binary=binary ) print("All image-processing operations completed.") print("Grayscale shape:", grayscale.shape) print("Cropped shape:", cropped.shape) print("Binary unique values:", np.unique(binary)) print("Processed image files and NPZ archive saved.")

The crop boundaries are limited to the image dimensions so that smaller images do not cause an out-of-range slice. If the image is smaller than the requested crop region, the resulting crop will also be smaller.

18. Common Mistakes

Mistake 1: Confusing image dimensions

A NumPy image array generally uses (height, width, channels). Pillow's resize method uses (width, height).

Mistake 2: Ignoring pixel data types

Standard 8-bit image channels use unsigned integer values from 0 to 255. Convert to a floating-point type before applying calculations that require decimal values.

Mistake 3: Forgetting to clip pixel values

Brightness calculations may exceed 255. Use np.clip() before converting results to np.uint8.

Mistake 4: Using the wrong channel index

In an RGB array, channel 0 is red, channel 1 is green, and channel 2 is blue. The channel order can differ in other image-processing libraries or formats.

Mistake 5: Using a missing or incorrect file path

Ensure the input image exists and the filename is correct. Use an absolute path if the image is stored outside the program's current working directory.

19. Practice Exercises

  1. Load a different image and print its shape and data type.
  2. Extract and save the red, green, and blue channels separately.
  3. Change the brightness factor to 1.5 and compare the output.
  4. Darken an image using a factor of 0.4.
  5. Crop a different rectangular region using NumPy slicing.
  6. Convert an image to grayscale and calculate its mean intensity.
  7. Try threshold values of 80, 128, and 180.
  8. Resize an image and inspect the new NumPy array shape.
  9. Save the original and processed arrays into one NPZ archive.
  10. Load the NPZ archive and verify that the saved arrays match the originals.

Summary

In this project, you learned that images can be represented as NumPy arrays and that RGB images typically contain separate red, green, and blue channels. You used array slicing and numerical operations to convert images to grayscale, adjust brightness, crop regions, flip images, and apply thresholding.

You also learned how to inspect image dimensions, save processed images using Pillow, and preserve numerical image data in NPY and NPZ files. These concepts provide a foundation for more advanced image processing and computer vision.