How to Apply Low Pass Filter to Image for Smoothing
To apply a
low pass filter to an image, you typically use a smoothing technique like a Gaussian blur or averaging filter that removes high-frequency details. In Python, libraries like OpenCV or scipy.ndimage provide functions such as cv2.GaussianBlur() to apply this filter easily.Syntax
The common syntax to apply a low pass filter using OpenCV's Gaussian blur is:
cv2.GaussianBlur(src, ksize, sigmaX)
src: Input image.ksize: Kernel size (width, height), must be positive and odd.sigmaX: Gaussian kernel standard deviation in X direction.
This smooths the image by averaging pixel values weighted by a Gaussian function, reducing sharp edges and noise.
python
import cv2 # Apply Gaussian blur blurred_image = cv2.GaussianBlur(src=image, ksize=(5,5), sigmaX=0)
Example
This example loads an image, applies a Gaussian low pass filter, and shows the original and filtered images side by side.
python
import cv2 import numpy as np from matplotlib import pyplot as plt # Load image in grayscale image = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE) # Apply Gaussian blur (low pass filter) blurred = cv2.GaussianBlur(image, (7,7), sigmaX=1.5) # Plot original and blurred images plt.subplot(1,2,1) plt.title('Original Image') plt.imshow(image, cmap='gray') plt.axis('off') plt.subplot(1,2,2) plt.title('Low Pass Filtered Image') plt.imshow(blurred, cmap='gray') plt.axis('off') plt.show()
Output
A window showing two images side by side: the original grayscale image and the smoothed image with reduced noise and details.
Common Pitfalls
- Using an even kernel size for Gaussian blur will cause an error; always use odd numbers like (3,3), (5,5).
- Setting
sigmaXto 0 lets OpenCV calculate it automatically, but setting it too high can over-blur the image. - Applying a low pass filter to a color image requires handling each channel or converting to grayscale first.
- Not normalizing or converting image data types can cause unexpected results.
python
import cv2 # Wrong: even kernel size causes error # blurred = cv2.GaussianBlur(image, (4,4), 0) # This will fail # Right: odd kernel size blurred = cv2.GaussianBlur(image, (5,5), 0)
Quick Reference
| Parameter | Description | Example Values |
|---|---|---|
| src | Input image to filter | Grayscale or color image array |
| ksize | Kernel size (width, height), odd integers | (3,3), (5,5), (7,7) |
| sigmaX | Gaussian kernel standard deviation in X | 0 (auto), 1.0, 1.5 |
| Output | Filtered image with reduced high-frequency details | Smoothed image array |
Key Takeaways
Use Gaussian blur with an odd-sized kernel to apply a low pass filter to images.
Low pass filters smooth images by reducing sharp edges and noise.
Set sigmaX carefully to control the amount of smoothing.
Always check image type and channels before filtering.
Visualize results to confirm the filter effect.