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.
Expected Output
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.
(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.
Run the installation command in your terminal or Python environment. If NumPy and Pillow are already installed, you can continue to the next step.
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.
Example Output
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.
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.
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.
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.
Example Output
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.
Example Output
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.
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.
Expected Output
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.
9. Darken an Image
We can use the same multiplication method with a factor below 1 to darken the image.
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.
Example Output
Python slice endpoints are exclusive. Therefore, 50:250 selects
200 rows, while 100:350 selects 250 columns.
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.
Expected Output
| 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.
Example Output
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.
The expression grayscale_array > threshold produces a Boolean array.
np.where() replaces each True position with 255 and each False position
with 0.
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.
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.
Example Output
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.
The arrays stored in an NPZ archive may have different shapes. Each array is retrieved by the key used when saving it.
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.
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
- Load a different image and print its shape and data type.
- Extract and save the red, green, and blue channels separately.
- Change the brightness factor to 1.5 and compare the output.
- Darken an image using a factor of 0.4.
- Crop a different rectangular region using NumPy slicing.
- Convert an image to grayscale and calculate its mean intensity.
- Try threshold values of 80, 128, and 180.
- Resize an image and inspect the new NumPy array shape.
- Save the original and processed arrays into one NPZ archive.
- 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.