GetPixel/SetPixel very very slow...


I'm using C# and the latest release of Visual Studio 2005.

I have written a small filter to modify an image that is being loaded by some picture boxes.  The filter works great except it takes about 30 to 40 seconds to run.  How can I speed this up

public void GreyFilter()

{

Color pixel;

int t;

for (int y = 0; y < mainImage.Height; y++)

{

for (int x = 0; x < mainImage.Width; x++)

{

pixel = mainImage.GetPixel(x, y);

t = (pixel.R + pixel.G + pixel.B) / 3;

mainImage.SetPixel(x, y, Color.FromArgb(t, t, t));

}

}

MessageBox.Show("done");

}



Answer this question

GetPixel/SetPixel very very slow...

  • shauli

  • vindos

    Are you familiar with C-style pointer arithmetic  If so, I suggest you lock the image (see Bitmap.LockBits) and perform this per-pixel modification directly on the RGB data in memory, using "unsafe" code and pointers. That's very fast in my experience.
  • darrellp

    Are you familiar with C-style pointer arithmetic  If so, I suggest you lock the image (see Bitmap.LockBits) and perform this per-pixel modification directly on the RGB data in memory, using "unsafe" code and pointers. That's very fast in my experience.






    Thank you.  Do you have an example

  • Keehan

    You may also want to consider using a ColorMatrix to modify the image as you draw it.

    See Bob Powells site for more info:
    http://www.bobpowell.net/grayscale.htm

  • Shinji


    You may also want to consider using a ColorMatrix to modify the image as you draw it.

    See Bob Powells site for more info:
    http://www.bobpowell.net/grayscale.htm


    Thank you.  I'll give this a try.


  • GetPixel/SetPixel very very slow...