Median Filtering with Python and OpenCV

Actually, median filtering is good for more than just that.

It turns out that it does a pretty good job of preserving edges in an image.

Edge preservation is really important in computer vision, since edges are important for things like differentiating between a person and the background in a video, or defining lane boundaries for a self-driving car.

Since Gaussian blurring takes the average of the values around a pixel, after scanning through all pixels in the image, each one ends up as a blend of all the colors around it, and it will end up doing exactly what it’s name says: blur.

And as we know, blurry images don’t have sharp edges.

However, since median filtering uses, well… the median, the pixels on the edge of an object in an image end up as values that are already present in that section of the image.

Let’s check out an example:Sweet ride with some nice sharp edges to inspect.

This image has some really nice edges to work with.

If we zoom in, we can see a nice edge between the red and white of the car.

Now let’s apply both filters and compare them to see the difference in edge preservation.

Left: Median filter.

Right: Gaussian filter.

You can see the median filter leaves a nice, crisp divide between the red and white regions, whereas the Gaussian is a little more fuzzy.

The difference may not be as drastic as the example of the brain MRI with salt and pepper noise, but optimizing edge detection is an important concept for image processing and computer vision, even if the optimizations seem marginal.

That’s not to say, however, that Median filtering is the optimal solution for all edge detection endeavors.

In fact, in an upcoming article I’ll discuss the Canny edge detector, which is a popular, and quite powerful multi-stage algorithm that actually doesn’t use Median filtering.

TL;DR — OpenCV medianBlur()Median Filtering is very effective at eliminating salt and pepper noise, and preserving edges in an image after filtering out noise.

The implementation of median filtering is very straightforward.

Load the image, pass it through cv2.

medianBlur() and provide an odd(since there must be a center pixel), positive integer for the second argument, which represents the kernel size, or the size of the matrix that scans over the image.

A larger number will use a larger matrix, and take pixels from further away from the center, which may or may not help.

Whether you want a larger or smaller kernel really depends on the image, but 5 is a good number to start with.

The code, once again, in case you skipped it in the article.

Happy coding!.

. More details

Leave a Reply