Blogs/Sharpening an Image

Sharpening an Image

mesakarghm Sep 17 2021 1 min read 41 views
Computer Vision
Sharpening an Image.jpeg

Image Sharpening is an image enhancement technique which increases the contrast between bright and dark regions to bring out the features. Image Sharpening is used to highlight the edges and fine details in an image. We can use various sharpening filters, which performs an convolution operation to the existing image pixels to get a sharpened image. The sharpening filters are divided into the following groups: 

  • High Pass Filters 
  • Laplacian of Gaussian / Mexican Hat Filters 
  • Unsharp Masking

Here, I will show how to use a high pass filter to get the effect of image sharpening. A high pass filter lets high frequencies pass and reduces the lower frequencies and is extremely sensitive to shut noise. To construct a high-pass filter, the kernel coefficient should be set positive near the center of the kernel and should be set negative in the outer periphery. 

One example of such high pass filter is : 

\(\begin{bmatrix} -1/9 & -1/9 & -1/9\\ -1/9 & 1 & -1/9 \\ -1/9 & -1/9 & -1/9 \end{bmatrix} \)

This is just an example of one possible kernel for a sharpening filter. There can be many other filters which can be used for image sharpening. 

Below I provide an all Python implementation, which uses the sharpening filter to sharpen a grayscale image. 

 

Learn and practice this concept here: 

https://mlpro.io/problems/image-sharpen/

def sharpen(image):
    """
    This function which takes an image and returns the sharpened image using the sharpening filter.

    :param image: a numpy array of size [image_height, image_width].
    :return: a numpy array of size [image_height, image_width] (sharpened image).
    """
    kernel = np.array([[-1/9,-1/9,-1/9],[-1/9,1,-1/9],[-1/9,-1/9,-1/9]])
    # Flip the kernel
    kernel = np.flipud(np.fliplr(kernel))
    # convolution output
    output = np.zeros_like(image)

    # Add zero padding to the input image
    image_padded = np.zeros((image.shape[0] + 2, image.shape[1] + 2))
    image_padded[1:-1, 1:-1] = image

    # Loop over every pixel of the image
    for x in range(image.shape[1]):
        for y in range(image.shape[0]):
            # element-wise multiplication of the kernel and the image
            output[y, x]=(kernel * image_padded[y: y+3, x: x+3]).sum()

    return output