Get total number of the black and white pixels in bitmap image separately
bitmap, c#, image
Solution
When you use `==` or `Equals` you are not comparing the value of ARGB byte by byte because the '==' operator is done like this
public static bool operator ==(Color left, Color right)
{
if (left.value != right.value || (int) left.state != (int) right.state || (int) left.knownColor != (int) right.knownColor)
return false;
if (left.name == right.name)
return true;
if (left.name == null || right.name == null)
return false;
else
return left.name.Equals(right.name);
}
following is how is done the `Equals` Method in .net
public override bool Equals(object obj)
{
if (obj is Color)
{
Color color = (Color) obj;
if (this.value == color.value && (int) this.state == (int) color.state && (int) this.knownColor == (int) color.knownColor)
{
if (this.name == color.name)
return true;
if (this.name == null || color.name == null)
return false;
else
return this.name.Equals(this.name);
}
}
return false;
}
to overcome your issue you should convert to ARGB using the `ToArgb()` function which send 32-bit of the current color
private void button1_Click(object sender, EventArgs e)
{
int whiteColor = 0;
int blackColor = 0;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
Color color = bmp.GetPixel(x, y);
if (color.ToArgb()==Color.White.ToArgb())
{
whiteColor++;
}
else
if (color.ToArgb() == Color.White.ToArgb())
{
blackColor++;
}
}
}
}
Problem
I am trying to write a code that goes through my image and counts all the pixels line by line and tells me how many white and how many black pixels are in my image? (Assuming my image is made of a black character against white background) ``` var backgroundPixels = 0; for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { if (bmp.GetPixel(x, y).Equals(Color.White)) { backgroundPixels++; } } } label3.Text = Convert.ToString(backgroundPixels); ``` I am having problem as the code doesn’t work for some reason. Can anyone help me please?