CS117: Median Filters

Photographs are often a mess. Sometimes there's a a hair or a scratch on the negative when you print a photograph. Still photographs taken from television broadcasts or from worn video tapes are often filled with static. Even photos taken with digital cameras might show signs of scratches or smudges on the lens. There are many ways an image can accumulate pixels that show "noise" instead of the intended subject.

One way to eliminate some kinds of noise is a median filter. The idea behind a median filter is that most pixels are surrounded by pixels of the same or similar color. If one pixel has an unexpected color (white for a scratch on the lens or black for a hair on the negative, for example), the surrounding pixels are probably still okay. If we somehow let a pixel's neighbors vote on the pixel's proper color, we might be able to get rid of noisy pixels.

Here's one way to arrange such a vote. Start with a grayscale image. Cycle through all the pixels in the image with the usual double loop over the rows and columns of the image. For each pixel P:

The left image below is a gray version of a photograph of my family on the London Underground, with some artificial scratching added to it. Using the median filter described above, with radius-1 square neighborhoods, we get the image on the right. At the cost of a bit of blurring and flattening of the grays, we have nearly eliminated the severe damage of the diagonal scratches.

       

It's interesting to see that some images clean up better than others. In this scene from a spring break past, for example, the same median filter doesn't do nearly as good a job of fixing the problem (any ideas why?).

       

To apply the median filter idea to a color image, play the same voting game with the red, green, and blue values separately. For example: