0

I was wondering if there is an efficient way to detect similar colors?

I've been trying to find solutions, and the best "solution" I have found is this StackOverflow question:

How to determine if a color is close to another color

But, It seems to be detecting black more than the color I assigned, also with the threshold on low.

Here is my code:

COLORREF color_yellow = (255, 255, 0);
COLORREF color;

bool ColorsAreClose(COLORREF Colora, COLORREF Colorz, int threshold = 70)
{
    int r = (int)GetRValue(Colora) - GetRValue(Colorz),
        g = (int)GetGValue(Colora) - GetGValue(Colorz),
        b = (int)GetBValue(Colora) - GetBValue(Colorz);
    return (r * r + g * g + b * b) <= threshold * threshold;
}

int main(){
    while (true) {
        if (ColorsAreClose(color, color_yellow) == true) {
            std::cout << "true";
        }
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • It mostly always detects black colors alot more than yellow. (Just to clarify what my issue is.) and for anyone wondering, I am getting my main color from get pixel. – MrCoInSanity Mar 14 '22 at 02:59
  • Edit the question if you want to clarify something – Rafaelplayerxd YT Mar 14 '22 at 03:14
  • I am here not very clear what you mean by your "efficient way" and "best 'solution'". – FooF Mar 14 '22 at 03:23
  • Please specify your inputs, your expected outputs, and your actual outputs. – JohnFilleau Mar 14 '22 at 03:42
  • 3
    `COLORREF` is just a plain integer, a typedef for `DWORD`. `COLORREF color_yellow = (255, 255, 0);` is equivalent to `COLORREF color_yellow = 0;` (read about comma operator in your favorite C++ textbook). Your `color_yellow` is in fact black. You are looking for [`RGB` macro](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-rgb), as in `COLORREF color_yellow = RGB(255, 255, 0);` – Igor Tandetnik Mar 14 '22 at 05:05
  • 1
    @IgorTandetnik that should be posted as an answer – Remy Lebeau Mar 14 '22 at 05:36

1 Answers1

0

COLORREF color_yellow = (255, 255, 0); is equivalent to COLORREF color_yellow = 0;. The expression (255, 255, 0) involves the comma operator and evaluates to 0. Thus, color_yellow ends up representing black color, not yellow color.

To construct a COLORREF value from three color components, use RGB macro:

COLORREF color_yellow = RGB(255, 255, 0);
Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85