In this Python OpenCV lesson we are going to learn about Python OpenCV Bilateral Filtering, this is the fourth technique for image smoothing or blurring in OpenCV. a bilateral filter is non-linear, edge-preserving and noise-reducing smoothing filter. the intensity value at each pixel in an image is replaced by a weighted average of intensity values from nearby pixels. This weight can be based on a Gaussian distribution.
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 32 |
import cv2 import matplotlib.pyplot as plt #read the image image = cv2.imread('imageface.jpg') #create bilteralfilter function bil_blur = cv2.bilateralFilter(image,13,75,75) #convert the image from bgr to rgb cvt_orig = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cvt_blur = cv2.cvtColor(bil_blur, cv2.COLOR_BGR2RGB) #show the result using matplotlib subplots plt.subplot(121) plt.imshow(cvt_orig) plt.title('Original Image') plt.xticks([]), plt.yticks([]) plt.subplot(122) plt.imshow(cvt_blur) plt.title('Bilateral Image') plt.xticks([]), plt.yticks([]) plt.show() cv2.waitKey(0) cv2.destroyAllWindows() |
For this lesson we are going to use this image, and we want to smooth this image using Bilateral method.
This is the syntax for Bilateral Filtering.
dst | It is the destination or output image |
d | A variable of the type integer representing the diameter of the pixel neighborhood. |
sigmacolor | A variable of the type integer representing the filter sigma in the color space. |
sigmaspace | A variable of the type integer representing the filter sigma in the coordinate space. |
Also you can use borderType if you want.
In here we are going to create our Bilateral Filtering.
1 |
bil_blur = cv2.bilateralFilter(image,13,75,75) |
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 |
cvt_orig = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cvt_blur = cv2.cvtColor(bil_blur, cv2.COLOR_BGR2RGB) |
Run the complete code and this is the result.