RGB To HSV

This algorithm converts RGB color model to HSV color model.



									class RGB
{
	public $R;
	public $G;
	public $B;
}

class HSV
{
	public $H;
	public $S;
	public $V;
}

function RGBToHSV($rgb) {
	$delta = 0;
	$min = 0;
	$h = 0;
	$s = 0;
	$v = 0;

	$min = min(min($rgb->R, $rgb->G), $rgb->B);
	$v = max(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;
	}

	$hsv = new HSV();
	$hsv->H = $h;
	$hsv->S = $s;
	$hsv->V = $v / 255;

	return $hsv;
}
								


Example

									$data = new RGB();
$data->R = 82;
$data->G = 0;
$data->B = 87;

$value = RGBToHSV($data);
								


Output

									H: 296.55172413793
S: 1
V: 0.34117647058824