我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用colorsys.hsv_to_rgb()。
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 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 __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 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 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 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 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 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 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 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