[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Count pixels of different colors in C#

[Count pixels of different colors in C#]

The following CountPixels method counts 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 compares the pixel's returned value to the target color.

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 pixels that are black or white 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 also reasonably 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.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.