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)
python类hsv_to_rgb()的实例源码
def draw_outputs(img, boxes, confidences, wait=1):
I = img * 255.0
#nms = non_max_suppression_fast(np.asarray(filtered_boxes), 1.00)
picks = postprocess_boxes(boxes, confidences)
for box, conf, top_label in picks:#[filtered[i] for i in picks]:
if top_label != classes:
#print("%f: %s %s" % (conf, coco.i2name[top_label], box))
c = colorsys.hsv_to_rgb(((top_label * 17) % 255) / 255.0, 1.0, 1.0)
c = tuple([255*c[i] for i in range(3)])
draw_ann(I, box, i2name[top_label], color=c, confidence=conf)
I = cv2.cvtColor(I.astype(np.uint8), cv2.COLOR_RGB2BGR)
cv2.imshow("outputs", I)
cv2.waitKey(wait)
def actionConfigSetColorSwatchRGB(self, hue, saturation, value):
self.methodTracer.threaddebug(u"CLASS: Plugin")
# hue, saturation and value are integers in the range 0 - 65535
hue = float(hue) / 65535.0
value = float(value) / 65535.0
saturation = float(saturation) / 65535.0
red, green, blue = colorsys.hsv_to_rgb(hue, saturation, value)
red = int(round(float(red * 255.0)))
green = int(round(float(green * 255.0)))
blue = int(round(float(blue * 255.0)))
rgb = [red,green,blue]
rgbHexVals = []
for byteLevel in rgb:
if byteLevel < 0:
byteLevel = 0
elif byteLevel > 255:
byteLevel = 255
rgbHexVals.append("%02X" % byteLevel)
return ' '.join(rgbHexVals)
def execute(self, context):
import random
from random import uniform
random.seed(self.random_seed)
for obj in bpy.context.selected_objects:
if (obj.type == 'MESH' or obj.type == 'CURVE'):
r = uniform(self.rminmax[0], self.rminmax[1])
g = uniform(self.gminmax[0], self.gminmax[1])
b = uniform(self.bminmax[0], self.bminmax[1])
m = obj.active_material
if self.rgb_or_hsv:
col = colorsys.hsv_to_rgb(r, g, b)
m.node_tree.nodes[1].inputs[0].default_value = (
col[0], col[1], col[2], 1)
obj.active_material.diffuse_color = (col)
else:
m.node_tree.nodes[1].inputs[0].default_value = (r, g, b, 1)
obj.active_material.diffuse_color = (r, g, b)
return {'FINISHED'}
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 get_colors_for_classes(num_classes):
"""Return list of random colors for number of classes given."""
# Use previously generated colors if num_classes is the same.
if (hasattr(get_colors_for_classes, "colors") and
len(get_colors_for_classes.colors) == num_classes):
return get_colors_for_classes.colors
hsv_tuples = [(x / num_classes, 1., 1.) for x in range(num_classes)]
colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
colors = list(
map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
colors))
random.seed(10101) # Fixed seed for consistent colors across runs.
random.shuffle(colors) # Shuffle colors to decorrelate adjacent classes.
random.seed(None) # Reset seed to default.
get_colors_for_classes.colors = colors # Save colors for future calls.
return colors
def draw_outputs(img, boxes, confidences, wait=1):
I = img * 255.0
#nms = non_max_suppression_fast(np.asarray(filtered_boxes), 1.00)
picks = postprocess_boxes(boxes, confidences)
for box, conf, top_label in picks:#[filtered[i] for i in picks]:
if top_label != classes:
#print("%f: %s %s" % (conf, coco.i2name[top_label], box))
c = colorsys.hsv_to_rgb(((top_label * 17) % 255) / 255.0, 1.0, 1.0)
c = tuple([255*c[i] for i in range(3)])
I = cv2.cvtColor(I.astype(np.uint8), cv2.COLOR_RGB2BGR)
cv2.imshow("outputs", I)
cv2.waitKey(wait)
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 pathsToSVG(self, G, paths):
svgPaths = []
for path in paths:
svgPath = []
for nodeIndex, n in enumerate(path):
command = None
if nodeIndex == 0:
command = 'M'
else:
command = 'L'
svgPath.append([command, (G.node[n]['x'], G.node[n]['y'])])
svgPaths.append(svgPath)
#Create a group
parent = inkex.etree.SubElement(self.current_layer, inkex.addNS('g','svg'))
for pathIndex, svgPath in enumerate(svgPaths):
#Generate a different color for every path
color = colorsys.hsv_to_rgb(pathIndex/float(len(svgPaths)), 1.0, 1.0)
color = tuple(x * 255 for x in color)
color = self.rgbToHex( color )
self.addPathToInkscape(svgPath, parent, color)
#Computes the physical path length (it ignores the edge weight)
def handleLedMessage(message):
if message.type == 'note_on' or message.type == 'note_off':
h = message.note / 127.0
s = message.velocity / 127.0
if message.type == 'note_on':
v = 1.0
else:
v = 0.0
rgb = colorsys.hsv_to_rgb(h, s, v)
r = int(rgb[0] * 255)
g = int(rgb[1] * 255)
b = int(rgb[2] * 255)
print("LED ring r:{} g:{} b:{}".format(r, g, b))
publishLedColor(r, g, b)
def get_colormap(self, k=5, criterion='maxclust'):
"""Generate colormap based on clustering.
Parameters
----------
k : {int, float}
criterion : {'maxclust','distance'}, optional
If `maxclust`, `k` clusters will be formed. If `distance`,
clusters will be created at threshold `k`.
Returns
-------
dict
{'skeleton_id': (r,g,b),...}
"""
cl = self.get_clusters(k, criterion, return_type='indices')
cl = [[self.mat.index.tolist()[i] for i in l] for l in cl]
colors = [colorsys.hsv_to_rgb(1 / len(cl) * i, 1, 1)
for i in range(len(cl) + 1)]
return {n: colors[i] for i in range(len(cl)) for n in cl[i]}
def colorShape(obj, rgb=None, hsv=None):
if not rgb:
if hsv and len(hsv) == 3:
rgb = colorsys.hsv_to_rgb(*hsv)
else:
raise RuntimeError('colorShape requires an rgb or hsv input.')
mc.setAttr('{}.overrideEnabled'.format(obj), 1)
mc.setAttr('{}.overrideRGBColors'.format(obj), 1)
mc.setAttr('{}.overrideColorRGB'.format(obj), *rgb)
shapes = mc.listRelatives(obj, shapes=True, pa=True)
for shape in shapes:
#if mc.getAttr('{}.overrideEnabled'.format(shape)):
mc.setAttr('{}.overrideEnabled'.format(shape), 1)
mc.setAttr('{}.overrideRGBColors'.format(shape), 1)
mc.setAttr('{}.overrideColorRGB'.format(shape), *rgb)
def flash_random(flash_count, delay):
# Copied from https://github.com/pimoroni/unicorn-hat/blob/master/python/examples/random_blinky.py
for index in range(flash_count):
rand_mat = np.random.rand(8, 8)
for y in range(8):
for x in range(8):
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)
lights.set_pixel(x, y, r, g, b)
lights.show()
time.sleep(delay)
lights.off()
time.sleep(delay)
def set_color(self, hue, sat, bri, kel):
"""Set color state values."""
self._hue = hue
self._sat = sat
self._bri = bri
self._kel = kel
red, green, blue = colorsys.hsv_to_rgb(hue / SHORT_MAX,
sat / SHORT_MAX,
bri / SHORT_MAX)
red = int(red * BYTE_MAX)
green = int(green * BYTE_MAX)
blue = int(blue * BYTE_MAX)
_LOGGER.debug("set_color: %d %d %d %d [%d %d %d]",
hue, sat, bri, kel, red, green, blue)
self._rgb = [red, green, blue]
def convert_hsv(hsv):
return tuple(pow(val, 2.2) for val in colorsys.hsv_to_rgb(*hsv))
def rainbowLights(r=5, n=100, freq=2, energy=0.1):
for i in range(n):
t = float(i)/float(n)
pos = (r*sin(tau*t), r*cos(tau*t), r*sin(freq*tau*t))
# Create lamp
bpy.ops.object.add(type='LAMP', location=pos)
obj = bpy.context.object
obj.data.type = 'POINT'
# Apply gamma correction for Blender
color = tuple(pow(c, 2.2) for c in colorsys.hsv_to_rgb(t, 0.6, 1))
# Set HSV color and lamp energy
obj.data.color = color
obj.data.energy = energy
def hsv(cls, hue, saturation, value):
assert 0 <= hue <= 1 and 0 <= saturation <= 1 and 0 <= value <= 1
r, g, b = colorsys.hsv_to_rgb(hue, saturation, value)
return cls(round(r * 0xFF), round(g * 0xFF), round(b * 0xFF))
def hsv_updated(self, value):
# Update the interface after HSV change.
h = self.h_scale['value']
s = self.s_scale['value']
v = self.v_scale['value']
self.update_hsv(h, s, v)
r, g, b = colorsys.hsv_to_rgb(h, s, v)
self.update_rgb(r, g, b)
self.update_color_area()
def convertHsvToRgb(hsv):
"""Converts hsv values to rgb
rgb is in 0-1 range, hsv is in (0-360, 0-1, 0-1) ranges
:param hsv: Hue Saturation Value Hue is in 0-360 range, Sat/Value 0-1 range
:type hsv: list
:return rgb: Red Green Blue values 0-1
:rtype rgb: list
"""
rgb = list(colorsys.hsv_to_rgb((hsv[0] / 360.0), hsv[1], hsv[2])) # convert HSV to RGB
return rgb
def fromhsv(self, h, s, v):
"""Convert to RGB from HSV."""
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