Open In App

Image Enhancement Techniques using OpenCV – Python

Last Updated : 15 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Image enhancement is the process of improving the quality and appearance of an image. It can be used to correct flaws or defects in an image, or to simply make an image more visually appealing. Image enhancement techniques can be applied to a wide range of images, including photographs, scans, and digital images. Some common goals of image enhancement include increasing contrast, sharpness, and colorfulness; reducing noise and blur; and correcting distortion and other defects. Image enhancement techniques can be applied manually using image editing software, or automatically using algorithms and computer programs such as OpenCV. 
In this article, we will explore a variety of image enhancement techniques that can be performed using OpenCV and Python. OpenCV is a powerful, open-source computer vision library that provides a wide range of image processing and computer vision algorithms. By combining the capabilities of OpenCV with the versatility of Python, we can easily implement a variety of image enhancement techniques to improve the quality and appearance of our images. 
In the following sections, we will discuss the different image enhancement techniques and how to implement them using OpenCV and Python. There are several image enhancement techniques that you can use with OpenCV and Python to improve the quality and clarity of images. Here are a few examples:

Adjusting brightness and contrast

Adjusting the brightness and contrast of an image can significantly affect its visual appeal and effectiveness. It can also help to correct defects or flaws in the image and make it easier to see details. Finding the right balance of brightness and contrast is important for creating an attractive and effective image.

There are several ways to adjust the brightness and contrast of an image using OpenCV and Python. One common method is to use the cv2.addWeighted() function, which allows you to adjust the brightness by adding a scalar value to each pixel in the image, and the contrast by scaling the pixel values.
Here is an example of how to adjust the brightness and contrast of an image using the cv2.addWeighted() function:

Python3




#Import the necessary libraries
import cv2
import matplotlib.pyplot as plt
import numpy as np
  
# Load the image
image = cv2.imread('GFG.jpeg')
  
#Plot the original image
plt.subplot(1, 2, 1)
plt.title("Original")
plt.imshow(image)
  
# Adjust the brightness and contrast
# Adjusts the brightness by adding 10 to each pixel value
brightness = 10 
# Adjusts the contrast by scaling the pixel values by 2.3
contrast = 2.3  
image2 = cv2.addWeighted(image, contrast, np.zeros(image.shape, image.dtype), 0, brightness)
  
#Save the image
cv2.imwrite('modified_image.jpg', image2)
#Plot the contrast image
plt.subplot(1, 2, 2)
plt.title("Brightness & contrast")
plt.imshow(image2)
plt.show()


Output:

Brightness & contrast -Geeksforgeeks

Brightness & contrast

In this example, the brightness of the image is adjusted by adding 10 to each pixel value, and the contrast is adjusted by scaling the pixel values by 2.3. You can adjust the values of brightness and contrast to achieve the desired level of brightness and contrast.

Another method for adjusting the brightness and contrast of an image is to use the cv2.convertScaleAbs() function, which allows you to adjust the brightness and contrast using a combination of scaling and shifting the pixel values.

Python3




#Import the necessary libraries
import cv2
import matplotlib.pyplot as plt
import numpy as np
  
# Load the image
image = cv2.imread('GFG.jpeg')
  
#Plot the original image
plt.subplot(1, 2, 1)
plt.title("Original")
plt.imshow(image)
  
# Adjust the brightness and contrast 
# g(i,j)=α⋅f(i,j)+β
# control Contrast by 1.5
alpha = 1.5  
# control brightness by 50
beta = 50  
image2 = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)
  
#Save the image
cv2.imwrite('Brightness & contrast.jpg', image2)
#Plot the contrast image
plt.subplot(1, 2, 2)
plt.title("Brightness & contrast")
plt.imshow(image2)
plt.show()


Outputs:

Brightness & contrast -Geeksforgeeks

Brightness & contrast

In this example, the brightness and contrast are adjusted using a combination of scaling and shifting the pixel values. You can adjust the values of alpha and beta to achieve the desired level of brightness and contrast.

Sharpening images

Sharpening is the process of enhancing the edges and fine details in an image to make it appear sharper and more defined. It is important because it can help to bring out the details and features in an image, making it more visually appealing and easier to understand. Sharpening can be used to correct blur or softness in an image and can be applied using a variety of techniques.

