title: Image processing task: Erosion C#
body: <p>I am doing an image processing assignment where I want to implement erosion and dilation algorithm. It needs to look for each pixel in all directions (in this case up, down, left and right), so i'm using a plus structuring element. Here is my problem: I've got 4 for loops nested, which makes this operation very slow.
  Can anyone tell me how to make the erosion process quicker without using unsafe method?
  Here is what I have:</p>
  
  <pre><code>        colorlistErosion = new List&lt;Color&gt;();
          int colorValueR, colorValueG, colorValueB;
          int tel = 0;
  
          for (int y = 0; y &lt; bitmap.Height; y++)
          {
              for (int x = 0; x &lt; bitmap.Width; x++)
              {
                  Color col = bitmap.GetPixel(x, y);
                  colorValueR = col.R; colorValueG = col.G; colorValueB = col.B;
                  //Erosion
                  for (int a = -1; a &lt; 2; a++)
                  {
                      for (int b = -1; b &lt; 2; b++)
                      {
                          try
                          {
                              Color col2 = bitmap.GetPixel(x + a, y + b);
                              colorValueR = Math.Min(colorValueR, col2.R);
                              colorValueG = Math.Min(colorValueG, col2.G);
                              colorValueB = Math.Min(colorValueB, col2.B);
                          }
                          catch
                          {
                          }
                      }
                  }
                  colorlistErosion.Add(Color.FromArgb(0 + colorValueR, 0+colorValueG, 0+colorValueB));
              }
          }
          for (int een = 0; een &lt; bitmap.Height; een++)
              for (int twee = 0; twee &lt; bitmap.Width; twee++)
              {
                  bitmap.SetPixel(twee, een, colorlistErosion[tel]);
                  tel++;
              }
  </code></pre>