Search code examples
c#asp.netocromr

Comparing Bitmap objects with different colors


I have a Bitmap object of a hand-written survey (see survey image below) which contains various checkboxes. I am using an algorithm to compare a Bitmap of a blank, unmarked checkbox against a Bitmap of the same checkbox (which may or may not be marked), in order to determine if the checkbox has been marked or not. This code basically loops over each checkbox location on the Bitmap, and scans pixel by pixel using bm.GetPixel(x, y).GetBrightness() < 0.5f, making a hash of the checkbox and storing it in a list. I will then compare the hash values of the blank checkbox against the hash values of the passed in checkbox (with some tolerance) to determine if it is marked or not.

Now my problem is this works perfectly if the checkboxes are marked with Black pen. If any other color pen (red, blue etc.) is used to mark these checkboxes then bm.GetPixel(x, y).GetBrightness() < 0.5f will not recognise the change in pixel. Can anyone tell me what I can change to include other color marks?

        foreach (KeyValuePair<string, CheckboxData> element in b1.CheckboxLocations)
        {

            int startX = element.Value.startX;
            int endX = element.Value.endX;
            int startY = element.Value.startY;
            int endY = element.Value.endY;

            List<bool> lResult = new List<bool>();

                for (int y = startY; y < endY; y++)
                {
                    for (int x = startX; x < endX; x++)
                    {
                        lResult.Add(bm.GetPixel(x, y).GetBrightness() < 0.5f);
                    }
                }

            int numMarked = 0;
            foreach(bool b in lResult)
            {
                if(b == true)
                {
                    numMarked++;
                }
            }

            Console.WriteLine($"Box Name: {element.Key}\nNumber of Pixels Marked: {numMarked}\n");

        }

enter image description here


Solution

  • Try looking instead at the R, G and B properties of the Bitmap object. You can then check each color individually against a unique threshold. Something like below may be more useful:

    lResult.Add(bm.GetPixel(x, y).R < 128 || bm.GetPixel(x, y).G < 128 || bm.GetPixel(x, y).B < 128);