One common method for sharpening images using OpenCV and Python is to use the cv2.filter2D() function, which convolves the image with a kernel. The kernel can be designed to enhance the edges in the image, resulting in a sharper image.

Here is an example of how to sharpen an image using the cv2.filter2D() function:

Python3




#Import the necessary libraries
import cv2
import matplotlib.pyplot as plt
import numpy as np
  
# Load the image
image = cv2.imread('GFG.jpeg')
  
#Plot the original image
plt.subplot(1, 2, 1)
plt.title("Original")
plt.imshow(image)
  
# Create the sharpening kernel
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
  
# Sharpen the image
sharpened_image = cv2.filter2D(image, -1, kernel)
  
#Save the image
cv2.imwrite('sharpened_image.jpg', sharpened_image)
  
#Plot the sharpened image
plt.subplot(1, 2, 2)
plt.title("Sharpening")
plt.imshow(sharpened_image)
plt.show()


Output:

Sharpening - Geeksforgeeks

Sharpening

In this example, a 3×3 sharpening kernel is used to enhance the edges in the image. You can experiment with different kernels to achieve the desired level of sharpening. Numpy is used to create the sharpening kernel is created as a NumPy array using the np.array() function. This array is then passed as an argument to the cv2.filter2D() function, which convolves the image with the kernel to sharpen it.

Another method for sharpening images is to use the cv2.Laplacian() function, which calculates the Laplacian of an image and returns the result as a sharpened image.

Python3




#Import the necessary libraries
import cv2
import matplotlib.pyplot as plt
import numpy as np
  
# Load the image
image = cv2.imread('GFG.jpeg')
  
#Plot the original image
plt.subplot(1, 2, 1)
plt.title("Original")
plt.imshow(image)
  
# Sharpen the image using the Laplacian operator
sharpened_image2 = cv2.Laplacian(image, cv2.CV_64F)
  
#Save the image
cv2.imwrite('Laplacian sharpened_image.jpg', sharpened_image2)
  
#Plot the sharpened image
plt.subplot(1, 2, 2)
plt.title("Laplacian Sharpening")
plt.imshow(sharpened_image2)
plt.show()


Output:

Laplacian Sharpening - Geeksforgeeks

Laplacian Sharpening

In this example, the Laplacian operator calculates the sharpened image. You can adjust the depth of the output image using the cv2.CV_64F parameter.

Removing noise from images

Noise reduction is the process of removing or reducing unwanted noise or artifacts from an image. It is important because it can improve the visual quality and clarity of the image and make it easier to analyze or process using computer algorithms. Noise can be introduced into an image due to a variety of factors and can degrade its quality. There are several techniques for reducing noise, including using filters such as the median filter or the Gaussian filter. It is important to apply noise reduction judiciously to avoid blur or loss of detail in the image.

One common method for removing noise from images using OpenCV and Python is to use a median filter. The median filter works by replacing each pixel in the image with the median value of a set of neighboring pixels. This can help to smooth out noise and reduce artifacts in the image.

Here is an example of how to remove noise from an image using the cv2.medianBlur() function in OpenCV:

Python3




#Import the necessary libraries
import cv2
import matplotlib.pyplot as plt
import numpy as np
  
# Load the image
image = cv2.imread('GFG.jpeg')
  
#Plot the original image
plt.subplot(1, 2, 1)
plt.title("Original")
plt.imshow(image)
  
# Remove noise using a median filter
filtered_image = cv2.medianBlur(image, 11)
  
#Save the image
cv2.imwrite('Median Blur.jpg', filtered_image)
  
#Plot the blured image
plt.subplot(1, 2, 2)
plt.title("Median Blur")
plt.imshow(filtered_image)
plt.show()


Output:

Median Blur -Geeksforgeeks

Median Blur

In this example, the cv2.medianBlur() function is used to apply a median filter to the image. The 5 parameter specifies the size of the kernel to use for the filter. You can adjust the kernel size to achieve the desired level of noise reduction.

Another method for removing noise from images is to use a Gaussian filter, which uses a weighted average of neighboring pixels to smooth out noise and reduce artifacts. You can use the cv2.GaussianBlur() function to apply a Gaussian filter to an image in OpenCV.

Python3




#Import the necessary libraries
import cv2
import matplotlib.pyplot as plt
import numpy as np
  
# Load the image
image = cv2.imread('GFG.jpeg')
  
#Plot the original image
plt.subplot(1, 2, 1)
plt.title("Original")
plt.imshow(image)
  
