title: 3X3 Median Filtering in c# but not working?
body: <p>Really I'm trying to apply 3X3 Median Filtering by C# and depending on my understanding the concepts of Median Filtering I wrote the following code but when I'm running it the Form hangs. I think have some problem in the last nested for loop but i don't know where is the error or the wrong in applying the Median concepts! </p>
  
  <pre><code>public static Bitmap MedianFiltering(Bitmap bm)
      {
          List&lt;int&gt; termsList = new List&lt;int&gt;();
          Bitmap res, temp;
          Color c;
          int counter = 0;
  
          //Convert to Grayscale 
          for (int i = 0; i &lt; bm.Width; i++)
          {
              for (int j = 0; j &lt; bm.Height; j++)
              {
                  c = bm.GetPixel(i, j);
                  byte gray = (byte)(.333 * c.R + .333 * c.G + .333 * c.B);
                  bm.SetPixel(i, j, Color.FromArgb(gray, gray, gray));
              }
          }
  
          temp = bm;
  
         //applying Median Filtering 
          for (int i = 0; i &lt;= temp.Width - 3; i++)
              for (int j = 0; j &lt;= temp.Height - 3; j++)
              {
                  for (int x = i; x &lt;= i + 2; x++)
                      for (int y = j; y &lt;= j + 2; y++)
                      {
  
                          c = temp.GetPixel(x, y);
                          termsList.Add(c.R);
                          counter++;
                      }
                  int[] terms = termsList.ToArray();
                  Array.Sort&lt;int&gt;(terms);
                  Array.Reverse(terms);
                  int color = terms[4];
                  temp.SetPixel(i + 1, j + 1, Color.FromArgb(color, color, color));
                  counter = 0;
              }
          res = temp;
  
          return res;
      }
  </code></pre>
  
  <p>Thanks.</p>