Home >Backend Development >C++ >How Can I Find the Closest Color Match in a Color Array?
Closest Color Match in an Array
Given an array of colors and a separate Color object, the task is to determine the closest match within the array to the given color. Color distance is a subjective concept, and there are various ways to quantify it.
Hues Only Method
This method focuses solely on the hues of the colors, ignoring saturation and brightness. It calculates the absolute difference between the hues of the candidate color and the given color. The candidate color with the smallest hue difference is selected.
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); }
RGB Space Method
This method measures the direct distance between the colors in RGB space. It calculates the Euclidean distance between the R, G, and B components of the candidate color and the given color. The candidate color with the smallest distance is selected.
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); }
Weighted Method
This method assigns weights to the hue, saturation, and brightness components of the colors. It calculates a weighted distance by combining the hue difference with a weighted combination of saturation and brightness. The candidate color with the smallest weighted distance is selected.
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); }
Based on your requirements, you can choose the method that best suits your application.
The above is the detailed content of How Can I Find the Closest Color Match in a Color Array?. For more information, please follow other related articles on the PHP Chinese website!