# Remove noise using a Gaussian filter
filtered_image2 = cv2.GaussianBlur(image, (7, 7), 0)
  
#Save the image
cv2.imwrite('Gaussian Blur.jpg', filtered_image2)
  
#Plot the blured image
plt.subplot(1, 2, 2)
plt.title("Gaussian Blur")
plt.imshow(filtered_image2)
plt.show()


Output:

Gaussian Blur -Geeksforgeeks

Gaussian Blur

In this example, the cv2.GaussianBlur() function is used to apply a Gaussian filter to the image. The (5, 5) parameter specifies the size of the kernel to use for the filter, and the 0 parameter specifies the standard deviation of the Gaussian function. You can adjust these parameters to achieve the desired level of noise reduction.

Enhancing color in images

Color enhancement is adjusting the colors in an image to make them more vibrant, balanced, or natural. It can be used to correct color defects or problems in an image or to simply make an image more appealing and aesthetically pleasing. Color enhancement is important because it can significantly affect the visual impact and effectiveness of an image. It can also be useful for correcting color errors or problems in an image and can make it easier to see details and features in the image. There are several techniques for enhancing the colors in an image, including adjusting the color balance, adjusting the saturation, and adjusting the hue.
There are several ways to enhance the colors in an image using OpenCV and Python. One common method is to use the cv2.cvtColor() function, which allows you to convert the image from one color space to another. This can be useful for adjusting the color balance or saturation of the image.
Here is an example of how to enhance the colors in an image using the cv2.cvtColor() function:

Python3




#Import the necessary libraries
import cv2
import matplotlib.pyplot as plt
import numpy as np
  
# Load the image
image = cv2.imread('GFG.jpeg')
  
#Plot the original image
plt.subplot(1, 2, 1)
plt.title("Original")
plt.imshow(image)
  
# Convert the image from BGR to HSV color space
image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
  
# Adjust the hue, saturation, and value of the image
# Adjusts the hue by multiplying it by 0.7
image[:, :, 0] = image[:, :, 0] * 0.7
# Adjusts the saturation by multiplying it by 1.5
image[:, :, 1] = image[:, :, 1] * 1.5
# Adjusts the value by multiplying it by 0.5
image[:, :, 2] = image[:, :, 2] * 0.5
  
# Convert the image back to BGR color space
image2 = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)
  
#Save the image
cv2.imwrite('enhanced coloured.jpg', image2)
  
#Plot the enhanced image
plt.subplot(1, 2, 2)
plt.title("enhanced coloured")
plt.imshow(image2)
plt.show()


Output:

Enhanced Coloured

This code first converts the image from the BGR color space to the HSV color space using the cv2.cvtColor() function. It then adjusts the hue, saturation, and value (brightness) of the image by multiplying the corresponding channels by a scalar value. Finally, it converts the image back to the BGR color space and saves the modified image. You can adjust the scalar values to achieve the desired level of color enhancement.

Image resizing and scaling

Image resizing and scaling involve adjusting the dimensions and size of an image. Both are important for meeting specific requirements or context, such as fitting a specific size or aspect ratio or reducing the file size. There are several techniques, including interpolation methods like the nearest neighbor, bilinear, and bicubic interpolation. It is important to choose a method that preserves image quality and clarity.

You can use the cv2.resize() function in OpenCV to resize and scale images. The cv2.resize() function takes the following arguments:

  • src: The input image.
  • dsize: The size of the output image, specified as a tuple (width, height).
  • fx: The scaling factor along the x-axis.
  • fy: The scaling factor along the y-axis.
  • interpolation: The interpolation method to use.

Here is an example of how to use the cv2.resize() function to resize an image:

Python3




#Import the necessary libraries
import cv2
import matplotlib.pyplot as plt
import numpy as np
  
# Load the image
image = cv2.imread('GFG.jpeg')
  
#Plot the original image
plt.subplot(1, 2, 1)
plt.title("Original")
plt.imshow(image)
  
# Resize the image to a specific width and height
resized_image = cv2.resize(image, (2100, 1500))
  
#Save the Resized image
cv2.imwrite('Resized image.jpg', resized_image)
  
#Plot the Resized image
plt.subplot(1, 2, 2)
plt.title("Resized")
plt.imshow(resized_image)
plt.show()


Output:

Resized Image -Geeksforgeeks

