Sharpening An Image using OpenCV Library in Python

Shiv Last Updated : 17 Aug, 2023
7 min read

This article was published as a part of the Data Science Blogathon

From our previous article, we have learned about how to blur an image using a kernel, and we have also learned exactly what a kernel is- It simply refers to the matrix involved in the image manipulation process. For the task of blurring an image, we created a kernel to average the pixel values. At this point in our OpenCV tutorial, we have obtained a good understanding of the OpenCV package in the Python programming language.

If you have not read through my previous articles and would like to do so, kindly navigate to the following hyperlinks:

We will now look at the process of sharpening an image, we will make use of a kernel to highlight each particular pixel and enhance the color that it emits. It is very similar to the process of blurring, except that now, instead of creating a kernel to average each pixel intensity, we are creating a kernel that will cause the pixel intensities to be higher and therefore more prominent to the human eye.

To facilitate this learning experience we shall make use of the same image as in our previous article. The image may be downloaded from this link or saved from below.

Sharpening An Image  1

Source: Pinterest.

Understanding The Backend Of The Process.

It is good to know that kernels are used for the process of blurring images, sharpening images, embossing, edge detection, and much more. A kernel is known by other names such as:

  • Convolution Matrix.
  • Mask.
  • Matrix/Array.

The process of blurring, sharpening, embossing, edge detection, and others, require that a kernel be applied to the image pixels, which is also why this process is also referred to as Convolution- i.e, the process during which the kernel is applied to the image.

There is a fixed/standard general formula for convolutions (blurring, sharpening, etc). This formula is as follows:

Source: Wikipedia.

The crucial point to know when you are working with image processing tasks is that the formula does not differ greatly, and the type of kernel that you use affects the operation you are performing on the image. Because it is the kernel that brings about a change in pixel formation and intensity when multiplied with the pixels in the original image.

So essentially what I am saying is that multiplying by a particular kernel (array of values) will bring about a specific change in the image presentation.

A few of the commonly used kernels are as follows:

Sharpening An Image  2

Source: Wikipedia.

I highly recommend that you visit this Wikipedia page to obtain a higher level of understanding and insight into the discussion.

How to sharpen an image in Python using OpenCV?

Here is a step by step procedure to sharpen an image in python using OpenCV

  1. Import the necessary libraries

    import cv2
    import numpy as np

  2. Load the image

    image = cv2.imread(‘your_image.jpg’)

  3. Convert the image to grayscale (optional)

    If your image is in color and you want to apply sharpening to the grayscale version, you can convert it using:

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

  4. Apply the sharpening filter

    kernel = np.array([[0, -1, 0],
    [-1, 5, -1],
    [0, -1, 0]])
    sharpened = cv2.filter2D(image, -1, kernel)

    In the above code, we define a sharpening kernel (a 3×3 matrix) with values that emphasize edges. The filter2D function applies this kernel to the image to perform the sharpening operation.

  5. Display the original and sharpened images:

    cv2.imshow(‘Original Image’, image)
    cv2.imshow(‘Sharpened Image’, sharpened)
    cv2.waitKey(0) cv2.destroyAllWindows()

    This code displays both the original and sharpened images using OpenCV’s imshow function. waitKey(0) waits for a keyboard event, and destroyAllWindows closes the image windows when a key is pressed.

That’s it! By following these steps, you can sharpen an image using OpenCV in Python. Remember to adjust the kernel values if necessary to achieve the desired sharpening effect.

Python Implementation.

Now that we understand how kernels function, we may proceed to sharpen an image using the Python Programming Language.

To sharpen an image in Python, we are required to make use of the filter2D() method. This method takes in several arguments, 3 of which are very important. The arguments to be passed in are as follows:

  • src: This is the source image, i.e., the image that will undergo sharpening.
  • ddepth: This is an integer value representing the expected depth of the output image. We will set this value to be equal to -1. In doing this, we tell the compiler that the output image will have the same depth as the input image.
  • kernel: This is the kernel we will use to conduct our desired process. Since we wish to sharpen an image our kernel will be as follows:
3 Sharpening An Image

Source: Wikipedia.

Before we attempt to sharpen our image as follows, we must first import the necessary packages into our script:

