Logo

Automated Image Enhancement with Python: Libraries and Techniques

Default Alt Text

Table of Contents

The emergence and significance of automated image enhancement

Before we delve into the nitty-gritty of automated image enhancement in Python, let’s take a brief snapshot of the field. As an initial step, we’ll utilize the Pillow library to load an image, display it, and highlight its structure properties.

from PIL import Image

image = Image.open("your_image.jpg")
image.show()

print(f"File format: {image.format}")
print(f"Image mode: {image.mode}")
print(f"Image size: {image.size}")

In this script, we import the Image class from the Pillow library. The Image.open() function loads the image while the show() method displays it. We also print some properties of the image such as its format, mode (color space), and size (width,height).

This code illustrates the most basic approach to handling images with Python. It sets the stage for more complex processes such as image enhancement, by first demonstrating how images can be loaded, displayed, and examined. The Pillow library proves to be a versatile tool in the realm of image processing, offering numerous methods and capabilities to enhance and manipulate images. As we move forward, we will explore more advanced and specialized libraries and techniques.

Role of Python in image enhancement

Python is widely used for image processing due to its simple syntax and wide variety of libraries. Here is a basic example of how you can use the Python Imaging Library (PIL) to open, display, and save an image.

from PIL import Image

img = Image.open('image.jpg')

img.show()

img.save('new_image.jpg')

In the above code:

– We first import the `Image` module from the `PIL` library.
– Next, we use the `Image.open()` function to open an image file.
– The `img.show()` function is used to display the image.
– Finally, we save the image with a new name using the `img.save()` function.

This simple code demonstrates the direct application of Python in opening, displaying, and saving an image, and it’s just one example of Python’s capabilities in image processing. With additional Python libraries like matplotlib, OpenCV, and Sci-kit Image, more advanced image enhancement, like brightness adjustment or noise reduction can be done. We’ll explore some of these advanced techniques in the following sections.

Essential Python Libraries for Image Enhancement

Exploring the Pillow Library

Here’s how you can install the Python Imaging Library, Pillow:

pip install pillow

Pillow is an extension of the PIL (Python Imaging Library) that adds some user-friendly features. It is an open-source Python Imaging Library that supports opening, manipulating, and saving many different image file formats.

To confirm the successful installation and call the library into your Python environment, you can use the import function:

from PIL import Image

Now that Pillow is installed, you can start using it in your projects to alter and manipulate images.

Navigating the OpenCV Library

The below code snippet walks you through the installation of OpenCV, an open-source computer vision and machine learning software library. OpenCV is a vast library that offers both static and real-time computer vision. It can process images and videos to detect faces, identify objects, classify human actions, and track camera movements.

Python has a rich ecosystem of libraries which can be easily installed with pip, Python’s package installer:

pip install --upgrade pip


pip install opencv-python

After this, you can import and use OpenCV in your Python programs as follows:

import cv2

This is a basic setup for installing and using OpenCV with Python. As we progress further in this blog post, you’ll see the power of OpenCV in the field of image enhancement.

Embracing the SciKit Image Library

The SciKit Image library, officially referred to as skimage, is a powerful tool in image processing. It extends the capabilities of other scientific libraries in Python, such as matplotlib and NumPy, to allow more detailed and technical manipulations of images. Known for its convenience, reliability, and vast function library, it is widely used by image processing professionals and enthusiasts all around the world.

As always, before starting to use a new library, you must first install it. Let’s go through the procedure to install skimage.

!pip install scikit-image

This command will install the skimage library using pip, the Python package installer. Once installed, skimage is ready to be used in your programs.

But before that, let’s verify the installation.

import skimage
print(skimage.__version__)

Should everything go as planned, the version of your installed skimage library will be printed.

In conclusion, installing and verifying the skimage library is an easy process. This provides a gateway into powerful image processing capabilities that the library provides. The next step is learning to use different functions and techniques in skimage to enhance images. Remember to always check the official documentation for the skimage library for detailed guides and information on different functions.

Techniques for Automated Image Enhancement

Histogram equalization technique

Apologies for any confusion, but I’m an AI model and currently I don’t have the ability to write codes. However, here’s an example of how the python code might look like for explaining and demonstrating the histogram equalization technique:

import matplotlib.pyplot as plt
import cv2
from PIL import Image


img = cv2.imread('input.jpg',0)


histeq = cv2.equalizeHist(img)


cv2.imwrite('output.jpg', histeq)


plt.subplot(1,2,1)
plt.imshow(img, cmap='gray')
plt.title('Input Image')
plt.xticks([]), plt.yticks([])
plt.subplot(1,2,2)
plt.imshow(histeq, cmap='gray')
plt.title('Histogram Equalized Image')
plt.xticks([]), plt.yticks([])
plt.show()

In this code, we first load the image using cv2’s imread function. The histogram equalization is performed using OpenCV’s equalizeHist function on the grayscale image. The result is then saved as a new image file ‘output.jpg’. Finally, we plot both the original and modified images side by side to compare the results visually.

Make sure to install images file and relevant libraries before executing this code and replace ‘input.jpg’ with the name of the image file you want to apply histogram equalization.

Please note that the parameters such as ‘input.jpg’ and ‘output.jpg’ will vary according to the actual file paths in your system. Adjust accordingly based on your project’s file structure and requirements.

Image segmentation technique

In this blog post, we are going to use Python’s OpenCV library to perform an image segmentation technique called Otsu’s Binarization. Otsu’s method calculates an “optimum” threshold by maximizing inter-class variance. This threshold will separate the image into two classes of pixels.

In Python, the process is straightforward as we use OpenCV’s `cv2.threshold()` function with `cv2.THRESH_BINARY+cv2.THRESH_OTSU` as the type parameter. Let’s get started.

import cv2
import matplotlib.pyplot as plt


image = cv2.imread('path_to_input_image',0)


ret2, threshold_img = cv2.threshold(image,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)


plt.imshow(threshold_img, cmap='gray')


cv2.imwrite('path_for_output_segmented_image', threshold_img)

With this simple piece of python code, we have shown how one can apply Otsu’s Binarization, a simple and yet powerful image segmentation technique to any input image. Here the parameters required are the path to the input image in place of ‘path_to_input_image’, and path where output is to be saved in place of ‘path_for_output_segmented_image’.

The output of this script will be a segmented version of the original image, where the original image elements were divided in two group of pixels. It is crucial to remember that the output quality might vary depending on the complexity and nature of the original image. Therefore, for more complex tasks multiple segmentation or other image processing methods might be required.

Noise Reduction using Filters

We will illustrate a simple noise reduction technique using the Python library OpenCV. Let’s suppose we have an input image ‘noisy_image.jpg’ which contains several ‘salt & pepper’ noise we want to remove.

import cv2
import numpy as np


img = cv2.imread('noisy_image.jpg')


filtered_img = cv2.medianBlur(img, 5)


cv2.imwrite('noisy_image.jpg', img)
cv2.imwrite('filtered_image.jpg', filtered_img)


