Sub topic 4
Smoothing with box, Gaussian, median and bilateral filters
Smoothing replaces each pixel with a value computed from its neighbors. This lowers noise and fine texture, and it blurs detail as a side effect. OpenCV has four standard smoothing functions, and they differ in how they weigh neighbors and in how much they blur edges.
This chapter assumes you can load a grayscale image as a NumPy uint8 array and that you know what cv2.filter2D does with a kernel. It also assumes you know the border modes from the previous chapter. Choosing a filter for a specific noise type comes in the next chapter. Here we focus on how each filter works and how to call it correctly.
The setup
All examples use the same grayscale image.
import cv2
import numpy as np
img = cv2.imread("input.jpg")
if img is None:
raise FileNotFoundError("input.jpg could not be read")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
kernel = np.ones((5, 5), np.float32) / 25.0
manual_box = cv2.filter2D(gray, -1, kernel)
box = cv2.blur(gray, (5, 5))
gauss = cv2.GaussianBlur(gray, (5, 5), 0)
median = cv2.medianBlur(gray, 5)
bilateral = cv2.bilateralFilter(gray, 9, 75, 75)
print(np.array_equal(manual_box, box)) # expected: True or nearly somanual_box and box compute the same average. The only differences come from how each function rounds back to uint8, so a few pixels can differ by one gray level. cv2.blur is the faster, purpose-built version.
Linear and nonlinear filters
The first two filters are linear. Each output pixel is a weighted sum of its neighborhood, and the weights come from a kernel. You could write either one with filter2D.
The median and bilateral filters are nonlinear. No single kernel describes them, because the result depends on the pixel values themselves. You cannot reproduce them with filter2D.
Box filter
cv2.blur(src, ksize) gives every neighbor in the window the same weight, 1/(w·h). It is the simplest and fastest smoother, and its cost does not grow with kernel size because OpenCV uses running sums.
The equal weights have a cost. A box kernel has sharp edges, so a pixel just inside the window counts fully and a pixel just outside counts for nothing. This produces blocky, uneven blur and can leave faint ringing artifacts around strong edges. Use it when speed matters more than quality, or as a quick baseline.
Gaussian filter
cv2.GaussianBlur(src, ksize, sigmaX, sigmaY=0) weights neighbors by a bell curve, so the center pixel counts most and the weights fall off smoothly with distance. The result looks more natural than a box blur and is the standard pre-filter before gradients and Canny.
Two parameters control the blur, ksize and sigma, and they interact.
ksizemust be odd and positive, such as(5, 5).- If
sigmaXis 0, OpenCV derives it fromksizeusingsigma = 0.3 * ((ksize - 1) * 0.5 - 1) + 0.8. Forksize=5this gives 1.1. - If you pass
ksize=(0, 0)and a positive sigma, OpenCV derives the kernel size from sigma. This is usually the cleanest way to ask for "blur by this much", and the unsharp masking example uses it. - If
sigmaYis 0, it is set equal tosigmaX.
The Gaussian kernel is separable. A 2D Gaussian equals a 1D Gaussian applied along the rows and then along the columns, so the cost per pixel grows with k instead of k². You can check this with the 1D kernel and cv2.sepFilter2D.
k = cv2.getGaussianKernel(5, 0).ravel()
print(k) # [0.0625 0.25 0.375 0.25 0.0625]
sep = cv2.sepFilter2D(gray, -1, k, k)
diff = cv2.absdiff(sep, gauss)
print(diff.max()) # tiny: only rounding differencesWhen a sigma of 0 is used with a small kernel size (1, 3, 5 or 7), OpenCV uses a fixed kernel. For size 5 this is the binomial kernel 1-4-6-4-1 divided by 16.
Median filter
cv2.medianBlur(src, ksize) sorts the values in the window and outputs the middle one. ksize is a single odd integer greater than 1, not a tuple.
Because the output is always one of the values already in the window, a single extreme pixel cannot pull the result toward it. A white speck inside a dark region simply disappears. An averaging filter would smear the speck into a gray blotch. The median also keeps straight edges sharper than a Gaussian of similar strength, though it rounds off corners and removes thin lines narrower than about half the window.
There is one dtype restriction. For ksize 3 or 5, OpenCV accepts uint8, uint16 and float32. For larger kernels, only uint8 works, so convert before calling it on other types.
Bilateral filter
cv2.bilateralFilter(src, d, sigmaColor, sigmaSpace) multiplies two weights for each neighbor.
- A spatial weight, a Gaussian of the distance from the center, controlled by
sigmaSpace. - A range weight, a Gaussian of the intensity difference from the center pixel, controlled by
sigmaColor.
A neighbor on the other side of an edge has a very different intensity, so its range weight is near zero and it barely contributes. Flat regions get smoothed, and edges survive. This is "edge-preserving smoothing".
| Parameter | Meaning | Practical note |
|---|---|---|
| `d` | Neighborhood diameter in pixels | `d` above 5 is slow for real-time use. If `d <= 0`, OpenCV computes it from `sigmaSpace`. |
| `sigmaColor` | How different two intensities can be and still mix | Larger values blur across weaker edges. |
| `sigmaSpace` | How far apart pixels can be and still mix | Matters only when `d <= 0`, since a positive `d` fixes the window. |
Typical starting values are d=9 and both sigmas between 50 and 100. OpenCV's guidance is that sigmas below about 10 have almost no effect, and sigmas above about 150 give a cartoon-like look.
The bilateral filter is much slower than the others, because it recomputes the range weights for every pixel. It takes only 8-bit or float images with 1 or 3 channels, and it cannot run in place, so always assign the result to a new array.
Comparing the results
Run all four on the same image and compare. The kernel values are the same size, but the effects differ.
results = {
"original": gray,
"box": box,
"gaussian": gauss,
"median": median,
"bilateral": bilateral,
}
for name, im in results.items():
lap = cv2.Laplacian(im, cv2.CV_64F).var()
print(f"{name:10s} sharpness (Laplacian variance): {lap:8.1f}")The variance of the Laplacian is a rough sharpness measure. Higher means more fine detail, including noise. Expect box and Gaussian to drop it the most. The bilateral filter keeps more of it because edges stay intact. Use this only for comparison between filters on one image, since the absolute number depends on the image content.
Common mistakes
- Even kernel sizes.
cv2.bluraccepts them, butGaussianBlurandmedianBlurrequire odd sizes. An even window also has no center pixel, so avoid it everywhere. - Passing a tuple to
medianBlur. It takes one integer. - Scaling the kernel instead of sigma. Doubling
ksizeon a Gaussian with a fixed sigma changes little once the kernel is wider than about 6σ. Change sigma to control blur strength. - Over-smoothing before edge detection. A large blur removes the noise and the weak edges together. Start small, such as 5×5.
- Using the bilateral filter on large images in a loop. Time it first. Reduce
dor downscale the image if it is too slow. - Filtering each color channel by accident. All four functions accept a BGR image and filter each channel on its own. For median and bilateral filtering this is fine. If you need the filter to respond to color differences jointly, convert to a different color space first.
Choosing at a glance
| Filter | Weights come from | Speed | Edge behavior |
|---|---|---|---|
| Box | Equal weights | Fastest | Blurs edges, can leave artifacts |
| Gaussian | Distance only | Fast | Blurs edges smoothly |
| Median | Rank order of values | Moderate | Keeps edges, removes outliers |
| Bilateral | Distance and intensity | Slowest | Preserves strong edges |
Exercise
You call cv2.GaussianBlur(gray, (0, 0), 3). What kernel size does OpenCV use, and which argument controls how strong the blur is? Then explain why cv2.medianBlur(gray, (5, 5)) raises an error.
Show answer
With ksize=(0, 0) and a positive sigma, OpenCV computes the kernel size from sigma (roughly 6σ+1, rounded to an odd number, so 19 for σ=3), and sigma alone sets the blur strength. medianBlur takes a single odd integer for its aperture size, so the tuple (5, 5) is an invalid argument. The correct call is cv2.medianBlur(gray, 5).
Exercise
A bilateral filter is called with sigmaColor=10 on an image where an object edge differs by 80 gray levels from its background. Will the filter blur across that edge? What would you change to make it blur across the edge?
Show answer
No. An 80-level difference is far larger than sigmaColor=10, so the range weight across the edge is close to zero and the two sides do not mix. Raising sigmaColor to around 80 or more lets pixels across the edge contribute, which makes the filter behave more like a Gaussian.