### color conversion module ### package Color::Convert; sub min { @_ = sort @_; shift; } sub max { @_ = sort @_; pop; } sub rgb2hsv { # r,g,b values are from 0 to 255 # h = [0..360], s = [0..100], v = [0..100] # if s == 0, then h = -1 (undefined) my ($r,$g,$b) = @_; $r /= 255; $g /= 255; $b /= 255; my ($h, $s, $v); my ($min, $max, $delta); $min = min ( $r, $g, $b ); $max = max ( $r, $g, $b ); # value is just the brightest rgb value $v = $max; # account for shades of gray: $delta = $max - $min; if ($delta == 0 ) { $s = 0; # no hue, so it can't be saturated! $h = -1; # hue is really undefined, but... return ($h, $s, $v*100); } # saturation is intensity/blandness of color: $s = $delta / $max; # max > 0 or delta would be 0 # hue depends on the relative strengths of the colors: if( $r == $max ) { $h = ( $g - $b ) / $delta; # between yellow & magenta } elsif( $g == $max ) { $h = 2 + (( $b - $r ) / $delta); # between cyan & yellow } else { $h = 4 + (( $r - $g ) / $delta); # between magenta & cyan } # it's also calculated as degrees on a color wheel $h *= 60; # degrees $h += 360 if ($h < 0); # s and v are percentages $s *= 100; $v *= 100; return (int( $h ), int($s), int($v)); # should be rounded, but oh well } 1;