Perform binary contrast enhancement more quickly in C#

[binary contrast enhancement]

The example Perform binary contrast enhancement interactively in C# lets you convert an image into completely black and white pixels depending on their brightness. Pixels that are brighter than a given cutoff value are converted into white. Those that are darker than the cutoff value are converted into black.

That example works well but is annoyingly slow for large images because it uses the Bitmap class’s GetPixel and SetPixel methods to get and set pixel values. This example improves that one by using the Bitmap32 class described in the post Use the Bitmap32 class to manipulate image pixels very quickly in C#.

The following code shows how the new example uses the Bitmap32 class to perform binary contrast enhancement on an image.

// Perform binary contrast enhancement on the bitmap.
private void BinaryContrast(Bitmap bm, int cutoff)
    Bitmap32 bm32 = new Bitmap32(bm);

    for (int y = 0; y < bm.Height; y++)
        for (int x = 0; x < bm.Width; x++)
            byte r, g, b, a;
            bm32.GetPixel(x, y, out r, out g, out b, out a);
            if (r + g + b > cutoff)
                bm32.SetPixel(x, y, 255, 255, 255, 255);
                bm32.SetPixel(x, y, 0, 0, 0, 255);

The method creates a Bitmap32 object associated with the bitmap that it should process. It locks the Bitmap32 object and then loops through the image’s pixels.

For each pixel, the code uses the Bitmap32 object’s GetPixel method to get the pixel’s red, green, blue, and alpha color components. If the sum of the red, green, and blue components is greater than the cutoff value, the code uses the Bitmap32 object’s SetPixel method to make that pixel white. If the sum is less than or equal to the cuttoff value, the code uses SetPixel to make the pixel black.

After it finishes processing all of the bitmap’s pixels, the method unlocks the Bitmap32 and returns the modified bitmap.

Download the example and see the following posts to learn about additional details.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in algorithms, image processing and tagged , , , , , , , . Bookmark the permalink.