Provide gamma correction for an image in C#


[example]

Gamma correction, or just gamma, is a nonlinear change to the red, green, and blue components of the pixels in an image. The post Use an ImageAttributes object to adjust an image’s brightness in C# explains how to use ImageAttributes and ColorMatrix objects to adjust an image’s brightness. Because it scales each pixel’s brightness by the same factor, the result can make bright areas too bright and dark areas too dark.

For example, suppose you’re brightening an image. The image’s bright areas probably don’t need as much brightening as the dark areas. Conversely if you’re darkening an image, the dark areas probably don’t need as much darkening as the bright areas.

Gamma correction adjusts an image’s brightness non-uniformly so bright areas are not as washed out and dark areas aren’t as dark. For more details about gamma correction, see the Wikipedia page Gamma correction.

You could loop through an image’s pixels and perform gamma correction on each one, but the ImageAttributes object can perform gamma correction for you much more quickly.

The following AdjustGamma method performs gamma correction on an image.

// Perform gamma correction on the image.
private Bitmap AdjustGamma(Image image, float gamma)
{
    // Set the ImageAttributes object's gamma value.
    ImageAttributes attributes = new ImageAttributes();
    attributes.SetGamma(gamma);

    // Draw the image onto the new bitmap
    // while applying the new gamma value.
    Point[] points =
    {
        new Point(0, 0),
        new Point(image.Width, 0),
        new Point(0, image.Height),
    };
    Rectangle rect =
        new Rectangle(0, 0, image.Width, image.Height);

    // Make the result bitmap.
    Bitmap bm = new Bitmap(image.Width, image.Height);
    using (Graphics gr = Graphics.FromImage(bm))
    {
        gr.DrawImage(image, points, rect,
            GraphicsUnit.Pixel, attributes);
    }

    // Return the result.
    return bm;
}

This code creates an ImageAttributes object and uses its SetGamma method to set the gamma correction value. This value should be greater than 0.0. Typical values range between 1 and 2.2.

After initializing the ImageAttributes object, the program uses it to draw the original image into a result Bitmap and returns the result. See the example Use an ImageAttributes object to adjust an image’s brightness in C# for additional details about how the drawing part works.

This method is extremely fast so you can drag the scroll bar back and forth to change the image’s gamma correction in real time.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in drawing, graphics, image processing and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

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