In this Python OpenCV lesson we are going to learn about Python OpenCV Gaussian Image Blurring, this is the second technique for smoothing the image, in this technique 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
This is the complete code for this lesson.
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 28 29 30 31 |
import cv2 import matplotlib.pyplot as plt #read the image image = cv2.imread('lena.tif') #create gaussian blur function, give the # image, kernel and sd 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) #show the image using matplotlib library 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() |
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) |
Run the complete code and this is the result.