How to Remove Image Noise Using Gaussian Filters in Python
Computer Vision (Part 27)
📚Chapter: 3-Filtering
If you want to read more articles about Computer Vision, don’t forget to stay tuned because we reach end to end:) click here.
Introduction:
In the realm of digital image processing, noise is an unwanted interference that can degrade the quality of images and impede the effectiveness of subsequent processing tasks. Thankfully, there are various techniques available to mitigate noise, and one such powerful method is the Gaussian filter. In this blog post, we will delve into the concept of noise reduction using the Gaussian filter, exploring its principles, implementation, and practical applications.
Noise in digital images is more than just a nuisance — it can significantly affect the performance of your computer vision pipeline. Whether you're working with scanned documents, medical imagery, or photographs, reducing noise is often the first step in preprocessing.
In this tutorial, we'll take a close look at how to reduce noise using the Gaussian filter, a simple yet powerful image smoothing tool. You’ll learn how it works, how it differs from other filters, and how to implement it in both MATLAB and Python (OpenCV).
Sections
Understanding Noise in Images
Introducing the Gaussian Filter
Keeping the Two Gaussians Straight
Implementing Gaussian Filtering
Remove Noise with Python
Practical Applications
Conclusion
Section 1-🔍 What Is Noise in Images?
Before we embark on our journey to remove noise, let’s first understand what noise in images entails. Noise can manifest in various forms, including random variations in pixel values, distortions introduced during image acquisition or transmission, or imperfections arising from the imaging sensor itself. Common types of noise include Gaussian noise, salt-and-pepper noise, and speckle noise, each posing unique challenges to image processing algorithms.
Noise refers to random variations in pixel intensity that can distort image quality. It usually appears due to poor lighting, faulty sensors, or data transmission errors. Common types include:
Gaussian noise – Normally distributed, random intensity shifts.
Salt-and-pepper noise – Sudden white or black pixel bursts.
Speckle noise – Granular noise often seen in ultrasound and radar images.
Each type of noise presents a unique challenge, and Gaussian filtering is especially effective at handling Gaussian noise.
Section 2- 🌡️ Meet the Gaussian Filter
The Gaussian filter, named after the Gaussian distribution, it employs, is a widely used linear filter for image smoothing and noise reduction. Unlike other filters that apply a uniform weighting to neighboring pixels, the Gaussian filter assigns higher weights to nearby pixels and lower weights to those farther away, resembling the shape of a Gaussian bell curve. This characteristic enables the Gaussian filter to effectively blur an image while preserving important details.
A Gaussian filter uses the properties of the Gaussian distribution (a bell curve) to smooth an image. Instead of averaging all neighboring pixels equally, it gives more weight to closer pixels and less to those farther away.
This makes it ideal for blurring an image gently without completely losing details — perfect for noise reduction.
Key Features:
Preserves edges better than box filters.
Reduces high-frequency noise.
Parameterized by kernel size and sigma (standard deviation).
Section 3- ⚠️ Two Sigmas, Two Meanings
Finally, a word of warning or clarification at least. We just talked about sigma as being the width of a Gaussian, where that was the variance of the, of the smoo, smoothing of the blurring. Last time we talked about sigma or sigma squared as the variance of a noise function, how much noise was being added. So in one case, where we share might the filter, the sigma is in space, okay? Where as in the noise case it’s in an intensity or it’s in the value. The bigger the noise signal is, the more noise you added, the bigger the blurring filter sigma, the more you’re going to blur. So, you have to be an in a reasonable called sigma as they’re both using a normal distribution. But one is over a space, and one is over intensity.
We can show those two sigmas here, and by the way, here I’m using I’m using images that go from zero to one. Partially because that I know how sigma varies with respect to the range of the image, and partially because the slides that I stole off the Internet did this. All right? So in the top row, there’s no smoothing going on, so we have a sigma of 0.2 in the noise. That’s a lot of noise if the range is only going from 0 to 1 or, or let’s say minus 0.5 to 0.5. A sigma 0.1 is less noise. A sigma 0.05 is less noise yet. But then we can smooth it, all right, with a Gaussian. Right, this is the smoothing, with the Gaussian kernel. And the more we smooth, the blurrier these things get. And so, for the same amount of smoothing, the thing with the smaller amount of noise, with the same amount of smoothing becomes even smoother, right? So this image here is even smoother than that image there. Okay? But this is showing you those two sigmas, the two Gaussians. Almost always it’ll be clear from context, but since I’ve had situations where students say, wait a minute, I thought the bigger signal was, the more noise we got. Now you’re telling me the more sigma is, the more blurring is,the less noise we have, and I say yep, two sigmas.
Before we go further, here's an important clarification. You might hear "sigma" used in two different contexts:
Sigma for Noise: Determines how much noise is added. Higher sigma = more noise.
Sigma for Filter: Controls how much the image is blurred. Higher sigma = smoother image.
Both use the Gaussian distribution — but one relates to intensity variation, the other to spatial blurring.
Section 4- Implementing Gaussian Filtering:
Now, let’s walk through the steps involved in implementing Gaussian filtering to remove noise from an image. We’ll be using the popular OpenCV library in Python for this demonstration.
1- Remove Noise with Matlab
We discussed noise removal using a filter. Let’s test the effectiveness of that approach.
Step 1: Load the Image
We start by loading the image onto which we intend to apply the Gaussian filter. This could be an image obtained from a digital camera, a scanned photograph, or any other source.
Let’s load a perfectly good image.
# Remove noise with a Gaussian filter
%% Load an image
img=imread ('saturn.png')
imshow(img);
Step 2: Add Noise To simulate a noisy image,
we introduce artificial noise into the loaded image. This can be achieved by adding random variations to the pixel values, mimicking real-world noise sources such as sensor noise or transmission artifacts.
Spoil it by adding some noise. It would be wise to assign a name to this sigma to prevent any confusion in the future.
%% Add some noise
noise_sigma=25;
noise= randan(size(img)).*noise_sigma;
noisy_img=img+noise;
imshow(noisy_img);
Step 3: Create the Gaussian Filter
Next, we create a Gaussian filter using the cv2.getGaussianKernel() function provided by OpenCV. We specify the size of the filter (kernel size) and the standard deviation (sigma) to control the extent of blurring applied by the filter.
At last, we have understood the process of creating a Gaussian filter. We establish a size and a sigma.Then, the fspecial function from the image package can be utilized. Begin by loading the package.Then, proceed to create the filter.Now, this filter can be applied to eliminate noise. Note the order of parameters in imfilter. First is the image and second is the filter. Observe how the filter has created a smoother effect, or rather, blurred the image. The noise, which once had a fine, particle-like appearance, is now blurred.. But the filter has also affected the original image a great deal.
%% Create a Gaussian Filter
filter_size=11;
filter_sigma=2;
pkg load image;
filter = fspecial('gaussian',filter_size, filter_sigma);
Step 4: Apply the Filter
With the Gaussian filter in hand, we convolve it with the noisy image using the cv2.filter2D() function. This process involves sliding the filter over each pixel of the image and computing the weighted average of neighboring pixels according to the filter’s coefficients.
Indeed, noise removal is not magic. You do not receive precisely what you began with.. Visually, it may not appear very impressive., but image processing routines further down the road behave quite differently given a noisy image versus a smooth image. Go ahead and run this code yourself. Try out different parameters for noise generation and smoothing.
%% Apply it to remove noise
somoothed = imfilter(noisy_img, filter);
Step 5: Display the Result
Finally, we display the filtered image, which should exhibit reduced noise and smoother transitions between pixels compared to the original noisy image.
Section 5- Remove Noise with Python
import cv2
import numpy as np
# Load an image
img = cv2.imread("/content/drive/MyDrive/Courses /Data Science /Computer Vision /Theory /Introduction to Computer Vision/ 📚Chapter: 2-Image As Function /Image/frut.png")
# Add some noise
noise_sigma = 25
noise = np.random.randn(*img.shape) * noise_sigma
noisy_img = np.clip(img + noise, 0, 255).astype(np.uint8)
Show original Image.
import matplotlib.pyplot as plt
# Display noisy image
plt.imshow(img)
plt.title('orginal Image')
plt.axis('off') # Turn off axis
plt.show()
show Nosy image
import matplotlib.pyplot as plt
# Display noisy image
plt.imshow(noisy_img)
plt.title('Noisy Image')
plt.axis('off') # Turn off axis
plt.show()
# Display noisy image
import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.subplot(1, 2, 1), plt.imshow(img)
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(1, 2, 2), plt.imshow(noisy_img)
plt.title('noise image'), plt.xticks([]), plt.yticks([])
plt.show()
# Create a Gaussian Filter
filter_size = 11
filter_sigma = 2
filter = cv2.getGaussianKernel(filter_size, filter_sigma)
filter = filter * filter.T
# Apply it to remove noise
smoothed = cv2.filter2D(noisy_img, -1, filter)
import matplotlib.pyplot as plt
# Display noisy image
plt.imshow(smoothed)
plt.title('Sommoth Image')
plt.axis('off') # Turn off axis
plt.show()
Section 6-Practical Applications:
The Gaussian filter finds widespread use in various domains, including medical imaging, satellite imagery, digital photography, and computer vision. Some common applications of Gaussian filtering include denoising medical scans, enhancing satellite images, and preprocessing images for feature extraction and object recognition tasks.
🎯 Real-World Applications of Gaussian Filtering
Gaussian filters are everywhere in image processing and computer vision:
📸 Digital photography: Smoothing noisy photos before applying effects or enhancements.
🩺 Medical imaging: Reducing artifacts in MRI or CT scans.
🛰️ Satellite imagery: Enhancing Earth observation data before classification.
🤖 Computer vision: Preprocessing for edge detection, object detection, and segmentation.
Conclusion:
In conclusion, the Gaussian filter serves as a valuable tool in the arsenal of image processing techniques, offering an effective means of noise reduction and image smoothing. By understanding its principles and mastering its implementation, practitioners can significantly improve the quality and reliability of image processing pipelines in diverse fields. Whether you’re a researcher, a hobbyist, or a professional in the field, harnessing the power of Gaussian filtering can unlock new possibilities in image analysis and interpretation.
Gaussian filtering is one of the most important tools in image processing. It helps reduce unwanted noise, smooth out images, and prepare them for further analysis.
Understanding how sigma affects both noise and filtering gives you better control over preprocessing tasks.
📩 What’s Next?
Liked this tutorial?
👉 Subscribe to our newsletter for more Python + ML tutorials
👉 Follow our GitHub for code notebooks and projects
👉, Computer Vision: Enroll for Full Course to find notes, repository etc.
👉, Deep learning and Neural network: Enroll for Full Course to find notes, repository etc.
🎁 Access exclusive Supervise Leanring with sklearn bundles and premium guides on our Gumroad store: From sentiment analysis notebooks to fine-tuning transformers—download, learn, and implement faster.
💬 Drop a comment below if you have questions or want to share your results!
Source
1-Introduction of Computer Vision