The Median filter smooths images using a fast median algorithm. The median algorithm is particularly good at removing "salt and pepper" noise from images without removing too much fine detail.

The median filter replaces each pixel with the median of its neighbors. The Median has a number of advantages over the Mean. Firstly unrepresentative pixels do not unduly influence the outcome of the final pixel level - this is why the filter is good at removing "salt and pepper" noise. Secondly, because the final pixel must actually be the value of one of its neighbors, edges are preserved more faithfully.

Syntax

[C#]

static void Median(Bitmap bitmap, Size size, Point anchor);

[Visual Basic]

Shared Sub Median(bitmap As Bitmap, size As Size, anchor As Point)
Params
Name Description
bitmap The bitmap to process
size The size of the median filter to be applied.
anchor The horizontal center of the filter in pixels from top left.
Notes

None.

See Also

Despeckle

Example

[C#]

using (Bitmap bm = (Bitmap)Bitmap.FromFile(Server.MapPath("rez/sam-schooler-E9aetBe2w40-unsplash.jpg"))) {
  using (BitmapData data = bm.LockBits(ImageLockMode.ReadWrite, bm.Bounds, bm.PixelFormat)) {
    var rnd = new Random(42);
    for (int i = 0; i < 1000; i++) {
      Point p = new Point(rnd.Next(bm.Width), rnd.Next(bm.Height));
      data.SetPixel(p.X, p.Y, i % 2 == 0 ? Color.White : Color.Black);
    }
  }
  bm.Save(Server.MapPath("IG8_Effects_Median1.jpg"));
  Effects.Median(bm, new Size(3, 3), new Point(1, 1));
  bm.Save(Server.MapPath("IG8_Effects_Median2.jpg"));
}


Here we apply a despeckle effect with different threshold levels. First we apply some salt and pepper to our image, then we try and remove it. Ouput files are shown below.


jeremy-bishop-_CFv3bntQlQ-unsplash.jpg


IG8_Effects_Median1.jpg


IG8_Effects_Median2.jpg