Master Image Enhancement Techniques With OpenCV

Image enhancement is a crucial tool for computer vision and image editing applications. It aims to improve the quality of images.

By enhancing image quality, the accuracy and reliability of image analysis and processing techniques can be significantly enhanced. This is particularly important in object detection, recognition, segmentation, and tracking applications.

Image enhancement can help out when factors like low light conditions, sensor noise, motion blur, or transmission errors have compromised image quality.

Setting Up Your Environment

Start by setting up a Python environment, then run the following terminal command to install the OpenCV library. You’ll use OpenCV to load and process the initial image, and to save the final enhanced image.

pip install opencv-python

You’ll use Matplotlib to display the two images. Install it using this command:

pip install matplotlib

Finally, install NumPy, which you'll use for numerical operations including creating lookup tables for gamma correction and defining the kernel for image sharpening:

pip install numpy 

Once you’ve installed these libraries in your environment, you’re ready to start coding.

The full source code for this demo is available in a GitHub repository .

Importing the Necessary Libraries

Import the libraries you previously installed in your environment:

import cv2
import matplotlib.pyplot as plt
import numpy as np

Note that you should import OpenCV as cv2. This is a standard practice that aims at ensuring code compatibility and ease of understanding for other developers.

Loading and Displaying the Original Image

Start by loading the original image using the cv2.imread function. This is the input image that your program will perform enhancement techniques on. Then display it using the appropriate Matplotlib functions:

image = cv2.imread('example.jpg')
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('Original Image')
plt.show()

Displaying the original image will help you compare the results of the program later:

The above image will be the input of the program.

Reducing Noise in the Image

Denoising is a technique that aims to reduce noise—random distortions—in the image. This results in a smoother output. OpenCV provides the fastNlMeansDenoisingColored function for this purpose. It uses a non-local means algorithm to remove noise while preserving image details.

# Apply image enhancements
# Denoise the image
denoised_image = cv2.fastNlMeansDenoisingColored(image, None, 10, 10, 7, 21)

The fastNlMeansDenoisingColored function takes several parameters, including the image, filter strength, template window size, and search window size. You can experiment with different values to get your desired results.

Stretch Contrast to Improve Detail Visibility

Contrast stretching is also known as normalization. It stretches the intensity values to span a certain range. This in turn improves the visibility of the details in the image.

You can apply contrast stretching to the denoised image using OpenCV’s normalize function:

# Perform contrast stretching
contrast_stretched_image = cv2.normalize(denoised_image, None, 255, 0, cv2.NORM_MINMAX, cv2.CV_8UC1)

How to Sharpen the Image

Image sharpening enhances the edges and details of the image, helping to improve the image's crispness.

# Image Sharpening
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32)
sharpened_image = cv2.filter2D(contrast_stretched_image, -1, kernel=kernel)

The above code creates a kernel matrix that emphasizes the edges and details in the image. The cv2.filter2D function applies the kernel to the contrast-stretched image, sharpening it as a result.

Adjust Brightness to Improve Exposure

Brightness adjustment controls the overall brightness of an image. It helps make the image visually appealing and well-exposed.

# Brightness Adjustment
brightness_image = cv2.convertScaleAbs(sharpened_image, alpha=1, beta=5)

The cv2.convertScaleAbs function adjusts the brightness of the image. The alpha parameter controls the contrast, while the beta parameter controls the brightness. Increasing the beta value enhances the brightness of the image.

Apply Gamma Correction to Brighten the Image

An image can appear too bright after the brightness adjustment technique. Gamma correction adjusts the overall brightness and contrast of an image. It corrects images that appear too dark or too bright.

# Gamma Correction
gamma = 1.5
lookup_table = np.array([((i / 255.0) ** gamma) * 255 for i in np.arange(0, 256)]).astype("uint8")
gamma_corrected_image = cv2.LUT(brightness_image, lookup_table)

The above code snippet creates a lookup table that applies gamma correction transformation to the brightness-adjusted image. The gamma value controls the adjustment. Use values greater than 1 to make the image darker, and values less than 1 to make it brighter.

Saving and Displaying the Final Enhanced Image

Once you’ve applied the above enhancement techniques, save the final processed image to a file.

# Save final image
cv2.imwrite('final_image.jpg', gamma_corrected_image)

Then display the output of the program using Matplotlib.

# Display the final enhanced image
plt.imshow(cv2.cvtColor(gamma_corrected_image, cv2.COLOR_BGR2RGB))
plt.title('Final Enhanced Image')
plt.show()

The final enhanced image is as follows:

The Future of Image Enhancement

The future of image enhancement is in the field of artificial intelligence. Machine learning algorithms are being trained to automatically perform image enhancement techniques on images.

These programs treat each image independently, so they apply different values of the techniques for different images.

ncG1vNJzZmivp6x7rq3KnqysnZ%2Bbe6S7zGimqZ2emMNutcyanp5llaO1orrCnqSepqRiwaavx6egqq2VqHw%3D