Resized Image

In this example, the image is resized to a width of 400 pixels and a height of 300 pixels.
You can also use the fx and fy parameters to specify the scaling factors along the x-axis and y-axis, respectively. For example:

Python3




#Import the necessary libraries
import cv2
import matplotlib.pyplot as plt
import numpy as np
  
# Load the image
image = cv2.imread('GFG.jpeg')
  
#Plot the original image
plt.subplot(1, 2, 1)
plt.title("Original")
plt.imshow(image)
  
# Scale the image by a factor of 2 along both axes
scaled_image = cv2.resize(image, None, fx=2, fy=2)
  
#Save the image
cv2.imwrite('Scaled.jpg', scaled_image)
  
#Plot the Scaled image
plt.subplot(1, 2, 2)
plt.title("Scaled")
plt.imshow(scaled_image)
plt.show()


Output:

Scaled Image -Geeksforgeeks

Scaled Image

In this example, the image is scaled by a factor of 2 along both axes, resulting in an image that is twice the size of the original. The interpolation parameter allows you to specify the interpolation method to use when resizing or scaling the image. The available options include cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, and others.
This is just a basic example of how to resize and scale images using OpenCV and Python. You can adjust the size and scaling factors to achieve the desired results, and you can also specify the interpolation method to use when resizing or scaling the image.

Inverse Transform

We can also inverse the color by simply subtracting each value from 255

Python3




#Import the necessary libraries
import cv2
import matplotlib.pyplot as plt
import numpy as np
  
# Load the image
image = cv2.imread('GFG.jpeg')
  
#Plot the original image
plt.subplot(1, 2, 1)
plt.title("Original")
plt.imshow(image)
  
# Inverse by subtracting from 255
inverse_image = 255 - image
  
#Save the image
cv2.imwrite('inverse_image.jpg', inverse_image)
#Plot the Inverse image
plt.subplot(1, 2, 2)
plt.title("Inverse color")
plt.imshow(inverse_image)
plt.show()


Output:

Inverse color -Geeksforgeeks

Inverse color

Equalizing histograms –

Histogram equalization is a technique used to adjust the contrast of an image by spreading out the intensity values of the pixels in the image. It is important because it can improve the contrast and clarity of an image, making it easier to see details and features that might be difficult to see in an image with low contrast. There are several different methods for performing histogram equalization, including global histogram equalization and local histogram equalization. Global histogram equalization adjusts the contrast of the entire image, while local histogram equalization adjusts the contrast in small, localized areas of the image.
You can use the cv2.equalizeHist() function in OpenCV to equalize the histogram of an image. This function takes the image data as an argument and returns the equalized image data. Here is an example of how to use the cv2.equalizeHist() function to equalize the histogram of an image:

Python3




#Import the necessary libraries
import cv2
import matplotlib.pyplot as plt
import numpy as np
  
# Load the image
image = cv2.imread('GFG.jpeg')
  
#Plot the original image
plt.subplot(1, 2, 1)
plt.title("Original")
plt.imshow(image)
  
# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  
# Equalize the histogram
equalized_image = cv2.equalizeHist(gray_image)
  
#Save the equalized image
cv2.imwrite('equalized.jpg', equalized_image)
  
#Plot the equalized image
plt.subplot(1, 2, 2)
plt.title("equalized")
plt.imshow(equalized_image)
plt.show()


Output:

Equalized-Geeksforgeeks

Equalized

In this example, the image is first loaded from a file using the cv2.imread() function. It is then converted to grayscale using the cv2.cvtColor() function. The cv2.equalizeHist() function is then called and passed the grayscale image data as an argument. The equalized image data is stored in the equalized_image variable. Finally, the modified image is saved to a file using the cv2.imwrite() function.

Note that the cv2.equalizeHist() function only works on grayscale images. If you want to equalize the histogram of a color image, you will need to convert the image to a color space that separates the intensity values (such as the YCrCb color space) and apply histogram equalization to the intensity channel. You can then convert the image back to the original color space if desired.

Other Techniques 

