Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

2.4 Image Manipulation in Python with PIL and OpenCV

Open In Colab

Overview

In this lesson, we will explore image manipulation using two popular Python libraries: PIL (Pillow) and OpenCV. You will learn how to load, display, resize, rotate, and apply basic filters to images using these libraries. Additionally, we will compare the functionality and performance of PIL and OpenCV.

By the end of this lesson, you will have a better understanding of how to perform image manipulation tasks programmatically and how to choose between PIL and OpenCV depending on your needs.

Learning Objectives

By the end of this section, you will:

  • Understand the importance of selecting appropriate image augmentations for training machine learning models in underwater imagery analysis.

  • Learn how to apply image transformations such as shearing, cropping, adding noise, and adjusting brightness using PIL and OpenCV.

  • Develop a deeper understanding of how augmentations improve model robustness in real-world scenarios, such as handling camera misalignment, murky water conditions, and variable lighting during AUV surveys


The Theory Behind Choosing Augmentations for Training Imagery

When training machine learning models, particularly in highly variable condition tasks such as underwater image analysis, image augmentation is a powerful tool to improve model robustness and performance. Augmentation creates variations of the training data, allowing models to generalize better to real-world conditions. For example, shearing can simulate the effects of camera tilt commonly seen in AUV surveys, where slight angles and shifts can distort how objects are captured. By applying shear transformations, we teach models to recognize objects even when they are skewed due to misalignment during transect movement. Another useful augmentation is cropping, which mimics scenarios where cameras, such as stationary underwater systems, capture only part of an object, often seen in situations where fish or coral are cut off at the edges of the frame. Training with cropped images helps models learn to detect partial objects and improves their robustness in handling incomplete data. In murky underwater environments with sediment or low visibility, adding noise can replicate the challenge of detecting objects in degraded imagery. Noise simulates particles in the water, preparing models to distinguish features despite visual interference. Similarly, brightness adjustments are crucial for dealing with varying lighting conditions that change with depth or time of day. By exposing models to images with different brightness levels, they become more adaptable to fluctuations in light intensity. Additionally, rotations help models handle misalignment that occurs naturally in dynamic underwater environments, where cameras may not always be perfectly horizontal. Lastly, blurring can simulate motion or water flow, which is useful when image clarity is compromised by movement during data collection. Tailoring these augmentations to the challenges of underwater surveys helps build models that are more adaptable, improving detection accuracy and resilience in diverse conditions. The following sections provide examples of how to implement these augmentations in PIL and OpenCV.


Loading and Displaying Images

Before performing any manipulations, we need to load and display images. Both PIL and OpenCV provide easy ways to handle this.

Using PIL:

Using OpenCV:

Resizing Images

Resizing is one of the most common operations when working with images. We will resize images using both PIL and OpenCV.

Using PIL:

Using OpenCV:

Rotating Images

Rotating images is another common transformation. We can easily rotate images using both PIL and OpenCV.

Using PIL:

Using OpenCV:

Applying Filters

Both PIL and OpenCV offer the ability to apply filters to images. We’ll demonstrate a simple blur effect.

Using PIL (Gaussian Blur):

Using OpenCV (Gaussian Blur):

Adjusting Brightness

Brightness is a key property of an image that you can manipulate to make an image lighter or darker.

Using PIL:

Using OpenCV:

Shearing Images

Shearing is a transformation that slants the shape of an object. We’ll shear images using PIL and OpenCV.

Using PIL:

Using OpenCV:

Flipping Images

Flipping an image horizontally or vertically can be useful in data augmentation for machine learning tasks.

Using PIL:

Using OpenCV:

Cropping Images

Cropping allows you to select a specific region of the image.

Using PIL:

Using OpenCV:

Converting Images to Grayscale

Converting an image to grayscale reduces the number of color channels, which is useful for some computer vision tasks (See next session to learn why that is!)

Using PIL:

Using OpenCV:

Adding Noise to Images

Adding random noise to an image can help simulate real-world noise that can be found in murky water, dirty cameras etc. Making it especially useful for training machine learning models.

Using NumPy and PIL:

Using OpenCV:

Histogram Equalization

Histogram equalization improves the contrast in images by spreading out the intensity values. Currently this is almost exclusively done using OpenCV.

Using OpenCV:

Edge Detection

Detecting edges is useful for object detection and shape analysis. Currently this is almost exclusively done using OpenCV.

Using OpenCV:

Blending Two Images

Blending combines two images with a specified weight ratio.

Using OpenCV:

Thresholding

Thresholding converts an image to a binary (black-and-white) image by setting a threshold value. Currently this is almost exclusively done using OpenCV

Using OpenCV:

Affine Transformation

Affine transformations include rotation, translation, scaling, and shearing while preserving collinearity.

Using OpenCV:

Color Space Conversion: BGR to RGB

OpenCV loads images in BGR (Blue, Green, Red) format by default, whereas most image processing libraries like Matplotlib expect images in RGB (Red, Green, Blue) format. To ensure the correct color representation when displaying images, you need to convert from BGR to RGB.

Using OpenCV: