RGB To HSV

This algorithm converts RGB color model to HSV color model.



									public struct RGB
{
	private byte _r;
	private byte _g;
	private byte _b;

	public RGB(byte r, byte g, byte b)
	{
		this._r = r;
		this._g = g;
		this._b = b;
	}

	public byte R
	{
		get { return this._r; }
		set { this._r = value; }
	}

	public byte G
	{
		get { return this._g; }
		set { this._g = value; }
	}

	public byte B
	{
		get { return this._b; }
		set { this._b = value; }
	}

	public bool Equals(RGB rgb)
	{
		return (this.R == rgb.R) && (this.G == rgb.G) && (this.B == rgb.B);
	}
}

public struct HSV
{
	private double _h;
	private double _s;
	private double _v;

	public HSV(double h, double s, double v)
	{
		this._h = h;
		this._s = s;
		this._v = v;
	}

	public double H
	{
		get { return this._h; }
		set { this._h = value; }
	}

	public double S
	{
		get { return this._s; }
		set { this._s = value; }
	}

	public double V
	{
		get { return this._v; }
		set { this._v = value; }
	}

	public bool Equals(HSV hsv)
	{
		return (this.H == hsv.H) && (this.S == hsv.S) && (this.V == hsv.V);
	}
}

public static HSV RGBToHSV(RGB rgb)
{
	double delta, min;
	double h = 0, s, v;

	min = Math.Min(Math.Min(rgb.R, rgb.G), rgb.B);
	v = Math.Max(Math.Max(rgb.R, rgb.G), rgb.B);
	delta = v - min;

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

	if (s == 0)
		h = 0.0;

	else
	{
		if (rgb.R == v)
			h = (rgb.G - rgb.B) / delta;
		else if (rgb.G == v)
			h = 2 + (rgb.B - rgb.R) / delta;
		else if (rgb.B == v)
			h = 4 + (rgb.R - rgb.G) / delta;

		h *= 60;

		if (h < 0.0)
			h = h + 360;
	}

	return new HSV(h, s, (v / 255));
}
								


Example

									RGB data = new RGB(82, 0, 87);
HSV value = RGBToHSV(data);
								


Output

									H: 296.55172413793105
S: 1
V: 0.3411764705882353