Serge's World

Blogging about software development, astronomy, genealogy and more.

Image Processing in C#: Part 4 - Contrast

Contrast in a picture is a measure of how close the range of colours in a picture are. The closer the colours are together, the lower the contrast.

The value for the contrast ranges from -100 to 100, with positive numbers increasing the contrast, and negative numbers decreasing the contrast.

Now, we calculate the contrast value which we will use in the calculation with ((100 + contrast) / 100)

Then, for each pixel in the image, we take each component of the pixel, and divide the value by 255 to get a value between 0 and 1. We then subtract 0.5, and any values which are negative will have their contrast decreased, while any positive values will have their contrast increased.

We then add back the 0.5, and convert the value back to a range of 0-255. After that we set the pixel colour again.

Contrast

public void ApplyContrast(double contrast)
{
    double A, R, G, B;

    Color pixelColor;

    contrast = (100.0 + contrast) / 100.0;
    contrast *= contrast;

    for (int y = 0; y < bitmapImage.Height; y++)
    {
        for (int x = 0; x < bitmapImage.Width; x++)
        {
            pixelColor = bitmapImage.GetPixel(x, y);
            A = pixelColor.A;

            R = pixelColor.R / 255.0;
            R -= 0.5;
            R *= contrast;
            R += 0.5;
            R *= 255;

            if (R > 255)
            {
                R = 255;
            }
            else if (R < 0)
            {
                R = 0;
            }

            G = pixelColor.G / 255.0;
            G -= 0.5;
            G *= contrast;
            G += 0.5;
            G *= 255;
            if (G > 255)
            {
                G = 255;
            }
            else if (G < 0)
            {
                G = 0;
            }

            B = pixelColor.B / 255.0;
            B -= 0.5;
            B *= contrast;
            B += 0.5;
            B *= 255;
            if (B > 255)
            {
                B = 255;
            }
            else if (B < 0)
            {
                B = 0;
            }

            bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));
        }
    }
}

The full source used in the series is available from https://github.com/sjmeunier/image-processor.

Originally posted on my old blog, Smoky Cogs, on 19 Nov 2009

Tag Cloud

Algorithms (3) Android (10) Astronomy (25) Audio (1) Audiobooks (1) Barcodes (9) C# (69) Css (1) Deep sky (6) Esoteric languages (3) Family (3) Fractals (10) Gaming (1) Genealogy (14) General (2) Geodesy (3) Google (1) Graphics (3) Hubble (2) Humour (1) Image processing (23) Java (8) Javascript (5) jQuery (3) Jupiter (3) Maths (22) Moon (5) Music (4) Pets (5) Programming (88) Saturn (1) Science (1) Spitzer (4) Sun (4) Tutorials (68) Unity (3) Web (9) Whisky (13) Windows (1) Xamarin (2)