Show Using Gaussian filter/kernel to smooth/blur an image is a very important tool in Computer Vision. You will find many algorithms using it before actually processing the image. Today we will be Applying Gaussian Smoothing to an image using Python from scratch and not using library like OpenCV. High Level Steps:There are two steps to this process:
Gaussian Kernel/Filter:Create a function named
Create a vector of equally spaced number using the size argument passed. When the
Now we will call the
Then we will create the outer product and normalize to make sure the center value is always 1. Kernel Output:In order to set the sigma automatically, we will use following equation: (This will work for our purpose, where filter size is between 3-21):
Here is the output of different kernel sizes. As you are seeing the dnorm()
Here is the Convolution and Average:We will create the convolution function in a generic way so that we can use it for other operations. This is not the most efficient way of writing a convolution function, you can always replace with one provided by a library. However the main objective is to perform all the basic operations from scratch. I am not going to go detail on
the Let’s look at the
The function has the image and kernel as the required parameters and we will also pass average as the 3rd argument. The average argument will be used only for smoothing filter. Notice, we can actually pass any filter/kernel, hence this function is not coupled/depended on the previously written Since our
We want the output image to have the same dimension as the input image. This is technically known as the \( In the the last two lines, we are basically creating an empty numpy 2D array and then copying the image to the proper location so that we can have the padding applied in the final output. In the below image we have applied a padding of 7, hence you can see the black border.
Now simply implement the convolution operation using two loops.
In order to apply the smooth/blur effect we will divide the output pixel by the total number of pixel available in the kernel/filter. This will be done only if the value of average is set We are finally done with our simple convolution function. Here is the output image. gaussian_blur():So the
main():In the main function, we just need to call our
Conclusion:As you have noticed, once we use a larger filter/kernel there is a black border appearing in the final output. This is because we have used zero padding and the color of zero is black. You can implement two different strategies in order to avoid this.
Full Code:
Project in Github:Please find the full project here: |