I get following codes from a Japanese Ghost's Blog, so I neglect the original URL for my hate of them.
RGB => HSV
def RGB2HSV( r, g, b ):
r, g, b = map( float, (r,g,b ) )
if r == g and g == b:
ma = r
mi = r
h = 0
v = r
elif r > g and r > b:
ma = r
mi = min( g , b )
h = 60 * ( g - b ) / ( ma - mi ) + 0
elif g > b and g >= r:
ma = g
mi = min( b , r )
h = 60 * ( b - r ) / ( ma - mi ) + 120
elif b >= r and b >= g:
ma = b
mi = min( r , g )
h = 60 * ( r - g ) / ( ma - mi ) + 240
else:
print "Error."
if ma == 0:
return 0, 0, 0
s = (ma - mi) / ma
v = ma
return h, s, v
HSV => RGB
def HSV2RGB( h, s, v ):
hi = int(h / 60) % 6
f = h / 60 - hi
p = v * ( 1 - s )
q = v * ( 1 - f * s )
t = v * ( 1 - ( 1 - f ) * s )
if hi == 0:
r = int(round( v ))
g = int(round( t ))
b = int(round( p ))
elif hi == 1:
r = int(round( q ))
g = int(round( v ))
b = int(round( p ))
elif hi == 2:
r = int(round( p ))
g = int(round( v ))
b = int(round( t ))
elif hi == 3:
r = int(round( p ))
g = int(round( q ))
b = int(round( v ))
elif hi == 4:
r = int(round( t ))
g = int(round( p ))
b = int(round( v ))
elif hi == 5:
r = int(round( v ))
g = int(round( p ))
b = int(round( q ))
return r, g, b