Perform binary contrast enhancement on an image in C#

[binary contrast enhancement]

In binary contrast enhancement, you change every pixel in an image to either black or white depending on whether it is brighter than some cutoff value. This example takes a simple approach and makes a pixel white if the sum of its red, green, and blue components is greater than 384 (3 * 128).

This example uses the following BinaryContrast method to perform binary contrast enhancement on an image.

// Perform binary contrast enhancement on the bitmap.
private void BinaryContrast(Bitmap bm, int cutoff)
{
    for (int y = 0; y < bm.Height; y++)
    {
        for (int x = 0; x < bm.Width; x++)
        {
            Color clr = bm.GetPixel(x, y);
            if (clr.R + clr.G + clr.B > cutoff)
                bm.SetPixel(x, y, Color.White);
            else
                bm.SetPixel(x, y, Color.Black);
        }
    }
}

The code simply loops over each pixel, adds its red, green, and blue components, and makes the pixel black or white depending on whether the sum is greater than the cutoff value. The calling code sets cutoff to 3 * 128.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in algorithms, graphics, mathematics and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *