Find a color's pixel coordinates

Pugmatt picture Pugmatt · May 8, 2012 · Viewed 7.4k times · Source

I am making a program in Visual Studio C# that can detect a color, then find the x, y coordinate of that pixel with that color. I have done research, but all I can find is you already give the coordinate, and it senses the color, that's not what I want though, I want to give the color, and it finds the coordinate. Anyone know how to do this? Thanks

Answer

kevin628 picture kevin628 · May 8, 2012

You can feed the image to a Bitmap object and then call the getPixel(x, y) method to get a pixel at a specific point. Since a Bitmap object has the dimensions of the image, you can iterate over every pixel (YIKES!), testing for a match with desired color. getPixel() returns a Color object, which you can work with. Here's something I worked up super fast. pictureBox1 is a PictureBox element on my form.

Bitmap b = new Bitmap(pictureBox1.Image);
Color c = b.GetPixel(0,0);

Remember, though, that the search for the matching pixel is worse case O(n) where n is the number of pixels in the image. For small and maybe medium-sized pictures this isn't too bad, but for huge images, you might notice your program hang.