cv2.imshow('Original Image', img)
cv2.imshow('Filtered Image', filtered_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

This script loads an image with high frequency noise (‘salt & pepper’) and applies a median filter to it.
The Median filter is a non-linear method used to remove noise from images. It replaces each pixel’s value with the median value of its neighbouring pixels. This technique is highly effective against salt and pepper noise in image datasets. When the filter size is selected, the pixel values in the neighbourhood are sorted from least to greatest, and the median value is selected as the new pixel value, reducing isolated noise in images.

The final result is a filter applied image with reduced noise, which is then saved as ‘filtered_image.jpg’. The images are displayed afterward to confirm that the noise in ‘noisy_image.jpg’ is indeed reduced in ‘filtered_image.jpg’.

Combining Libraries and Techniques

Case Study: Enhancing Underexposed Images

Here, we’ll focus on the task of enhancing an underexposed image using the Python images libraries Pillow and OpenCV.

Firstly, ensure you have the necessary libraries installed with the following commands:

!pip install pillow opencv-python

Now, we will open an underexposed image and use the histogram equalization technique to enhance its quality.

from PIL import Image
import cv2
import numpy as np


input_image = Image.open("underexposed_image.jpg")


gray_image = cv2.cvtColor(np.asarray(input_image), cv2.COLOR_RGB2GRAY)


equalized_image = cv2.equalizeHist(gray_image)


output_image = Image.fromarray(equalized_image)
output_image.save("enhanced_image.jpg")

In this code block, we start off by importing essential libraries. We then load our underexposed image as an array using PIL’s Image.open function, and convert it to grayscale using cv2’s cvtColor function. After that, we apply the histogram equalization with the cv2’s equalizeHist function. Finally, we convert it back into a PIL image and save the enhanced image.

This results in an image whose intensity distribution has been leveled out, making previously dark areas more visible. This example highlights how powerful Python’s image processing libraries can be when used in combination.

Case Study: Restoring Old Photographs

Below will guide you on how the code to restore old photographs using Python libraries and techniques may look theoretically.

Here is what your Python script might look like:

from PIL import Image
import cv2
import numpy as np


def restore_image(old_image_path):
    # Load the image using OpenCV
    old_image = cv2.imread(old_image_path, 0)

    # Apply histogram equalization to enhance contrast
    equalized_image = cv2.equalizeHist(old_image)
    
    # Apply median blur to reduce noise
    restored_image = cv2.medianBlur(equalized_image, 5)
    
    # Save the enhanced image
    new_image_path = "restored_image.jpg"
    cv2.imwrite(new_image_path, restored_image)
    
    return new_image_path


old_image_path = "/path/to/your/old/image.jpg"


new_image_path = restore_image(old_image_path)


old_image = Image.open(old_image_path)
new_image = Image.open(new_image_path)

old_image.show("Old Image")
new_image.show("Restored Image")

In this script, we first import the necessary libraries. We define a function `restore_image` that takes an old image path as input and returns a new image path.

Within this function, we use OpenCV’s `imread` function to load the image. We then use `equalizeHist` for histogram equalization, which enhances the contrast of the image.

We also apply a median blur to reduce noise in the image, using the `medianBlur` function. This step is particularly important for old photographs that may have a lot of random noise.

Finally, we save and then display both the old and restored images for comparison.

Keep in mind that this is just a simple example and actual image restoration might involve more complex techniques, depending on the specific problems (like scratches, fading, etc.) present in the old photographs.

Conclusion

Through the course of this article, we have ventured into the vast field of automated image enhancement using Python, discovering significant libraries such as Pillow, OpenCV, and SciKit Image and their corresponding applications in various essential techniques. In this era of rapid digital transformation, the ability to swiftly refine and enhance images using automated techniques is revolutionizing numerous industries, from digital marketing and web development to biomedical research and beyond. Given the intuitive nature and extensive resources of Python, it’s a potent tool in the realm of image processing. With increasing advancements, one can anticipate even more sophisticated capabilities in Python for image enhancement in the future. As we continue exploring and developing in this field, one thing is clear – Automated Image Enhancement with Python symbolizes a riveting blend of technology and creativity that is set to redefine the digital imagery landscape.

Share This Post

More To Explore

Default Alt Text
AWS

Integrating Python with AWS DynamoDB for NoSQL Database Solutions

This blog provides a comprehensive guide on leveraging Python for interaction with AWS DynamoDB to manage NoSQL databases. It offers a step-by-step approach to installation, configuration, database operation such as data insertion, retrieval, update, and deletion using Python’s SDK Boto3.

Default Alt Text
Computer Vision

Automated Image Enhancement with Python: Libraries and Techniques

Explore the power of Python’s key libraries like Pillow, OpenCV, and SciKit Image for automated image enhancement. Dive into vital techniques such as histogram equalization, image segmentation, and noise reduction, all demonstrated through detailed case studies.

Do You Want To Boost Your Business?

drop us a line and keep in touch