compare two colors by hue in csharp

To compare two colors by hue in C#, you can use the HSL (Hue, Saturation, Lightness) color space. In this color space, the hue value represents the color's shade, saturation represents the purity of the color, and lightness represents the brightness of the color.

Here's an example algorithm to compare two colors by hue in C#:

main.cs
public static bool CompareColorsByHue(Color color1, Color color2, int hueThreshold = 10)
{
    // convert the colors to HSL
    float[] hsl1 = RGBtoHSL(color1.R, color1.G, color1.B);
    float[] hsl2 = RGBtoHSL(color2.R, color2.G, color2.B);

    // compare the hue values
    float hueDiff = Math.Abs(hsl1[0] - hsl2[0]);

    if (hueDiff > 0.5f)
    {
        // handle edge case when one hue is near 0 and the other is near 1
        hueDiff = 1 - hueDiff;
    }

    // compare the hue difference with the threshold
    return hueDiff * 360 <= hueThreshold;
}

// helper function to convert RGB to HSL
public static float[] RGBtoHSL(int r, int g, int b)
{
    float h, s, l;

    float rNorm = (float)r / 255f;
    float gNorm = (float)g / 255f;
    float bNorm = (float)b / 255f;

    float cmax = Math.Max(rNorm, Math.Max(gNorm, bNorm));
    float cmin = Math.Min(rNorm, Math.Min(gNorm, bNorm));
    float delta = cmax - cmin;

    // calculate the hue
    if (delta == 0)
    {
        h = 0;
    }
    else if (cmax == rNorm)
    {
        h = ((gNorm - bNorm) / delta) % 6;
    }
    else if (cmax == gNorm)
    {
        h = ((bNorm - rNorm) / delta) + 2;
    }
    else
    {
        h = ((rNorm - gNorm) / delta) + 4;
    }

    h = h / 6f;

    if (h < 0)
    {
        h = h + 1f;
    }

    // calculate the lightness and saturation
    l = (cmax + cmin) / 2f;

    if (delta == 0)
    {
        s = 0;
    }
    else
    {
        s = delta / (1 - Math.Abs((2 * l) - 1));
    }

    return new float[] { h, s, l };
}
1532 chars
72 lines

The CompareColorsByHue function takes two Color objects and an optional hueThreshold parameter (default value 10). It converts the colors to the HSL color space using the RGBtoHSL helper function. It then calculates the difference between the hue values of the two colors and checks if it's within the threshold. The hue difference is multiplied by 360 to convert it from a float between 0 and 1 to an angle in degrees.

Example usage:

main.cs
Color color1 = Color.FromArgb(255, 169, 208);
Color color2 = Color.FromArgb(213, 137, 209);

bool areSimilar = CompareColorsByHue(color1, color2);
147 chars
5 lines

In this example, areSimilar will be true because the hue difference between the two colors is within the default threshold value of 10.

gistlibby LogSnag