Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine image overall lightness

Tags:

c#

.net

imaging

I need to overlay some texts on an image; this text should be lighter or darker based on the overall image lightness. How to compute the overall (perceived) lightness of an image?

Found something interesting for single pixel: Formula to determine brightness of RGB color

like image 968
ʞᴉɯ Avatar asked Nov 01 '11 09:11

ʞᴉɯ


People also ask

How do you determine the color lightness?

Here are 3 ways to calculate Luminance: Luminance (standard for certain colour spaces): (0.2126*R + 0.7152*G + 0.0722*B) source. Luminance (perceived option 1): (0.299*R + 0.587*G + 0.114*B) source.

How do you calculate the mean brightness of an image?

It's generally the same for "brightness" of an image, "loudness" of a sound signal, etc. Some ideas of what you can use as a generic "brightness" is: Average value of all the pixels (i.e. sum up all the brightnesses of all the pixels, then divide by total amount of pixels, i.e. width * height).

How do you calculate RGB intensity?

The intensity is the sum of the RGB values normalized to 1: 1 1= 3(R + G+ B). (10.11) - R+G+B.


1 Answers

Solved by me:

    public static double CalculateAverageLightness(Bitmap bm)
    {
        double lum = 0;
        var tmpBmp = new Bitmap(bm);
        var width = bm.Width;
        var height = bm.Height;
        var bppModifier = bm.PixelFormat == PixelFormat.Format24bppRgb ? 3 : 4;

        var srcData = tmpBmp.LockBits(new Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.ReadOnly, bm.PixelFormat);
        var stride = srcData.Stride;
        var scan0 = srcData.Scan0;

        //Luminance (standard, objective): (0.2126*R) + (0.7152*G) + (0.0722*B)
        //Luminance (perceived option 1): (0.299*R + 0.587*G + 0.114*B)
        //Luminance (perceived option 2, slower to calculate): sqrt( 0.299*R^2 + 0.587*G^2 + 0.114*B^2 )

        unsafe
        {
            byte* p = (byte*)(void*)scan0;

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    int idx = (y * stride) + x * bppModifier;
                    lum += (0.299*p[idx + 2] + 0.587*p[idx + 1] + 0.114*p[idx]);
                }
            }
        }

        tmpBmp.UnlockBits(srcData);
        tmpBmp.Dispose();
        var avgLum = lum / (width * height);


        return avgLum/255.0;
    }
like image 148
ʞᴉɯ Avatar answered Sep 23 '22 00:09

ʞᴉɯ