Image enhancement is a wide field that involves adjusting images to improve their visual quality or to make them more suitable for further analysis. There are many techniques for enhancing images, such as:

  • Morphological transformations: These are operations based on the image shape. They are typically applied to binary images, but can also be used with grayscale images. Examples include dilation, erosion, opening, closing, etc.  Operations can be used to enhance or modify the shape or structure of objects in an image. To apply morphological operations with OpenCV and Python, you can use functions such as erode, dilate, and morphologyEx.
  • Edge detection: OpenCV provides several functions for performing edge detection, such as Canny(), Sobel(), and Laplacian(). These functions can be used to identify edges in an image by looking for sharp changes in pixel intensity.
  • Color correction: OpenCV provides several functions for adjusting the colors in an image, such as cvtColor() and inRange(). These functions can be used to perform tasks such as color balance, color grading, and white balancing.
  • Image gradients: OpenCV provides several functions for computing image gradients, such as Scharr(), Sobel(), and Laplacian(). These functions can be used to highlight changes in pixel intensity in an image and can be useful for tasks such as edge detection and image segmentation.
  • Image cropping: Cropping techniques can be used to remove unwanted areas from an image. To crop an image, you can use the copyMakeBorder function to create a new image with the desired dimensions, and then copy the relevant portion of the original image into the new image.
  • Image rotation: Rotation techniques can be used to change the orientation of an image. To rotate an image with OpenCV, you can use the warpAffine function with a rotation matrix.
  • Image blending: Blending techniques can be used to combine two or more images together. To blend images with OpenCV and Python, you can use the addWeighted function to combine the images using a weighted average.
  • Image thresholding: Thresholding techniques can be used to convert an image to black and white by setting a threshold value for pixel intensity. To apply thresholding, you can use the threshold function.
  • Image deblurring: Deblurring techniques can be used to remove blur from an image caused by camera shake, out-of-focus subjects, or other factors. To deblur an image, you can use the wiener function, which applies a Wiener filter to the image.
     

OpenCV is a powerful library for image processing and computer vision tasks and it provides many advanced image enhancement techniques that can be used for a variety of applications. Some of these techniques are:

  • Super-resolution: OpenCV provides the pyrUp() and pyrDown() functions for upsampling and downsampling images, respectively. These functions can be used as part of a super-resolution algorithm to increase the resolution of an image.
  • Image restoration: OpenCV provides several functions for image restoration, such as fastNlMeansDenoising() and fastNlMeansDenoisingColored(). These functions can be used to remove noise and improve the visual quality of an image.
  • Image fusion: OpenCV provides the addWeighted() function for combining two images using a weighted sum. This function can be used to fuse multiple images of the same scene to create a single image that contains more information or is of higher quality.
  • Image segmentation: OpenCV provides several functions for image segmentation, including threshold(), adaptiveThreshold(), and findContours(). These functions can be used to partition an image into regions or segments that correspond to different objects or regions of interest.
  • Image recognition: OpenCV provides several functions for image recognition, including HOGDescriptor() and SIFT(). These functions can be used to extract features from an image and train a machine-learning model to recognize objects or scenes.
  • Object detection: OpenCV provides several functions for object detection, including HOGDescriptor() and SIFT(). These functions can be used to detect and locate objects in an image or video in real time.
  • Image registration: OpenCV provides the registerTranslation() function for aligning or registering two or more images of the same scene. This function can be used to align images from different sensors or from different viewpoints.
  • Image stitching: Image stitching techniques can be used to combine multiple images into a single panoramic or mosaic image. To apply image stitching with OpenCV and Python, you can use techniques such as feature matching, which matches the features in the source images to create a common reference frame, and image warping, which warps the images to align them with the reference frame.
     

To effectively use image enhancement techniques using OpenCV and Python, it is important to choose the right technique for your images and desired outcomes, experiment with different parameters, use caution when increasing image contrast, use color appropriately, and consider using other image processing techniques as needed. For further reading and resources on image enhancement using OpenCV and Python, consider exploring the OpenCV documentation and tutorials, as well as online resources such as the PyImageSearch blog and tutorials, and the Python Machine Learning with OpenCV course. 
In conclusion, image enhancement is a crucial technique used to improve the visual quality of images in various fields such as medicine, robotics, security, photography, remote sensing, and manufacturing. OpenCV is a powerful open-source library that provides a wide range of image enhancement techniques for use in Python. By using OpenCV, developers can easily implement image enhancement techniques in their applications to improve the visual quality of images and extract valuable information from them. Whether you are a researcher, a developer, or a professional working in a field that relies on images, OpenCV and Python offers a flexible and powerful toolkit for enhancing the quality of your images.
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads