def fromhwb(self, h, w, b):
"""Convert to RGB from HWB."""
# Normalize white and black
# w + b <= 1.0
if w + b > 1.0:
norm_factor = 1.0 / (w + b)
w *= norm_factor
b *= norm_factor
# Convert to HSV and then to RGB
s = 1.0 - (w / (1.0 - b))
v = 1.0 - b
r, g, b = hsv_to_rgb(h, s, v)
self.r = round_int(r * 255.0) & 0xFF
self.g = round_int(g * 255.0) & 0xFF
self.b = round_int(b * 255.0) & 0xFF
python类hsv_to_rgb()的实例源码
def get_symbols_for_filts(uf):
# Plot colors
#cc = ['r','g','b','m','k']
# blue to red
cc = [colorsys.hsv_to_rgb(h, 1., 1.)
for h in np.linspace(0.666, 0., len(uf), endpoint=True)]
# normalize
cc = [x / np.sum(x) for x in cc]
# darken green
for x in cc:
x[1] *= 0.7
# Plot symbols
ss = ['*','x','o','^','s']
# filter-to-color and filter-to-symbol maps
fcmap = dict([(f,cc[i%len(cc)]) for i,f in enumerate(uf)])
fsmap = dict([(f,ss[i%len(ss)]) for i,f in enumerate(uf)])
return cc, ss, fcmap, fsmap
def fromhwb(self, h, w, b):
"""Convert to RGB from HWB."""
# Normalize white and black
# w + b <= 1.0
if w + b > 1.0:
norm_factor = 1.0 / (w + b)
w *= norm_factor
b *= norm_factor
# Convert to HSV and then to RGB
s = 1.0 - (w / (1.0 - b))
v = 1.0 - b
r, g, b = hsv_to_rgb(h, s, v)
self.r = round_int(r * 255.0) & 0xFF
self.g = round_int(g * 255.0) & 0xFF
self.b = round_int(b * 255.0) & 0xFF
def __changeMode(self, *args):
newMode = self.colorModeVar.get()
if newMode != self.colorModeLocal:
x = self.colorX.get()
y = self.colorY.get()
z = self.colorZ.get()
col=0
if newMode == 0: # HSV->RGB
col = [ int(round(x*255.0)) for x in colorsys.hsv_to_rgb(x/255.0, y/255.0, z/255.0)]
else: # RGB -> HSV
col = [ int(round(x*255.0)) for x in colorsys.rgb_to_hsv(x/255.0, y/255.0, z/255.0)]
self.colorX.set(col[0])
self.colorY.set(col[1])
self.colorZ.set(col[2])
self.colorModeLocal = newMode
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def set_outline(self, color=[255, 0, 0], width=2):
'enables the draw_outline and sets line color and width'
self.perm_outline = True
if color == 0 and hasattr(self, "door_outline") is False: # if color is 0 calculate colour from base colour
# convert to hsv
c = self.color
h, s, v = ex.rgb_to_hsv(c[0], c[1], c[2])
outline_color = ex.hsv_to_rgb(h, s + 50, v - 50)
self.perm_outline_color = outline_color
elif color == 1:
c = self.color
h, s, v = ex.rgb_to_hsv(c[0], c[1], c[2])
outline_color = ex.hsv_to_rgb(h, s + 20, v - 20)
self.perm_outline_color = outline_color
elif hasattr(self, "door_outline") is False:
self.perm_outline_color = color
else:
pass
# self.perm_outline_color = color
# self.perm_outline_color = [255,0,0]
self.perm_outline_width = width
self.init_pow = width
def hue_change(img, intensity, value):
"""
Change to purple/green hue
:param img: PIL image object
:param intensity: float > 0.1, larger the value, the less intense and more washout
:param value: float, the colour to hue change too on a scale from -360 to 0
:return: PIL image object
"""
original_width, original_height = img.size
# Don't apply hue change if already grayscaled.
if img.mode == 'L':
return img
else:
ld = img.load()
for y in range(original_height):
for x in range(original_width):
r, g, b = ld[x, y]
h, s, v = rgb_to_hsv(r/255, g/255, b/255)
h = (h + value/360.0) % 1.0
s = s**intensity
r, g, b = hsv_to_rgb(h, s, v)
ld[x, y] = (int(r * 255.9999), int(g * 255.9999), int(b * 255.9999))
return img
def run(params):
width,height=unicorn.get_shape()
while True:
rand_mat = [[random.random() for i in range(width)] for j in range(height)]
for y in range(height):
for x in range(width):
h = 0.1 * rand_mat[x][y]
s = 0.8
v = rand_mat[x][y]
rgb = colorsys.hsv_to_rgb(h, s, v)
r = int(rgb[0]*255.0)
g = int(rgb[1]*255.0)
b = int(rgb[2]*255.0)
unicorn.set_pixel(x, y, r, g, b)
unicorn.show()
time.sleep(0.02)
def run(params):
def compute_z(x, y, t):
x = x + t
y = y + t
h, w = 2, 2
z = (128.0 + (128.0 * math.sin(x / 16.0)) + 128.0 + (128.0 * math.sin(y / 32.0)) \
+ 128.0 + (128.0 * math.sin(math.sqrt((x - w / 2.0) * (x - w / 2.0) + (y - h / 2.0) * (y - h / 2.0)) / 8.0)) \
+ 128.0 + (128.0 * math.sin(math.sqrt(x * x + y * y) / 8.0))) % 255 / 255
return z
t = 0
while True:
for y in range(8):
for x in range(8):
h = compute_z(x, y, t)
s = 1.0
v = 0.4
rgb = colorsys.hsv_to_rgb(h, s, v)
r = int(rgb[0]*255.0)
g = int(rgb[1]*255.0)
b = int(rgb[2]*255.0)
unicorn.set_pixel(x, y, r, g, b)
unicorn.show()
time.sleep(0.05)
t += 1
def run(params={}):
while True:
for t in range(10000):
for y in range(16):
for x in range(16):
h = 0.1
s = 1.0
v = compute_z(x, y, t)
rgb = colorsys.hsv_to_rgb(h, s, v)
r, g, b = lookup_color(x, y)
r = r * v
g = g * v
b = b * v
unicornhathd.set_pixel(x, y, r, g, b)
unicornhathd.show()
time.sleep(0.04)
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def read_color(self):
# See http://www.graphviz.org/doc/info/attrs.html#k:color
c = self.read_text()
c1 = c[:1]
if c1 == '#':
hex2float = lambda h: float(int(h, 16)/255.0)
r = hex2float(c[1:3])
g = hex2float(c[3:5])
b = hex2float(c[5:7])
try:
a = hex2float(c[7:9])
except (IndexError, ValueError):
a = 1.0
return r, g, b, a
elif c1.isdigit() or c1 == ".":
# "H,S,V" or "H S V" or "H, S, V" or any other variation
h, s, v = map(float, c.replace(",", " ").split())
r, g, b = colorsys.hsv_to_rgb(h, s, v)
a = 1.0
return r, g, b, a
elif c1 == "[":
sys.stderr.write('warning: color gradients not supported yet\n')
return None
else:
return self.lookup_color(c)
def read_color(self):
# See http://www.graphviz.org/doc/info/attrs.html#k:color
c = self.read_text()
c1 = c[:1]
if c1 == '#':
hex2float = lambda h: float(int(h, 16)/255.0)
r = hex2float(c[1:3])
g = hex2float(c[3:5])
b = hex2float(c[5:7])
try:
a = hex2float(c[7:9])
except (IndexError, ValueError):
a = 1.0
return r, g, b, a
elif c1.isdigit() or c1 == ".":
# "H,S,V" or "H S V" or "H, S, V" or any other variation
h, s, v = map(float, c.replace(",", " ").split())
r, g, b = colorsys.hsv_to_rgb(h, s, v)
a = 1.0
return r, g, b, a
elif c1 == "[":
sys.stderr.write('warning: color gradients not supported yet\n')
return None
else:
return self.lookup_color(c)
def create_light_icon(lid, light_data):
"""Creates a 1x1 PNG icon of light's RGB color and saves it to the local dir.
"""
# Create a color converter & helper
converter = colors.Converter()
# Set color based on the type of light
# See: http://www.developers.meethue.com/documentation/supported-lights
if light_data['state'].get('xy'):
rgb_value = converter.xy_to_rgb(light_data['state']['xy'][0], light_data['state']['xy'][1])
elif light_data['state'].get('bri'):
rgb_value = colorsys.hsv_to_rgb(0, 0, float(light_data['state']['bri']) / 255)
rgb_value = tuple([255 * x for x in rgb_value])
else:
rgb_value = (255, 255, 255) if light_data['state']['on'] else (0, 0, 0)
f = open(alp.local('icons/%s.png' % lid), 'wb')
w = png.Writer(1, 1)
w.write(f, [rgb_value])
f.close()
def hsvToRGB(data):
"""Convert image from HSV to RGB
Parameters
----------
data : numpy array [rows x columns x channels], input HSV image
Returns
-------
output : numpy array [rows x columns x channels], output RGB image
"""
dataSize = data.shape
output = np.zeros([np.prod(dataSize[0:2]),3])
data = data.reshape([np.prod(dataSize[0:2]),-1])
for i in range(0,np.prod(dataSize[0:2])):
output[i,:] = hsv_to_rgb(data[i,0],data[i,1],data[i,2])
return output.reshape(dataSize)
def get_colors(num_colors):
HSVcolors = np.array([np.linspace(0, 1, num_colors),
#np.random.uniform(low=0.3, high=0.7, size=(num_colors,)),
#np.random.uniform(low=0.55, high=0.95, size=(num_colors,))])
np.linspace(0.3, 0.7, num_colors),
np.linspace(0.55, 0.95, num_colors)])
HSVcolors = HSVcolors.transpose()
#np.random.shuffle(HSVcolors)
RGBcolors = [colorsys.hsv_to_rgb(hsv[0], hsv[1], hsv[2]) for hsv in HSVcolors]
return RGBcolors
#import matplotlib.colorbar as cb
#import matplotlib.pyplot as plt
#from matplotlib.colors import LinearSegmentedColormap
#n=20
#fig, ax = plt.subplots(figsize=(15, 1))
#cb.ColorbarBase(ax, cmap=LinearSegmentedColormap.from_list('newcm', get_colors(n), N=n), spacing='proportional', ticks=None, format='%1i', orientation=u'horizontal')
#plt.axis('off')
#plt.show()
def uh_pulse():
UH.off()
global working
working = True
global contWorking
contWorking = True
while contWorking == True:
x0, y0 = 3.5, 3.5
for z in range(1, 5)[::-1] + range(1, 10):
fwhm = 5/z
gauss = make_gaussian(fwhm, x0, y0)
for y in range(8):
for x in range(8):
h = 0.8
s = 0.8
v = gauss[x,y]
rgb = colorsys.hsv_to_rgb(h, s, v)
r = int(rgb[0] * 255.0)
g = int(rgb[1] * 255.0)
b = int(rgb[2] * 255.0)
UH.set_pixel(x, y, r, g, b)
UH.show()
time.sleep(0.025)
UH.off()
working = False
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def create_unique_color_float(tag, hue_step=0.41):
"""Create a unique RGB color code for a given track id (tag).
The color code is generated in HSV color space by moving along the
hue angle and gradually changing the saturation.
Parameters
----------
tag : int
The unique target identifying tag.
hue_step : float
Difference between two neighboring color codes in HSV space (more
specifically, the distance in hue channel).
Returns
-------
(float, float, float)
RGB color code in range [0, 1]
"""
h, v = (tag * hue_step) % 1, 1. - (int(tag * hue_step) % 4) / 5.
r, g, b = colorsys.hsv_to_rgb(h, 1., v)
return r, g, b
def hist_multi_channel(self, locs):
oversampling = self.parameters_dialog.oversampling.value()
self.oversampling = oversampling
if locs is None:
locs = self.locs
n_channels = len(locs)
hues = np.arange(0, 1, 1 / n_channels)
colors = [colorsys.hsv_to_rgb(_, 1, 1) for _ in hues]
renderings = []
for i in range(n_channels):
if self.dataset_dialog.checks[i].isChecked():
renderings.append(render.render_hist3d(locs[i], oversampling, self.t_min, self.t_min, self.t_max, self.t_max, self.z_min, self.z_max, self.pixelsize))
n_locs = sum([_[0] for _ in renderings])
images = np.array([_[1] for _ in renderings])
pixmap1 = self.pixmap_from_colors(images,colors,2)
pixmap2 = self.pixmap_from_colors(images,colors,0)
pixmap3 = self.pixmap_from_colors(images,colors,1)
return pixmap1, pixmap2, pixmap3
def calculate_histogram(self):
slice = self.pick_slice.value()
ax = self.figure.add_subplot(111)
ax.hold(False)
plt.cla()
n_channels = len(self.zcoord)
hues = np.arange(0, 1, 1 / n_channels)
self.colors = [colorsys.hsv_to_rgb(_, 1, 1) for _ in hues]
self.bins = np.arange(np.amin(np.hstack(self.zcoord)),np.amax(np.hstack(self.zcoord)),slice)
self.patches = []
ax.hold(True)
for i in range(len(self.zcoord)):
n, bins, patches = plt.hist(self.zcoord[i], self.bins, normed=1, facecolor=self.colors[i], alpha=0.5)
self.patches.append(patches)
plt.xlabel('Z-Coordinate [nm]')
plt.ylabel('Counts')
plt.title(r'$\mathrm{Histogram\ of\ Z:}$')
# refresh canvas
self.canvas.draw()
self.sl.setMaximum(len(self.bins)-2)
#self.sl.setValue(np.ceil((len(self.bins)-2)/2))
def fromhwb(self, h, w, b):
"""Convert to RGB from HWB."""
# Normalize white and black
# w + b <= 1.0
if w + b > 1.0:
norm_factor = 1.0 / (w + b)
w *= norm_factor
b *= norm_factor
# Convert to HSV and then to RGB
s = 1.0 - (w / (1.0 - b))
v = 1.0 - b
r, g, b = hsv_to_rgb(h, s, v)
self.r = round_int(r * 255.0) & 0xFF
self.g = round_int(g * 255.0) & 0xFF
self.b = round_int(b * 255.0) & 0xFF
def set_brightness(channel, br):
global status
if channel == 'all':
for ch in status['colour']:
c = status['colour'][ch]
r, g, b = c
h, s, v = rgb_to_hsv(r, g, b)
v = int(br) / 100.0
r, g, b = [int(c * 255) for c in hsv_to_rgb(h, s, v)]
status['colour'][ch] = [r, g, b]
if not all(status['state'].values()) == 0:
mote_on(status)
else:
c = status['colour'][int(channel)]
r, g, b = c
h, s, v = rgb_to_hsv(r, g, b)
v = int(br) / 100.0
r, g, b = [int(c * 255) for c in hsv_to_rgb(h, s, v)]
status['colour'][int(channel)] = [r, g, b]
if not status['state'][int(channel)] == 0:
mote_on(status)
return jsonify(status)
## Returns the current API version to the requester
def read_color(self):
# See http://www.graphviz.org/doc/info/attrs.html#k:color
c = self.read_text()
c1 = c[:1]
if c1 == '#':
hex2float = lambda h: float(int(h, 16)/255.0)
r = hex2float(c[1:3])
g = hex2float(c[3:5])
b = hex2float(c[5:7])
try:
a = hex2float(c[7:9])
except (IndexError, ValueError):
a = 1.0
return r, g, b, a
elif c1.isdigit() or c1 == ".":
# "H,S,V" or "H S V" or "H, S, V" or any other variation
h, s, v = map(float, c.replace(",", " ").split())
r, g, b = colorsys.hsv_to_rgb(h, s, v)
a = 1.0
return r, g, b, a
else:
return self.lookup_color(c)
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def read_color(self):
# See http://www.graphviz.org/doc/info/attrs.html#k:color
c = self.read_text()
c1 = c[:1]
if c1 == '#':
hex2float = lambda h: float(int(h, 16)/255.0)
r = hex2float(c[1:3])
g = hex2float(c[3:5])
b = hex2float(c[5:7])
try:
a = hex2float(c[7:9])
except (IndexError, ValueError):
a = 1.0
return r, g, b, a
elif c1.isdigit() or c1 == ".":
# "H,S,V" or "H S V" or "H, S, V" or any other variation
h, s, v = map(float, c.replace(",", " ").split())
r, g, b = colorsys.hsv_to_rgb(h, s, v)
a = 1.0
return r, g, b, a
elif c1 == "[":
sys.stderr.write('warning: color gradients not supported yet\n')
return None
else:
return self.lookup_color(c)
def random_colors(n, seed=None):
import random
import colorsys
random.seed(seed)
# based on http://stackoverflow.com/a/470747
colors = []
for i in range(n):
hsv = (1.*i/n, 0.9 + random.random()/10, 0.9 + random.random()/10)
rgb = tuple(255*x for x in colorsys.hsv_to_rgb(*hsv))
colors.append('#%02x%02x%02x' % rgb)
return colors
# Kelly's high-contrast colors [K Kelly, Color Eng., 3 (6) (1965)],
# via http://stackoverflow.com/a/4382138. Changes: black excluded as
# not applicable here, plus some reordering (numbers in comments give
# original order).
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))