Calculate the difference in hue between two s. - CSharp System.Drawing

CSharp examples for System.Drawing:Color Calculation

Description

Calculate the difference in hue between two s.

Demo Code


using System.Windows.Media;
using System.Globalization;
using System;// w ww .  j a v a  2  s .c  o  m

public class Main{
        /// <summary>
        /// Calculate the difference in hue between two <see cref="Color"/>s.
        /// </summary>
        /// <param name="c1">
        /// </param>
        /// <param name="c2">
        /// </param>
        /// <returns>
        /// The hue difference.
        /// </returns>
        public static double HueDifference(Color c1, Color c2)
        {
            double[] hsv1 = ColorToHsv(c1);
            double[] hsv2 = ColorToHsv(c2);
            double dh = hsv1[0] - hsv2[0];

            // clamp to [-0.5,0.5]
            if (dh > 0.5)
            {
                dh -= 1.0;
            }

            if (dh < -0.5)
            {
                dh += 1.0;
            }

            double e = dh * dh;
            return Math.Sqrt(e);
        }
        /// <summary>
        /// Converts from a <see cref="Color"/> to HSV values (double)
        /// </summary>
        /// <param name="color">
        /// </param>
        /// <returns>
        /// Array of [Hue,Saturation,Value] in the range [0,1]
        /// </returns>
        public static double[] ColorToHsv(Color color)
        {
            byte r = color.R;
            byte g = color.G;
            byte b = color.B;

            double h = 0, s, v;

            double min = Math.Min(Math.Min(r, g), b);
            v = Math.Max(Math.Max(r, g), b);
            double delta = v - min;

            if (v == 0.0)
            {
                s = 0;
            }
            else
            {
                s = delta / v;
            }

            if (s == 0)
            {
                h = 0.0;
            }
            else
            {
                if (r == v)
                {
                    h = (g - b) / delta;
                }
                else if (g == v)
                {
                    h = 2 + (b - r) / delta;
                }
                else if (b == v)
                {
                    h = 4 + (r - g) / delta;
                }

                h *= 60;
                if (h < 0.0)
                {
                    h = h + 360;
                }
            }

            var hsv = new double[3];
            hsv[0] = h / 360.0;
            hsv[1] = s;
            hsv[2] = v / 255.0;
            return hsv;
        }
}

Related Tutorials