All pastes #261395 Raw Edit

Unnamed

public text v1 · immutable
#261395 ·published 2006-11-29 05:28 UTC
rendered paste body
sub rgb_to_hsv {
    my ($r, $g, $b) =  shift @_;
    my $max = 0;
    my $min = 255;

    for ($r, $g, $b) { $max = $_ if $max < $_ }
    for ($r, $g, $b) { $min = $_ if $min > $_ }

    my ($h, $s, $v);

    #H Calculations to find H

    # You have greyscale if RGB are the same. "If you've got grey, the
    # question "is it red, or blue, or green, or yellow" is pointless"
    if ($max == $min)  { 
	$h = undef;
    }

    #Refer to http://en.wikipedia.org/wiki/HSV_color_space  for details on the
    #remaining steps
    elsif (($max == $r) && ($g >= $b)) {        
	$h = 60 * (($g-$b)/($max-$min)) + 0;
    }
    elsif (($max== $r) && ($g < $b)) {
	$h = 60 * (($g-$b)/($max-$min)) + 360;
    }
    elsif ($max == $g) {
	$h = 60 * (($b-$r)/($max-$min)) + 120;
    }
    elsif ($max == $b) {
	$h = 60 * (($r-$g)/($max-$min)) + 240;
    }

    #S Calculations to find S
    if ($max == 0) { #No saturation if the colour is Black
	$s = 0;
    }
    else {
	$s = 1 - ($min / $max) #Finds Saturation using a formula :P
    }

    #V Calculations to find V
    $v = $max; #V is the highest of the RGB values.

    return ($h, $s, $v);
}