Skip to content

Instantly share code, notes, and snippets.

@remram44
Created August 20, 2013 17:33
Show Gist options
  • Save remram44/6284607 to your computer and use it in GitHub Desktop.
Save remram44/6284607 to your computer and use it in GitHub Desktop.
HSV color generator
def rgb2hsv(rgb):
"""Converts RGB to HSV.
Note that H may be None when S is 0 (for grey colors).
"""
r, g, b = rgb
minimum = min(r, g, b)
maximum = max(r, g, b)
v = maximum
delta = maximum - minimum
if delta != 0:
s = delta / maximum
else:
# h is undefined
s = 0
h = None
return (h, s, v)
if r == maximum:
h = (g - b) / delta # between yellow & magenta
elif g == maximum:
h = 2 + (b - r) / delta # between cyan & yellow
else:
h = 4 + (r - g) / delta # between magenta & cyan
h *= 60 # degrees
if h < 0:
h += 360
return (h, s, v)
def hsv2rgb(hsv):
"""Converts HSV to RGB.
Accepts H=None when S=0.
"""
h, s, v = hsv
if s == 0:
return (v, v, v)
h /= 60
i = int(h)
f = h - i # factorial part
p = v * (1 - s)
q = v * (1 - s * f)
t = v * (1 - s * (1 - f))
if i == 0:
return (v, t, p)
elif i == 1:
return (q, v, p)
elif i == 2:
return (p, v, t)
elif i == 3:
return (p, q, v)
elif i == 4:
return (t, p, v)
else: # i == 5
return (v, p, q)
class ColorGenerator(object):
def __init__(self, h=8, v=2):
self.colors_per_value = h
self.value_planes = v
def get_color_hsv(self, pos):
h = 360.0 / self.colors_per_value * (pos % self.colors_per_value)
s = 1.0
v = pos // self.colors_per_value
if v >= self.value_planes:
raise ValueError
v = 1.0 - (1.0/self.value_planes) * v
print "h, s, v: %f, %f, %f" % (h, s, v)
return (h, s, v)
def get_color_rgb(self, pos):
return hsv2rgb(self.get_color_hsv(pos))
get_color = get_color_rgb
def __iter__(self):
def generator():
pos = 0
try:
while True:
yield self.get_color(pos)
pos += 1
except ValueError:
raise StopIteration
return generator()
from PyQt4 import QtGui
if __name__ == '__main__':
app = QtGui.QApplication([])
w = QtGui.QWidget()
w.show()
l = QtGui.QVBoxLayout()
w.setLayout(l)
for r, g, b in ColorGenerator(12, 2):
c = QtGui.QWidget()
c.setStyleSheet('background-color: rgb(%d, %d, %d);' % (
r * 255, g * 255, b * 255))
l.addWidget(c)
app.exec_()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment