📸 How to Apply Gaussian Filtering in Python (and MATLAB)
Computer Vision (Part 26)
📚Chapter: 3-Filtering
Sections
Filter in Matlab and Python
Smoothing with a Gaussian
🧠 Introduction: Why Filtering Matters in Computer Vision
In computer vision, filtering is a core concept—whether you're trying to smooth out noise, detect edges, or prepare your images for feature extraction. One of the most widely used filters is the Gaussian filter, which is great for reducing image noise and blurring details in a controlled way.
While MATLAB makes this easy with built-in functions, Python also offers powerful libraries like OpenCV
, scipy
, and matplotlib
for similar tasks.
In this guide, we’ll explore how to apply Gaussian filtering using both MATLAB and Python, and break it down for learners new to image processing.
🧪 What is a Gaussian Filter?
A Gaussian filter is a type of low-pass filter that smooths images by averaging pixel values using weights that follow a Gaussian distribution (i.e., a bell curve). It depends on two parameters:
Kernel size: The width and height of the filter matrix
Sigma (σ): Controls the amount of smoothing. Higher sigma = more blur
As I mentioned at the start of this class, I’ll be showing my examples mostly using Matlab. I know we’ve looked at the course developer. Arpin has worked on being able to do it in Octave or also in Python using various image manipulation OpenCV.But what I’m going to do is show you filtering in Matlab. And basically Matlab makes it trivial to build filters and apply filters.
🛠️ Filtering in MATLAB (For Reference)
In MATLAB, applying a Gaussian filter is super straightforward thanks to fspecial
. Here's a high-level breakdown:
hsize = [31 31]; % Kernel size (odd dimensions preferred)
sigma = 5; % Smoothing factor
h = fspecial('gaussian', hsize, sigma); % Create Gaussian filter
imshow(imfilter(panda_image, h)); % Apply and display the filtered image
The function fspecial
creates the filter, and imfilter
applies it. You can even use surf(h)
to visualize the filter in 3D.
So Matlab, what we’re going to do is define two things. We’re going to define the size of the kernel. Remember that’s what we were talking about before. So in this case it’s going to be a 31 by 31. Again, odd, so I can put a center pixel down. I’m going to a sigma of five, and Matlab has this really great little function called fspecial. And obviously it’s special, or they would call it something else. In fspecial, you can give it parameters, one of which is the type of filter you’d like. You can give it the size and the sigma. You can also give it rectangular size and multiple sigmas. It will build these filters for you. And in fact, Matlab has this beautiful little function called surf. Right, which will plot for you as a surface and if you do it with the right color map you would see this. You could also show it as an image. That’s what this little picture is right here, all right? But even more importantly, you can take your image, and that’s our image here of a panda, I can filter it by this h, which was the filter we just built, and then I can show that. What’s that going to look like? It’s going to be a blurry panda. Okay. This code is all it takes to build your filters and apply them to images in Matlab. It makes it very easy.
🐍 Gaussian Filtering in Python: Step-by-Step
Python example 1
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
from scipy.signal import convolve2d
hsize = 31
sigma = 5
# Create Gaussian kernel
h = np.outer(signal.gaussian(hsize, std=sigma), signal.gaussian(hsize, std=sigma))
# Display 3D surface plot of the kernel
fig = plt.figure()
ax = fig.add_subplot(121, projection='3d')
ax.plot_surface(np.arange(hsize), np.arange(hsize), h, cmap='viridis')
ax.set_title('3D Surface Plot of Gaussian Kernel')
# Display 2D image plot of the kernel
plt.subplot(122)
plt.imshow(h, cmap='viridis')
plt.title('2D Image Plot of Gaussian Kernel')
plt.colorbar()
plt.show()
# Assuming 'im' is your input image
# Apply Gaussian filter to the input image
outim = gaussian_filter(im, sigma)
# Display the filtered image
plt.imshow(outim, cmap='gray')
plt.title('Filtered Image')
plt.colorbar()
plt.show()
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the input image (assuming 'im' is your input image)
im = cv2.imread('input_image.jpg', cv2.IMREAD_GRAYSCALE)
# Define the size and sigma value for the Gaussian kernel
hsize = 31
sigma = 5
# Create the Gaussian kernel using OpenCV
h = cv2.getGaussianKernel(hsize, sigma)
# Apply Gaussian blur to the input image
outim = cv2.filter2D(im, -1, h)
# Display the filtered image
plt.imshow(outim, cmap='gray')
plt.colorbar()
plt.show()
📷 Example 1: Using SciPy and Matplotlib
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
from scipy.ndimage import gaussian_filter
# Define filter parameters
hsize = 31
sigma = 5
# Create a 2D Gaussian kernel
h = np.outer(signal.gaussian(hsize, std=sigma), signal.gaussian(hsize, std=sigma))
# Plot the 3D surface and 2D heatmap
fig = plt.figure(figsize=(12, 5))
# 3D Surface Plot
ax = fig.add_subplot(121, projection='3d')
X, Y = np.meshgrid(np.arange(hsize), np.arange(hsize))
ax.plot_surface(X, Y, h, cmap='viridis')
ax.set_title('3D Gaussian Kernel')
# 2D Image Plot
plt.subplot(122)
plt.imshow(h, cmap='viridis')
plt.title('2D Gaussian Kernel')
plt.colorbar()
plt.tight_layout()
plt.show()
📷 Example 2: Apply Gaussian Filter to an Image
from scipy.ndimage import gaussian_filter
import imageio.v2 as imageio # Replace with cv2 if needed
# Load a grayscale image
im = imageio.imread('panda.jpg', pilmode='L')
# Apply Gaussian blur
blurred = gaussian_filter(im, sigma=5)
# Show result
plt.imshow(blurred, cmap='gray')
plt.title('Blurred Image (σ = 5)')
plt.axis('off')
plt.show()
🧊 Example 3: Using OpenCV for Gaussian Filtering
import cv2
import matplotlib.pyplot as plt
# Load image in grayscale
im = cv2.imread('panda.jpg', cv2.IMREAD_GRAYSCALE)
# Apply Gaussian blur using OpenCV
blurred = cv2.GaussianBlur(im, (31, 31), sigmaX=5)
# Show the result
plt.imshow(blurred, cmap='gray')
plt.title('Gaussian Blurred Image (OpenCV)')
plt.axis('off')
plt.show()
🔍 What Happens When You Change Sigma?
Let’s compare what happens when we change the sigma
value:
sigmas = [1, 3, 10]
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
for i, s in enumerate(sigmas):
blurred = gaussian_filter(im, sigma=s)
axes[i].imshow(blurred, cmap='gray')
axes[i].set_title(f'σ = {s}')
axes[i].axis('off')
plt.tight_layout()
plt.show()
What you’ll notice:
Small σ → barely any blur
Large σ → heavy smoothing
Perfect for noise removal, but be cautious: too much blur can erase important image details.
Section 2- Smoothing with a Gaussian
Again, depending upon the size of the sigma we get different amounts of smoothing. So here we’re using three different sigmas of 1, 3, and 10. We build our Gaussians using the different sized sigmas. We filter them and show them, and you see that we get, you know, hardly any blurring, little more blurring, and a little more blurring. That’s all it takes to build these filters in Matlab.
✅ Final Thoughts
Filtering is fundamental in computer vision, and Gaussian filters are a great place to start. Whether you’re using MATLAB or Python, the process is relatively straightforward—and highly customizable.
Understanding how kernel size and sigma affect the output gives you more control when cleaning up or prepping your image data for more complex tasks like edge detection or feature extraction.
📩 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