R
R
Rikonardo2019-05-07 20:44:32
Image processing
Rikonardo, 2019-05-07 20:44:32

How to convert RGB to 1 of 24 colors?

You need to write a code (function) that, using three variables (RGB), whose values ​​are in the range from 0 to 255 inclusive, will give the most suitable color from the list (in the picture). There are 24 options in total.
I can’t figure out how to write it at all (except how to write all possible options in if :D )
5cd1c3bf78836686984209.png
The function should look something like this:

int GetColorFromRGB(int R, int G, int B)
{
    int result = 0;
    //Тут происходит магия
    return result;
}

I understand that there must be some simple solution, but I can not get to it ...
I would be very grateful for the help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavlo Ponomarenko, 2019-05-07
@REKTOR_RG

The easiest way is to calculate your color's distance to each of the 24 and pick the closest one.
Well something like

Number Distance (Color source, Color target) {
  const dRed   = Math.Abs(target.r - source.r);
  const dGreen = Math.Abs(target.g - source.g);
  const dBlue  = Math.Abs(target.b - source.b);

  return dRed + dGreen + dBlue;
}

I'd start with this and see where it takes me

M
Moskus, 2019-05-07
@Moskus

Since this series of 24 colors is not ordered by any parameter and contains colors that have random distances between them in any of the main color spaces, it is impossible to write a function that would mathematically convert 24-bit colors to this palette. You can only find and hardcode the lookup table, or calculate the distance each time. Cartesian (as you were advised in the next answer) or perceptual (then you need, for example, to translate everything into a color space that takes into account human perception, and count in it).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question