Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine which color (red, blue, green or other) would be visible for a given RGB value combination?

So basically, I need a method in which I can pass values of red, green and blue and the method should return whether that combination of RGB values result in a visibly Red-ish color Green-ish color or Blue-ish color. And if the combination doesn't result in any of those three colors it should return false.

I tried to do this by using conditional statements, tried a few variations, but nothing is accurate.

For example I tried:

if (B > 100 && B > G / 2 && B > R / 2)
{
    blueCount++;
}
else if (G > 100 && G > G / 2 && G > B / 2)
{
    greenCount++;
}
else if (R > 100 && R > G / 2 && R > B / 2)
{
    redCount++;
}

// R , G , B contains 0-255 values 
like image 976
kas Avatar asked Jan 01 '23 08:01

kas


2 Answers

If you define "being color-ish" as:

  • the color value is above 100
  • the color value is at least twice as the 2 other values
    • your current code states "at least half of the 2 other values" but this can't work because if you have "R:199 G:101 B:102", you could say that it is green-ish because G is above 100 and more than half 199 and half 102 (when it's obviously red-ish)

then your code looks almost good (just replace / with *).

I would just use an enum for the result:

enum Ish
{
    Other, // 0 so this would be false if you convert it to bool
    Red,   // 1
    Green, // 2
    Blue   // 3
}
if (R>100 && R>G*2 && R>B*2)
    return Ish.Red;
if (G>100 && G>R*2 && G>B*2) // you had G>G/2 here /!\
    return Ish.Green;
if (B>100 && B>G*2 && B>R*2)
    return Ish.Blue;
return Ish.Other;

I used 2 for twice, but I think you can use other values as long as it is >1 (you can't say blue is dominant if B <= R for example)

This would be the redish values possible for R=100 (left image with factor 2, right image with factor 1):

Red-ish 100 fact 2 Red-ish 100 fact 1

And this for R=200 (left image with factor 2, right image with factor 1):

Red-ish 200 fact 2 Red-ish 200 fact 1

Therefore you could probably use a factor between 1 and 2

For R=200 you can see the red-ish colors depending on the factor below:

Red-ish 200 multifactor

like image 51
Rafalon Avatar answered Jan 27 '23 18:01

Rafalon


I suggest using different color space: HSV or HSL instead of RGB.

Now, to declare the color being greenish you have to check

  1. If color has H (Hue) within some range (Green tinge dominates over other colors)
  2. If color has S (Saturation) above some threshold in order not to be too colorless (grayish)
  3. If color has V or L (Value or Luminocity) above some threshold in order not to be too dark (blackish)

https://vignette.wikia.nocookie.net/psychology/images/e/e0/HSV_cylinder.png/revision/latest?cb=20071105130143

like image 23
Dmitry Bychenko Avatar answered Jan 27 '23 19:01

Dmitry Bychenko