find a color in an image in c#

Randster picture Randster · Sep 25, 2010 · Viewed 28.4k times · Source

I stumbled across this youtube video here http://www.youtube.com/watch?v=Ha5LficiSJM that demonstrates someone doing color detection using the AForge.NET framework. I'd like to duplicate what that author has done but I'm not sure how to do some image processing.

It would appear that the AForge.NET framework allows you to pull down from the video source the image in a Bitmap format. My questions is could anyone point me in the direction or provide some guidance on how to interrogate a Bitmap object to find specific colors in it? (for example - if there is 'Red' or 'Purple' in the image for X seconds, I'd like to raise an event 'ColorDetected' or so...)

Does anyone have any suggestions on where to start?

Thanks,

-R.

EDIT: Would I need to walk the entire Bitmap object and interrogate each pixel for the color? Like so: http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.getpixel.aspx

Answer

Ed S. picture Ed S. · Sep 25, 2010

Well, you can always use the GDI+ method.

Bitmap b = new Bitmap( "some path" );
Color x = b.GetPixel( x, y );

However, GetPixel is actually pretty slow. Try it that way first, but if you need to scan many relatively large images it may not work for you. In that case, use LockBits to get a pointer to a contiguous memory chunk. You can then loop through the image quickly, but you have to know how to manipulate pointers, though it's not terribly complicated.

EDIT: Using LockBits to look at each pixel:

Bitmap b = new Bitmap( "some path" );
BitmapData data = b.LockBits( new Rectangle( 0, 0, b.Width, b.Height ),
ImageLockMode.ReadOnly, b.PixelFormat );  // make sure you check the pixel format as you will be looking directly at memory

unsafe
{         
    // example assumes 24bpp image.  You need to verify your pixel depth
    // loop by row for better data locality
    for( int y = 0; y < data.Height; ++y )
    {
        byte* pRow = (byte*)data.Scan0 + y * data.Stride;
        for( int x = 0; x < data.Width; ++x )
        {
            // windows stores images in BGR pixel order
            byte r = pRow[2];
            byte g = pRow[1];
            byte b = pRow[0];

            // next pixel in the row
            pRow += 3;
        }
    }
}

b.UnlockBits(data);

If your images are padded at the end you can use the BitmapData.Stride property to get to the start of each new row (otherwise you will be reading some junk and your offsets will be screwy).