Skip to content

Instantly share code, notes, and snippets.

@cab404 cab404/hsvrgb.py
Created Nov 7, 2015

Embed
What would you like to do?
def rgb2hsv(r, g, b):
v = max(r,g,b)
l = min(r,g,b)
sxf = (1.0 / 6)
trd = (1.0 / 3)
# actual start
s = l / v;
# actual distance
d = v - l
r = (r - l) / d
g = (g - l) / d
b = (b - l) / d
h = 0
if (r == 1):
if (b > 0): h += sxf * (1 - b)
if (g > 0): h += sxf * (1 + g)
elif (g == 1):
h += trd
if (r > 0): h += sxf * (1 - r)
if (b > 0): h += sxf * (1 + b)
elif (b == 1):
h += 2 * trd
if (g > 0): h += sxf * (1 - g)
if (r > 0): h += sxf * (1 + r)
h -= sxf
if (h < 0): h += 1
return (h, s, v)
def hsv2rgb(h, s, v):
r = 0
g = 0
b = 0
sxf = (1.0 / 6)
trd = (1.0 / 3)
h += sxf
if (h > 1): h -= 1.0
if (h < trd):
r = 1.0
if (h < sxf):
b = 1.0 - (h / sxf)
else:
g = ((h - sxf) / sxf)
elif (h < 2 * trd):
g = 1.0
h -= 1 * trd
if (h < sxf):
r = 1.0 - (h / sxf)
else:
b = ((h - sxf) / sxf)
else:
b = 1.0
h -= 2 * trd
if (h < sxf):
g = 1.0 - (h / sxf)
else:
r = ((h - sxf) / sxf)
c = (s * v)
r = c + (r * (v - c))
g = c + (g * (v - c))
b = c + (b * (v - c))
return (r,g,b)
print (hsv2rgb(1.0/12, 0.5, 0.5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.