BLOG.CSHARPHELPER.COM: Count the black and white pixels in an image in C#
Count the black and white pixels in an image in C#
The following CountPixels method returns the number of pixels in an image that match a target color.
// Return the number of matching pixels.
private int CountPixels(Bitmap bm, Color target_color)
{
// Loop through the pixels.
int matches = 0;
for (int y = 0; y < bm.Height; y++)
{
for (int x = 0; x < bm.Width; x++)
{
if (bm.GetPixel(x, y) == target_color) matches++;
}
}
return matches;
}
This code is reasonably straightforward. It loops through the pixels calling the GetPixels method to get each pixel's color. It then
The only strangeness here is that the Color class's Equals method, which is used by == to determine equality, treats named colors differently from those obtained in other ways, including colors obtained with the GetPixel method. That means this method won't work if you pass it a named color such as Color.Black. If you used such a color, the method would find no matching pixels.
The following code shows how this program uses the CountPixels method to count the black and white pixels in the image.
// Count the black and white pixels.
private void btnCount_Click(object sender, EventArgs e)
{
Bitmap bm = new Bitmap(picImage.Image);
int black_pixels = CountPixels(bm, Color.FromArgb(255, 0, 0, 0));
int white_pixels = CountPixels(bm, Color.FromArgb(255, 255, 255, 255));
lblBlack.Text = black_pixels + " black pixels";
lblWhite.Text = white_pixels + " white pixels";
lblTotal.Text = white_pixels + black_pixels + " total pixels";
}
The code is mostly straightforward. The only thing to note is that it uses the colors returned by Color.FromArgb(255, 0, 0, 0) and Color.FromArgb(255, 255, 255, 255) instead of the named colors Color.Black and Color.White.
5/22/2012 5:24 PM
Juiced5 wrote: Big thanks for the post!!!
Sorry for noobish question, but how I can add browsing for custom images for processing???
Could You Help me??? Reply to this
- Add a OpenFileDialog to the form.
- Add something to let the user tell the program to open a file. For example, add a button or a File > Open menu item.
- When the user wants to open a file, call the OpenFileDialog's ShowDialog method. If ShowDialog returns OK, then open the file given by the dialog's FileName property.
Big thanks for the post!!!
Sorry for noobish question, but how I can add browsing for custom images for processing???
Could You Help me???
Reply to this
Lots of other posts show how to do this. The steps are:
- Add a OpenFileDialog to the form.
- Add something to let the user tell the program to open a file. For example, add a button or a File > Open menu item.
- When the user wants to open a file, call the OpenFileDialog's ShowDialog method. If ShowDialog returns OK, then open the file given by the dialog's FileName property.
For example, see today's post Pixellate parts of an image in C#. It lets you open (save save) an image file.
Reply to this