Open In Colab

Sharpen image using unsharp mask#

We first install kornia

%matplotlib inline
!pip install kornia
import kornia
/home/docs/checkouts/ TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See
  from .autonotebook import tqdm as notebook_tqdm
import cv2
import numpy as np
import torch
import matplotlib.pyplot as plt

Downloading the example image.

!wget -q
# Read the image with OpenCV
img: np.ndarray = cv2.imread('squirrel.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#convert image to tensor
data: torch.tensor = kornia.utils.image_to_tensor(img, keepdim=False)
data = data.float() / 255.

We create Unsharp Mask filter object and apply it to data. The unsharp mask filter is initialized with the format kornia.filters.UnsharpMask(kernel_size, sigma). You can tune these parametres and experiment!

sharpen = kornia.filters.UnsharpMask((9,9), (2.5,2.5))
sharpened_tensor = sharpen(data)
difference = (sharpened_tensor - data).abs()
# Converting the sharpened tensor to image
sharpened_image = kornia.utils.tensor_to_image(sharpened_tensor) 
difference_image = kornia.utils.tensor_to_image(difference)

So, let us understand how we arrived till here.

  1. In the unsharp mask technique, first a gaussian blur is applied to the data.

  2. Then the blur is subtracted from the orignal data.

  3. The resultant is added to the origanl data.

  4. So, what do we get? Sharpened data!

# To display the input image, sharpened image and the difference image
fig, axs = plt.subplots(1, 3, figsize=(16, 10))
axs = axs.ravel()

axs[0].set_title('image source')


Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).