Noise Reduction of an Image in C# using Median Filters
One of the main issues when trying to do image processing is the simple fact that images usually contain some degree of noise. This noise can in turn cause issues. For instance if you
Unfortunately in C# there is no built in function to do this (or at least none that I
1: public static Bitmap MedianFilter(Bitmap Image, int Size)
2: {
3: System.Drawing.Bitmap TempBitmap = Image;
4: System.Drawing.Bitmap NewBitmap = new System.Drawing.Bitmap(TempBitmap.Width, TempBitmap.Height);
5: System.Drawing.Graphics NewGraphics = System.Drawing.Graphics.FromImage(NewBitmap);
6: NewGraphics.DrawImage(TempBitmap, new System.Drawing.Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), new System.Drawing.Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), System.Drawing.GraphicsUnit.Pixel);
7: NewGraphics.Dispose();
8: Random TempRandom = new Random();
9: int ApetureMin = -(Size / 2);
10: int ApetureMax = (Size / 2);
11: for (int x = 0; x < NewBitmap.Width; ++x)
12: {
13: for (int y = 0; y < NewBitmap.Height; ++y)
14: {
15: List<int> RValues = new List<int>();
16: List<int> GValues = new List<int>();
17: List<int> BValues = new List<int>();
18: for (int x2 = ApetureMin; x2 < ApetureMax; ++x2)
19: {
20: int TempX = x + x2;
21: if (TempX >= 0 && TempX < NewBitmap.Width)
22: {
23: for (int y2 = ApetureMin; y2 < ApetureMax; ++y2)
24: {
25: int TempY = y + y2;
26: if (TempY >= 0 && TempY < NewBitmap.Height)
27: {
28: Color TempColor = TempBitmap.GetPixel(TempX, TempY);
29: RValues.Add(TempColor.R);
30: GValues.Add(TempColor.G);
31: BValues.Add(TempColor.B);
32: }
33: }
34: }
35: }
36: RValues.Sort();
37: GValues.Sort();
38: BValues.Sort();
39: Color MedianPixel = Color.FromArgb(RValues[RValues.Count / 2],
40: GValues[GValues.Count / 2],
41: BValues[BValues.Count / 2]);
42: NewBitmap.SetPixel(x, y, MedianPixel);
43: }
44: }
45: return NewBitmap;
46: }