Shashank Jain
Shashank Jain

Reputation: 857

Cannot draw an image using this program?

I am trying to process an image for finding out red color regions in it. I scan pixels and if they are found to be ENOUGH red, they are converted to black, otherwise white.

To speed up the process, I skip certain pixels, and need to draw blocks of black or white at their place. I am using this function but it seems to be wrong somewhere. The image I get in the end is completely blank.

    public void ProcessFrame( ref Bitmap image )
    {
        int skip = 10;
        Graphics g = Graphics.FromImage(System.Drawing.Image.FromHbitmap(image.GetHbitmap()));
        SolidBrush black = new SolidBrush(Color.Black);
        SolidBrush white = new SolidBrush(Color.White);
        for (int i = 0; i < image.Width; i=i+skip)
        {
            for (int j = 0; j < image.Height; j = j + skip)
            {

                Color cl = image.GetPixel(i, j);
                if (cl.R > (cl.G * 2) && cl.R > (cl.B * 2))
                {
                    g.FillRectangle(black, new Rectangle(i, j, skip, skip));
                }
                else
                {
                    g.FillRectangle(white, new Rectangle(i, j, skip, skip));
                }
            }
        }
   }

Can you point out the mistake, OR any other better method to achieve what I aim for?

Upvotes: 1

Views: 294

Answers (3)

Niki
Niki

Reputation: 15867

You didn't show where image is created, but this code will draw into a bitmap:

var bmp = new Bitmap(200,200);
using (g = Graphics.FromImage(bmp))
{
    g.FillEllipse(Brushes.Red, 10, 10, 50, 50);
}

Note that you need to call Graphics.Dispose (or use using) before using the image.

Also note that using GetPixel for image processing will be very slow. Use low-level memory access (Bitmap.LockBits) or try some image processing library for .NET (like AForge).

Upvotes: 0

Felice Pollano
Felice Pollano

Reputation: 33252

Try to use:

Graphics g = Graphics.FromImage(image);

Then consider other replies to improve your color testing.

Upvotes: 2

Lou Franco
Lou Franco

Reputation: 89162

By blank, do you mean white?

I don't know your image, but if (cl.R > (cl.G * 2) && cl.R > (cl.B * 2)) is not a good test for redness. #010000 passes that test, but is basically black. And, #ffaaaa looks red, but won't pass.

If you had a very dark image, lots of pixels might pass that test that aren't very red. With a light image, lots of red pixels won't pass.

Probably the best way is to convert the color the HSL, and then use values of H(ue) that are in the red zone, but only if S(aturation) and L(uminance) are sufficiently bright and non-gray (over a threshhold to not just be black or gray).

Upvotes: 4

Related Questions