0

Say, Given an arbitrary RGB Value and an array of colors with defined values(eg red, blue, green, yellow, etc.), what would be an optimal way of finding the nearest defined color to the arbitrary color?

Some Pseudocode:

        public struct DefinedColors
        {
            public string colorName;
            public Vector3 RGB;
            public Vector3 HSV; //Paying attention to Hue, float h?
            //public string hexdecimal ??
            public DefinedColors(string colorName, Vector3 RGB, Vector3 HSV)
            {
                this.colorName = colorName;
                this.RGB = RGB;
                this.HSV = HSV;
            }
        }
        public DefinedColors[] definedColors = new DefinedColors[6]
        {
            new DefinedColors("red", new Vector3(1,0,0), new Vector3(0,100,100)),
            new DefinedColors("yellow", new Vector3(1,1,0), new Vector3(60,100,100)),
            new DefinedColors("green", new Vector3(0,1,0), new Vector3(120,100,100)),
            new DefinedColors("cyan", new Vector3(0,1,1), new Vector3(180,100,100)),
            new DefinedColors("blue", new Vector3(0,0,1), new Vector3(240,100,100)),         
            new DefinedColors("magenta", new Vector3(1,0,1), new Vector3(300,100,100))
        };
    
    
        string NearestColor(Color color)
        {
            ///Logic 
    
            return definedColors[i].colorName;
        }

I know I could brute force something like

V3 arbitraryRGB;
V3 closest;
foreach(V3 v in foo) 
  if (|v-arbitraryRGB|<closest)
    closest = v;

I considered focusing on the hues of the color, because its a simple 0-360, but it gave me inconsistent results.

And I've read a little about KD Trees, but I don't know if that would be applicable.

FaffyWaffles
  • 125
  • 1
  • 7
  • Have you looked into the [`ColorUtility`](https://docs.unity3d.com/ScriptReference/ColorUtility.html)? Maybe you don't need this at all? – derHugo Apr 04 '22 at 08:01
  • Otherwise this would most probably be a duplicate of [How to compare `Color` object and get closest `Color` in an `Color[]`?](https://stackoverflow.com/questions/27374550/how-to-compare-color-object-and-get-closest-color-in-an-color) ;) – derHugo Apr 04 '22 at 08:02
  • If you don't mind using a [NuGet](https://www.nuget.org/packages/KGySoft.Drawing) package [this](https://docs.kgysoft.net/drawing/?topic=html/T_KGySoft_Drawing_Imaging_Palette.htm) `Palette` class has a pair of `GetNearestColor`/`GetNearestColorIndex` methods. Source is also available on GitHub. – György Kőszeg Apr 04 '22 at 08:32

0 Answers0