Create a Vignette Filter using OpenCV in Python

Vignette is a popular image filter that we use to darken the regions marking the boundary of an image. So this averts distractions while viewing the main content. The brightness and saturation decrease as we move radially outwards. Hence, as a direct result, the central portion of the image becomes a region of enhanced focus.  In this tutorial, we shall learn how to create a vignette filter using the OpenCV library in Python.

We shall dive into the code and explain the concepts involved all along.

Importing the necessary Python libraries and modules

import numpy as np 
import cv2


We are going to use a bright colorful image of some strawberries so that better illustration can be performed. You can download the image from here or from below:



Applying the filter

To apply the vignette filter, we need to assign more and more weights of the pixels as we move inwards. We need to create a kernel composed of two one-dimensional Gaussian functions traversing along the horizontal and vertical axes that would do the aforementioned task. For this purpose, we shall use the getGaussianKernel() function about which you can learn from here. This function takes two parameters:

  • ksize: the size of the kernel
  • sigma: the standard deviation of the Gaussian that regulates the size of the central region


input = cv2.imread('input/strawberry.jpg') 
height, width = input_image.shape[:2] 
x_gauss = cv2.getGaussianKernel(width,250) 
y_gauss = cv2.getGaussianKernel(height,200) 
kernel = x_gauss * y_gauss.T


Then, we need to create a mask from this kernel and apply that to the image. While doing that, we need to iterate for the three different color channels of the image.


mask = kernel * 255 / np.linalg.norm(kernel)  
output[:,:,0] = input[:,:,0] * mask 
output[:,:,1] = input[:,:,1] * mask 
output[:,:,2] = input[:,:,2] * mask 


Visualizing the output

cv2.imshow('vignette', output) 


Output image:

vignette filter of strawberry image


So as you can see, the central portion of the image is bright and saturated and more focussed. You can adjust the size of this region by changing the sigma variable in the getGaussianKernel(). Then you can visualize the variations. Hence, this concludes the tutorial on how to create a vignette filter using OpenCV in Python.


Also, read:

Leave a Reply

Your email address will not be published. Required fields are marked *