user239247
user239247

Reputation: 51

How to recognize "green" in a particular image?

Trying to find a solution for how to recognize if there is a "green" color on particular screenshot (image below).

The problem is that when using a plain RGB Bitmap, it doesn't work as I would like to because the image is taken from a screenshot of a webpage and it's kind of blurry, so many pixels doesn't look like "green".

I need somehow to understand how to define whether there is "green" color on a particular screenshot

enter image description here

Upvotes: 2

Views: 726

Answers (2)

fubo
fubo

Reputation: 45977

I need somehow to know whether there is green color

Iterate all pixels and search for the desired color

Color c = Color.Green; //or the color you want to search

Bitmap bmp = new Bitmap(Image.FromFile(@"c:\file.bmp"));
bool containsgreen = false;
for (int w = 0; w < bmp.Width; w++)
    for (int h = 0; h < bmp.Height; h++)
        if (bmp.GetPixel(w, h) == c)
            containsgreen = true;

If you're looking for a color range or similar colors, you could also calculate the color distance to add tolerance

public static double GetColourDistance(Color e1, Color e2)
{
    return Math.Sqrt((e1.R - e2.R) * (e1.R - e2.R) + (e1.G - e2.G) * (e1.G - e2.G) + (e1.B - e2.B) * (e1.B - e2.B));
}

Upvotes: 3

Kit
Kit

Reputation: 21729

I am going to assume from your question, that when you say green, you don't mean that any pixel will have some positive value for the G component of the RGB color, but that you mean it looks visually green to a human.

If that is the case, I suggest a modification to @fubo's code that calculates "visually green". That would be when the G component is greater than the other components.

Now, this will return true for some sketchy greens, e.g. a green that is very, very dark or very, very light. If you want to filter those out, use a tolerance value of your choosing.

Here's the code:

bool HasGreen(int tolerance)
{
    using (var bmp = new Bitmap(Image.FromFile(@"c:\file.bmp")))
    {            
        for (int w = 0; w < bmp.Width; w++)
        for (int h = 0; w < bmp.Height; h++)
            if (IsGreenPixel(bmp.GetPixel(w, h), tolerance))
                return true;
    }

    return false;
}

bool IsGreenPixel(Color color, int tolerance) 
    => color.G > color.R + tolerance && color.G > color.B + tolerance;

If you're looking for "what is the main green color in the green colors", you could modify this algorithm further by doing counts of colors and dropping them into buckets (i.e. a histogram).

Upvotes: 2

Related Questions