Search code examples
c#colorsdetectionsystem.drawingaforge

Detect the brightness of a pixel or the area surrounding it


I am writing a c# program and I am a noob in c#, although i am just fine in programming , i know C and C++. My program basically scans an image and locates the circle in that image and distinguishes them according to the coordinates of their centers. Now i want to make it find the brightness of the circle's color. i figured that it is enough to check the brightness of the center pixel, or even some pixels surrounding the circle too. But i couldn't do it so far. I tried using GetBrightness() in the color struct and get HUE but i couldn't specify what pixel i want it to work on. I hope i made myself clear and ask me for any more details. I will mention again that i am a noob in C# , all i know is C and C++


Solution

  • Take a look at this answer for the formula to calculate brightness from an RGB value: Formula to determine brightness of RGB color

    In C# this would look something like:

    public double GetBrightness(Color color)
    {
        return (0.2126*color.R + 0.7152*color.G + 0.0722*color.B);
    }
    

    If you wanted to calculate the brightness of all colors in a circle, then you could do something like:

    public double GetAverageBrightness(IEnumerable<Color> colors)
    {
        int count = 0;
        double sumBrightness = 0;
    
        foreach (var color in colors)
        {
            count++;
            sumBrightness += GetBrightness(color);
        }
    
        return sumBrightness/count;        
    }