How to Compare Color Objects and Determine the Closest Match in an Array of Colors
Understanding color distances can be crucial for tasks like color selection and image processing. While there is no definitive definition of color distance, several methods can be employed to measure it.
1. Hue Only Comparison
This method focuses solely on the hue component of the color, ignoring saturation and brightness. Here's the implementation:
int closestColor1(List<Color> colors, Color target) { var hue1 = target.GetHue(); var diffs = colors.Select(n => getHueDistance(n.GetHue(), hue1)); var diffMin = diffs.Min(n => n); return diffs.ToList().FindIndex(n => n == diffMin); } float getHueDistance(float hue1, float hue2) { float d = Math.Abs(hue1 - hue2); return d > 180 ? 360 - d : d; }
2. RGB Distance
This method measures the direct distance between colors in RGB space:
int closestColor2(List<Color> colors, Color target) { var colorDiffs = colors.Select(n => ColorDiff(n, target)).Min(n => n); return colors.FindIndex(n => ColorDiff(n, target) == colorDiffs); } int ColorDiff(Color c1, Color c2) { return (int)Math.Sqrt((c1.R - c2.R) * (c1.R - c2.R) + (c1.G - c2.G) * (c1.G - c2.G) + (c1.B - c2.B) * (c1.B - c2.B)); }
3. Weighted Distance
This method considers hue, saturation, and brightness, with customizable weights:
int closestColor3(List<Color> colors, Color target) { float hue1 = target.GetHue(); var num1 = ColorNum(target); var diffs = colors.Select(n => Math.Abs(ColorNum(n) - num1) + getHueDistance(n.GetHue(), hue1) ); var diffMin = diffs.Min(x => x); return diffs.ToList().FindIndex(n => n == diffMin); } float ColorNum(Color c) { return c.GetSaturation() * factorSat + getBrightness(c) * factorBri; } float getBrightness(Color c) { return (c.R * 0.299f + c.G * 0.587f + c.B *0.114f) / 256f; }
To use these methods, convert your Color array into a List
The optimal method choice depends on the specific application and what aspect of color is most relevant.
The above is the detailed content of How to Find the Closest Color Match in an Array?. For more information, please follow other related articles on the PHP Chinese website!