How Can I Find the Closest Color Match in a Color Array?
Dec 31, 2024 am 09:58 AMClosest 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the types of values returned by c language functions? What determines the return value?

What are the definitions and calling rules of c language functions and what are the

C language function format letter case conversion steps

Where is the return value of the c language function stored in memory?

How do I use algorithms from the STL (sort, find, transform, etc.) efficiently?

How does the C Standard Template Library (STL) work?