# load the required packages
import cv2
import numpy as np

Next, we will proceed to load the image into our system memory. We will load the image in standard, i.e., Color format.

# load the image into system memory
image = cv2.imread('C:/Users/Shivek/Pictures/images.jpg', flags=cv2.IMREAD_COLOR)

We will thereafter display the contents of the variable storing the image, to the screen:

# display the image to the screen
cv2.imshow('AV CV- Winter Wonder', image)
cv2.waitKey()
cv2.destroyAllWindows()

By this point in our OpenCV learning experience, we should be familiar with the explanation of the above code blocks. Essentially what we have done is as follows:

  • We have imported the necessary packages into our python script.
  • We have loaded the image into system memory using the imread() method while passing the file name/path, and the appropriate color flag.
  • We proceeded to utilize the imshow() method to display the image window, which will be terminated upon user action.

 Output to the above code will be seen as follows:

Sharpening An Image  4

Below is the Python code we will use for sharpening the image:

kernel = np.array([[0, -1, 0],
                   [-1, 5,-1],
                   [0, -1, 0]])
image_sharp = cv2.filter2D(src=image, ddepth=-1, kernel=kernel)
cv2.imshow('AV CV- Winter Wonder Sharpened', image_sharp)
cv2.waitKey()
cv2.destroyAllWindows()

Output to the above code block will be seen as follows:

And immediately, one can see that the glare, and luminance of our sharpened image, are much more noticeable and striking to the eye, than the original image. If one looks closely at the image, one will notice that the edges/outlines of objects in the image have been highlighted and made to look more prominent.

Thus we have successfully sharpened an image using the OpenCV package in Python Programming Language. I do hope that you enjoyed reading through this article, and have new takeaways of OpenCV Operations in Python.

Frequently Asked Questions

Q1. How does image sharpening work Python?

A. Image sharpening in Python involves enhancing the edges and fine details in an image to improve its visual quality. It is typically achieved by emphasizing high-frequency components, such as edges, while suppressing low-frequency components.

The most common approach to image sharpening is to apply a sharpening filter or kernel to the image using convolution. In Python, OpenCV provides functions to perform convolution and apply filters.

Here’s a general overview of how image sharpening works:

1. Load the image: Read the image using OpenCV’s imread function and store it in a variable.
2. Convert the image to grayscale (optional): If desired, convert the image to grayscale using OpenCV’s cvtColor function. This step is useful if you want to apply sharpening to the grayscale version of the image.
3. Create a sharpening filter/kernel: Define a kernel, which is a small matrix of values, that highlights edges and fine details. Common sharpening kernels include Laplacian, Unsharp Masking, or High Pass filters.
4. Apply the sharpening filter: Use OpenCV’s filter2D function to apply the sharpening kernel to the image. The filter2D function convolves the kernel with each pixel of the image, enhancing the edges and details.
5. Adjust the sharpening strength: You can control the strength of the sharpening effect by adjusting the values in the kernel. Higher values increase the emphasis on edges, while lower values yield a milder sharpening effect.
6. Display the original and sharpened images: Use OpenCV’s imshow function to display the original and sharpened images side by side. You can also save the sharpened image to a file using the imwrite function.

It’s worth noting that image sharpening can also be achieved using other techniques, such as gradient-based methods or frequency domain operations like Fourier Transform. However, the convolution-based approach described above is a commonly used and straightforward method for image sharpening in Python using OpenCV.

Q2. What is image sharpening vs smoothing?

A. Image sharpening and smoothing are two opposite processes in image processing. Sharpening enhances the edges and fine details in an image, increasing its visual clarity and emphasizing high-frequency components. It helps to enhance the image’s crispness and improve its overall appearance. On the other hand, smoothing, also known as blurring or averaging, reduces image noise and removes fine details. It works by suppressing high-frequency components and creating a smoother appearance. Smoothing is often used to reduce noise, blur sensitive information, or create artistic effects, while sharpening aims to enhance image details and edges.

Please feel free to connect with me on LinkedIn. If you would like to see all articles that I have composed for Analytics Vidhya, please navigate to my Analytics Vidhya Profile.

Thank you for your time.

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

Responses From Readers

Clear

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details