compare two given colors by similarity of hue in csharp

To compare two colors by similarity of hue in c#, first, we need to convert each color to the HSL (Hue, Saturation, Lightness) color space. Then we can compare their hue values to determine the similarity.

Here's an example implementation of a function that compares two colors by their hue similarity:

main.cs
public static bool AreColorsSimilarByHue(Color color1, Color color2, int hueThreshold = 10)
{
    // Convert the colors to the HSL color space
    var hsl1 = HslColor.FromColor(color1);
    var hsl2 = HslColor.FromColor(color2);

    // Calculate the difference in hue values, accounting for wrap-around at 360 degrees
    var hueDiff = Math.Abs(hsl1.H - hsl2.H) % 360;
    hueDiff = hueDiff > 180 ? 360 - hueDiff : hueDiff;

    // Compare the hue difference to the threshold
    return hueDiff <= hueThreshold;
}
515 chars
14 lines

This function takes two Color objects as input, along with an optional hueThreshold parameter that specifies the maximum difference in hue values that we consider to be "similar". The function first converts the color values to the HSL color space using a HslColor class (which can be found in many third-party libraries, or implemented yourself if you prefer). It then calculates the difference in hue values between the two colors, accounting for wrap-around at 360 degrees, and checks if the absolute difference is less than or equal to the threshold. If it is, the function returns true, meaning that the colors are similar in hue; otherwise, it returns false.

With this function, you can easily compare any two colors by their hue similarity in your c# program.

gistlibby LogSnag