How can I read total number of the pixels in foreground and background of my image in C#?

StackOverflow https://stackoverflow.com/questions/21385114

  •  03-10-2022
  •  | 
  •  

Question

Basically I have written a code that creates image of a character (randomly generated). I have a problem how to scan the image line by line and read the total number of the foreground (text) and background (white) pixels in my bmp image and display the results to the user. here is part of my code:

Image bmp = new Bitmap(100, 100);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
g.DrawString(randomString, myFont, new SolidBrush(Color.Black), new PointF(0, 0));
pictureBox1.Image = bmp;
bmp.Save(@"CAPTCHA.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
Was it helpful?

Solution

The basic idea is simple - iterate over all the pixels in the bitmap, and if the pixel is white, increment your background pixel counter. After you're done, you can simply get the total amount of pixels (width * height) and do whatever you want with the background pixel counter value.

A simple (and very slow) code snippet that does this:

var backgroundPixels = 0;

for (int x = 0; x < bmp.Width; x++)
  for (int y = 0; y < bmp.Height; y++)
    if (bmp.GetPixel(x, y) == Color.White)
      backgroundPixels++;

The notion of foreground and background is only there in your head. The resulting bitmap only has an array of pixels, each with a position and colour. You can assign a specific meaning to some color (white in your case) and say that it means the background - but that's it.

A good alternative would be to use a transparent bitmap, where there indeed is a special meaning for what you call background - transparency. In that case, apart from the colour, the pixel also has a notion of the degree of transparency (Color.A), which you can exploit. In that case, you'd do g.Clear(Color.Transparent); instead of using white, and when iterating over the pixels, you'd check if bmp.GetPixel(x, y).A > 0 or whatever threshold you'd have for saying "this is the background". When you want to add the actual background colour, you'd paint this bitmap over a bitmap that's completely white and save that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top