In this OpenCV article we are going to talk about Gaussian Blurring for Images in Python,
so this is the second technique for image smoothing or blurring in OpenCV . the first one was
using Averaging, you can check that article in the below link.
Read More Image Smoothing techniques in OpenCV
1: OpenCV Averaging Image Blurring in Python
So in Gaussian Blurring method we need to specify width and height of the kernel which should be
positive and odd. also we need to add standard deviation in the x and y directions. sigmax
and sigmay. you can use cv2.GaussianBlur() for this in opencv
So now this is the complete code for OpenCV Gaussian Blurring for Images in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import cv2 import matplotlib.pyplot as plt image = cv2.imread('lena.tif') gaussian_blur = cv2.GaussianBlur(image, (5,5), 0) #convert the image from bgr to rgb original_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) gaussian = cv2.cvtColor(gaussian_blur, cv2.COLOR_BGR2RGB) plt.subplot(121) plt.imshow(original_image),plt.title('Original Image') plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(gaussian),plt.title('Gaussian Blurred Image') plt.xticks([]), plt.yticks([]) plt.show() cv2.waitKey(0) cv2.destroyAllWindows() |
This line of code is used for reading of the image, make sure that you have added an image
in your working directory.
1 |
image = cv2.imread('lena.tif') |
So in here we are going to create our Gaussian Blur using cv2.GaussianBlur() function.
we need to give some parameters, our image, kernel size, sigmax and sigmay.
1 |
gaussian_blur = cv2.GaussianBlur(image, (5,5), 0) |
Because we are going to show our image in Matplotlib, so Matplotlib uses RGB (Red, Green, Blue)
color system, and OpenCV uses BGR (Blue, Green, Red) color system, we need to convert the BGR
color to RGB. if we don’t do this there will be messed up in the color.
1 2 |
original_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) gaussian = cv2.cvtColor(gaussian_blur, cv2.COLOR_BGR2RGB) |
Note: cv2.waitKey() is a keyboard binding function. Its argument is the time in milliseconds.
the function waits specified milliseconds for any keyboard event. If you press any key in that
time, the program continues. If 0 is passed, it waits indefinitely for a key stroke.
So now run the complete code and this will be the result.
Subscribe and Get Free Video Courses & Articles in your Email
Comments are closed.