def __init__(self, persistent): assert isinstance(persistent, Persistent) from . import human_names color_resolution = 100 u = int(persistent._CrossProcessPersistent__uuid) (u, human_name_seed) = divmod(u, 5494) self.human_name = human_names.name_list[human_name_seed] '''A human name. (e.g. "Jeffrey".)''' color_seeds = [] for i in range(4): (u, new_color_seed) = divmod(u, color_resolution) color_seeds.append(new_color_seed) normalized_color_seeds = \ [color_seed * (1.0/color_resolution) for color_seed in color_seeds] light_color_hls = \ (normalized_color_seeds[0], 0.9, normalized_color_seeds[1]) dark_color_hls = \ (normalized_color_seeds[2], 0.3, normalized_color_seeds[3]) self.light_color = colorsys.hls_to_rgb(*light_color_hls) '''A light color in RGB. (e.g. `(0.98, 0.86, 0.81)`.)''' self.dark_color = colorsys.hls_to_rgb(*dark_color_hls) '''A dark color in RGB. (e.g. `(0.58, 0.01, 0.35)`.)'''
def _parse_hsl_color(color): """ Parse a CSS color string that starts with the 'h' character. """ float_ = float min_ = min max_ = max match = _HSL_RE.match(color) if match is not None: hs, ss, ls = match.groups() h = ((float_(hs) % 360.0 + 360.0) % 360.0) / 360.0 s = max_(0.0, min_(100.0, float_(ss))) / 100.0 l = max_(0.0, min_(100.0, float_(ls))) / 100.0 r, g, b = hls_to_rgb(h, l, s) return (r, g, b, 1.0) match = _HSLA_RE.match(color) if match is not None: hs, ss, ls, as_ = match.groups() h = ((float_(hs) % 360.0 + 360.0) % 360.0) / 360.0 s = max_(0.0, min_(100.0, float_(ss))) / 100.0 l = max_(0.0, min_(100.0, float_(ls))) / 100.0 a = max_(0.0, min_(1.0, float_(as_))) r, g, b = hls_to_rgb(h, l, s) return (r, g, b, a)
def __init__(self, persistent): assert isinstance(persistent, Persistent) import human_names color_resolution = 100 u = int(persistent._CrossProcessPersistent__uuid) (u, human_name_seed) = divmod(u, 5494) self.human_name = human_names.name_list[human_name_seed] color_seeds = [] for i in range(4): (u, new_color_seed) = divmod(u, color_resolution) color_seeds.append(new_color_seed) normalized_color_seeds = \ [color_seed * (1.0/color_resolution) for color_seed in color_seeds] light_color_hls = (normalized_color_seeds[0], 0.9, normalized_color_seeds[1]) dark_color_hls = (normalized_color_seeds[2], 0.3, normalized_color_seeds[3]) self.light_color = colorsys.hls_to_rgb(*light_color_hls) self.dark_color = colorsys.hls_to_rgb(*dark_color_hls)
def value_to_rgb(self, value, htmlhex=False, max_rgb_value=255): """ :param value: float value to convert to RGB color :param htmlhex: toggle to return value as html formatted hex, ex: '#FFFFFF' :returns: RGB color as tuple or string convert the given float value to rgb color """ # flooring value to the limits of the legend if value < self.minimum_value: value = self.minimum_value elif value > self.maximum_value: value = self.maximum_value # hsl is used because it is easier to 'rotate' evenly to another color on the spectrum h, s, l = self.value_to_hsl(value) # adjust range to be from 0 to 1 change to hls for use with hls_to_rgb() hls = (h / 360.0, l / 100.0, s / 100.0) # covert to rgb if max_rgb_value == 255: # --> adjust values from 0 to 1, to 0 to 255 rgb = [int(i * 255) for i in hls_to_rgb(*hls)] else: rgb = hls_to_rgb(*hls) if htmlhex: rgb = "#" + "".join("{:02x}".format(i) for i in rgb) return rgb
def darken(rgb_hex): # Split into r, g, and b whilst converting to decimal values r_var = int(list(rgb_hex)[0]+list(rgb_hex)[1], 16)/255.0 g_var = int(list(rgb_hex)[2]+list(rgb_hex)[3], 16)/255.0 b_var = int(list(rgb_hex)[4]+list(rgb_hex)[5], 16)/255.0 # Converts to hsl h_var = round(rgb_to_hls(r_var, g_var, b_var)[0]*255) l_var = round(rgb_to_hls(r_var, g_var, b_var)[1]*255) s_var = round(rgb_to_hls(r_var, g_var, b_var)[2]*255) # Makes lighter code if l_var < 10: l2_var = 0 else: l2_var = l_var-10 r2_var = round(hls_to_rgb(h_var/255.0, l2_var/255.0, s_var/255.0)[0]*255) g2_var = round(hls_to_rgb(h_var/255.0, l2_var/255.0, s_var/255.0)[1]*255) b2_var = round(hls_to_rgb(h_var/255.0, l2_var/255.0, s_var/255.0)[2]*255) if len(hex(r2_var)[2:]) == 1: r_hex = "0"+hex(r2_var)[2:] else: r_hex = hex(r2_var)[2:] if len(hex(g2_var)[2:]) == 1: g_hex = "0"+hex(g2_var)[2:] else: g_hex = hex(g2_var)[2:] if len(hex(b2_var)[2:]) == 1: b_hex = "0"+hex(b2_var)[2:] else: b_hex = hex(b2_var)[2:] return r_hex+g_hex+b_hex # the lighter code
def rgb_color_variants(self,stat_dict): n_samples=0 sample_names=[] for fam,obj in stat_dict.iteritems(): if len(obj.samples)>n_samples: n_samples=len(obj.samples) for sample in obj.samples.iterkeys(): if sample not in sample_names: sample_names.append(sample) assert n_samples == len(sample_names) #iterate over samples -> color_map rgbs={} i=1 for sample in sample_names: rgbs[sample]={} h=1.*(i/n_samples) h=float(h)/2. l=[0.1,0.4,0.7] rgbs[sample]["pathogen"]=colorsys.hls_to_rgb(h,l[0],1.0) rgbs[sample]["ambiguous"]=colorsys.hls_to_rgb(h,l[1],1.0) rgbs[sample]["human"]=colorsys.hls_to_rgb(h,l[2],1.0) i+=1 return rgbs
def create_test_image(block_width=7, block_height=4, h_blocks=4, v_blocks=6, as_string=True): width, height = block_width * h_blocks, block_height * v_blocks block_count = h_blocks * v_blocks hue_values = [*linspace(block_count, endpoint=False)] light_values = [*linspace(block_width + 2)][1:-1] # remove first and last item sat_values = [*linspace(block_height, 1, 0, endpoint=False)] img_string = b'' img_list = [] for j in range(v_blocks): for l in range(block_height): sat = sat_values[l] for i in range(h_blocks): hue = hue_values[j * h_blocks + i] for k in range(block_width): light = light_values[k] rgb = hls_to_rgb(hue, light, sat) r, g, b = round(rgb[0] * 255), round(rgb[1] * 255), round(rgb[2] * 255) img_list.append((r, g, b)) img_string += bytes([r]) # red img_string += bytes([g]) # green img_string += bytes([b]) # blue for j in range(block_height): for i in range(width): rgb = hls_to_rgb(0, i / (width - 1), 0) light = round(rgb[0] * 255) img_list.append((light, light, light)) img_string += bytes([light]) * 3 if as_string: return img_string, width, height+block_height return img_list, width, height+block_height
def color_theme_bg(itemclass, rank): br, bg, bb = colorsys.hls_to_rgb( class2hue[itemclass], rank/3+0.6, 0.7) fr, fg, fb = colorsys.hls_to_rgb( 0, rank/2, 0.0) return {'bg':"#%02x%02x%02x" % (int(br*256), int(bg*256), int(bb*256)), 'fg':"#%02x%02x%02x" % (int(fr*256), int(fg*256), int(fb*256))}
def get_color_pallete(c): """ Given a color c(rgb) return a new dark and light color(rgb). """ hls_d = rgb_to_hls(c[0]/255., c[1]/255., c[2]/255.) # Magic numbers are the diff from hls(DARK) and hls(LIGHT). hls = (hls_d[0] - 0.04385, hls_d[1] + 0.27059, hls_d[2]) new_dark = scrub_rgb(hls_to_rgb(hls_d[0], hls_d[1], hls_d[2])) new_light = scrub_rgb(hls_to_rgb(hls[0], hls[1], hls[2])) return new_light, new_dark
def generate_color(type): if type == "street": color = hls_to_rgb( uniform(0.55, 0.60), uniform(0.55, 0.60), uniform(0.25, 0.35) ) return color if type == "plot": color = hls_to_rgb( uniform(0.40, 0.50), uniform(0.10, 0.40), uniform(0.30, 0.40) ) return color
def get_rgb_color(scope_defined_color_raw, scheme): scope_defined_color = scope_defined_color_raw.strip() if scope_defined_color.startswith("#"): return ColorSchemeEditor.full_hex_chars(scope_defined_color.strip()) elif scope_defined_color.startswith("var("): return ColorSchemeEditor.get_rgb_color(scheme["variables"][scope_defined_color[4:-1]], scheme) elif scope_defined_color.startswith("rgb("): #rgb(255, 0, 0) rgb_match = re.match("rgb\(\s*(\d+),\s*(\d+),\s*(\d+)\s*\)", scope_defined_color) red = int(rgb_match.group(1)) green = int(rgb_match.group(2)) blue = int(rgb_match.group(3)) return "#{0:0>2X}{1:0>2X}{2:0>2X}00".format(red, green, blue) elif scope_defined_color.startswith("rgba("): #rgba(255, 0, 0, 0.5) rgba_match = re.match("rgb\(\s*(\d+),\s*(\d+),\s*(\d+)\s*,\s*(1(\.0+)?|0(\.\d+)?)\s*\)", scope_defined_color) red = int(rgba_match.group(1)) green = int(rgba_match.group(2)) blue = int(rgba_match.group(3)) alpha = int(float(rgba_match.group(4)) * 255) return "#{0:0>2X}{1:0>2X}{2:0>2X}{3:0>2X}".format(red, green, blue, alpha) elif scope_defined_color.startswith("hsl("): #hsl(0, 100%, 100%) hsl_match = re.match("hsl\(\s*(\d+),\s*(\d+)%,\s*(\d+)%\s*\)", scope_defined_color) hue = float(hsl_match.group(1)) / 360 saturation = float(hsl_match.group(2)) / 100 lightness = float(hsl_match.group(3)) / 100 red, green, blue = colorsys.hls_to_rgb(hue, lightness, saturation) return "#{0:0>2X}{1:0>2X}{2:0>2X}00".format(int(red * 255), int(green * 255), int(blue * 255)) elif scope_defined_color.startswith("hsla("): #hsla(0, 100%, 100%, 0.5) hsla_match = re.match("hsl\(\s*(\d+),\s*(\d+)%,\s*(\d+)%,\s*(1(\.0+)?|0(\.\d+)?)\s*\)", scope_defined_color) hue = float(hsla_match.group(1)) / 360 saturation = float(hsla_match.group(2)) / 100 lightness = float(hsla_match.group(3)) / 100 alpha = int(float(hsla_match.group(4)) * 255) red, green, blue = colorsys.hls_to_rgb(hue, lightness, saturation) return "#{0:0>2X}{1:0>2X}{2:0>2X}{3:0>2X}".format(int(red * 255), int(green * 255), int(blue * 255), alpha) elif scope_defined_color.startswith("color("): # can have all of the above plus blend, blenda, alpha, a. Blend percent is percent of first color contents, modifier = ColorSchemeEditor.get_color_prefix(scope_defined_color[6:-1]) color = ColorSchemeEditor.get_rgb_color(contents, scheme) if len(modifier) == 0: return color else: return ColorSchemeEditor.modify_color(ColorSchemeEditor.full_hex_chars(color), modifier, scheme) else: return CSS_COLORS[scope_defined_color]
def analog_sensor_color(val): _hue_cold = 240/360.0 ## For low values _hue_hot = 0/360.0 ## For high values _delta = _hue_hot - _hue_cold _d2 = _delta * val hue = _hue_cold + _d2 import colorsys h,s,v = hue, 1.0, 1.0 rgb = colorsys.hsv_to_rgb(h, s, v) h,l,s = colorsys.rgb_to_hls(*rgb) greyscale_rgb = colorsys.hls_to_rgb(h, l, 0) #return '#%02X%02X%02X' % tuple(c*255 for c in rgb) return '#%02X%02X%02X' % tuple(c*255 for c in colorsys.hls_to_rgb(h, l*1.5, 1))
def hls_palette(n_colors=6, h=.01, l=.6, s=.65): """Get a set of evenly spaced colors in HLS hue space. h, l, and s should be between 0 and 1 Parameters ---------- n_colors : int number of colors in the palette h : float first hue l : float lightness s : float saturation Returns ------- palette : list of tuples color palette """ hues = np.linspace(0, 1, n_colors + 1)[:-1] hues += h hues %= 1 hues -= hues.astype(int) palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues] return palette
def get_color_scale(self, n, s): if s == 0: # Black - White scale = self.new_color_scale([[0, [0,0,0]], [1, [1,1,1]]], n) elif s == 1: # Black - Red - Yellow - White (STM colors) scale = self.new_color_scale([[0, [0,0,0]], [0.33, [1,0,0]], [0.67, [1,1,0]], [1, [1,1,1]]], n) elif s == 2: # Black - Green - White scale = self.new_color_scale([[0, [0,0,0]], [0.5, [0,0.9,0]], [0.75, [0.2,1.0,0.2]], [1, [1,1,1]]], n) elif s == 3: # Black - Blue - Cyan scale = self.new_color_scale([[0, [0,0,0]], [0.5, [0,0,1]], [1, [0,1,1]]], n) elif s == 4: # Hues hues = np.linspace(0.0, 1.0, n, endpoint=False) scale = ["%.3f, %.3f, %.3f" % colorsys.hls_to_rgb(h, 0.5, 1) for h in hues] elif s == 5: # Named colors scale = self.get_named_colors(n) else: scale = None return scale
def desaturate(color, prop): """Decrease the saturation channel of a color by some percent. Parameters ---------- color : matplotlib color hex, rgb-tuple, or html color name prop : float saturation channel of color will be multiplied by this value Returns ------- new_color : rgb tuple desaturated color code in RGB tuple representation """ # Check inputs if not 0 <= prop <= 1: raise ValueError("prop must be between 0 and 1") # Get rgb tuple rep rgb = mplcol.colorConverter.to_rgb(color) # Convert to hls h, l, s = colorsys.rgb_to_hls(*rgb) # Desaturate the saturation channel s *= prop # Convert back to rgb new_color = colorsys.hls_to_rgb(h, l, s) return new_color
def fromhls(self, h, l, s): """Convert to RGB from HSL.""" r, g, b = hls_to_rgb(h, l, s) self.r = int(round(r * 255)) & 0xFF self.g = int(round(g * 255)) & 0xFF self.b = int(round(b * 255)) & 0xFF
def _color_subtree(node, color=None, level=0): global colormap node.color = color max_luminosity = 0 if color is not None: hls = np.asarray(colorsys.rgb_to_hls(*color)) max_luminosity = hls[1] #luminosities = np.linspace(0.3, 0.8, len(node.children)) children_sizes = map(len, node.children) indices = np.argsort(children_sizes)[::-1] luminosities = np.linspace(max_luminosity, 0.2, len(node.children)) #for child, luminosity, offset in zip(node.children, luminosities, offsets): for idx, luminosity in zip(indices, luminosities): child = node.children[idx] if level <= min_level: color = next(colormap) _color_subtree(child, color, level+1) else: hls = np.asarray(colorsys.rgb_to_hls(*color)) #if hls[1] > 0.8: # hls[1] -= 0.3 #elif hls[1] < 0.3: # hls[1] += 0.3 rbg = colorsys.hls_to_rgb(hls[0], luminosity, hls[2]) _color_subtree(child, np.asarray(rbg), level+1)
def convert_color(c, to_schema='rgb'): """ Convert a color to another schema. """ color_attrs = c.keys() # RGB to x if ''.join(sorted(color_attrs)) == 'bgr': if to_schema == 'rgb': return c elif to_schema == 'hsv': hsv = colorsys.rgb_to_hsv(c['r']/255.0, c['g']/255.0, c['b']/255.0) return dict(zip(['h', 's', 'v'], hsv)) elif to_schema == 'hls': hsv = colorsys.rgb_to_hls(c['r']/255.0, c['g']/255.0, c['b']/255.0) return dict(zip(['h', 'l', 's'], hsv)) # HSV to x elif ''.join(sorted(color_attrs)) == 'hsv': from_schema = 'hsv' if to_schema == 'hsv': return c elif to_schema == 'rgb': rgb = colorsys.hsv_to_rgb(c['h'], c['s'], c['v']) return dict(zip(['r', 'g', 'b'], [int(255 * attr) for attr in rgb])) # HLS to x elif ''.join(sorted(color_attrs)) == 'hls': from_schema = 'hls' if to_schema == 'hls': return c elif to_schema == 'rgb': rgb = colorsys.hls_to_rgb(c['h'], c['l'], c['s']) return dict(zip(['r', 'g', 'b'], [int(255 * attr) for attr in rgb]))
def set_hls_values(color, h=None, l=None, s=None): """Independently manipulate the h, l, or s channels of a color. Parameters ---------- color : matplotlib color hex, rgb-tuple, or html color name h, l, s : floats between 0 and 1, or None new values for each channel in hls space Returns ------- new_color : rgb tuple new color code in RGB tuple representation """ # Get rgb tuple representation rgb = mplcol.colorConverter.to_rgb(color) vals = list(colorsys.rgb_to_hls(*rgb)) for i, val in enumerate([h, l, s]): if val is not None: vals[i] = val rgb = colorsys.hls_to_rgb(*vals) return rgb
def _color_subtree(node, color=None, level=0, max_lum=0.9, min_lum=0.1): global colormap node.color = color #max_lum = 1 if color is not None: hls = np.asarray(colorsys.rgb_to_hls(*color)) max_lum = min(max_lum, hls[1] + 0.2) min_lum = max(min_lum, hls[1] - 0.2) children_sizes = map(len, node.children) indices = np.argsort(children_sizes)[::-1] luminosities = np.linspace(max_lum, min_lum, len(node.children)+1) #for child, luminosity, offset in zip(node.children, luminosities, offsets): for i, idx in enumerate(indices): child = node.children[idx] if level <= min_level: color = next(colormap) _color_subtree(child, color, level+1) else: hls = np.asarray(colorsys.rgb_to_hls(*color)) #rbg = colorsys.hls_to_rgb(hls[0], (luminosities[i]+luminosities[i+1])/2, hls[2]) rbg = colorsys.hls_to_rgb(hls[0], luminosities[i+1], hls[2]) _color_subtree(child, np.asarray(rbg), level+1, luminosities[i], luminosities[i+1])
def hsl_to_rgb(hue, saturation, lightness): """Takes a colour in HSL format and produces an RGB string in the form #RRGGBB. :param hue: The Hue value (between 0 and 360). :param saturation: The Saturation value (between 0 and 100). :param lightness: The Lightness value (between 0 and 100). :raises ValueError: if any of the three parameters are outside their \ bounds.""" if not isinstance(hue, int) and not isinstance(hue, float): raise TypeError("hue must be numeric, not '%s'" % hue) if not isinstance(saturation, int) and not isinstance(saturation, float): raise TypeError("saturation must be numeric, not '%s'" % saturation) if not isinstance(lightness, int) and not isinstance(lightness, float): raise TypeError("lightness must be numeric, not '%s'" % lightness) if not (0 <= hue <= 360): raise ValueError("hue must be between 0 and 360, not '%s'" % str(hue)) if not (0 <= saturation <= 100): raise ValueError( "saturation must be between 0 and 100, not '%s'" % str(saturation) ) if not (0 <= lightness <= 100): raise ValueError( "lightness must be between 0 and 100, not '%s'" % str(lightness) ) r, g, b = colorsys.hls_to_rgb(hue / 360, lightness / 100, saturation / 100) return ("#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255))).upper()
def create_html_data(tags, size=(500,500), layout=LAYOUT_MIX, fontname=DEFAULT_FONT, rectangular=False): """ Create data structures to be used for HTML tag clouds. """ sizeRect, tag_store = _draw_cloud(tags, layout, size=size, fontname=fontname, rectangular=rectangular) tag_store = sorted(tag_store, key=lambda tag: tag.tag['size']) tag_store.reverse() data = { 'css': {}, 'links': [] } color_map = {} for color_index, tag in enumerate(tags): if not color_map.has_key(tag['color']): color_name = "c%d" % color_index hslcolor = colorsys.rgb_to_hls(tag['color'][0] / 255.0, tag['color'][1] / 255.0, tag['color'][2] / 255.0) lighter = hslcolor[1] * 1.4 if lighter > 1: lighter = 1 light = colorsys.hls_to_rgb(hslcolor[0], lighter, hslcolor[2]) data['css'][color_name] = ('#%02x%02x%02x' % tag['color'], '#%02x%02x%02x' % (light[0] * 255, light[1] * 255, light[2] * 255)) color_map[tag['color']] = color_name for stag in tag_store: metrics = stag.font.metrics(stag.tag['tag']) line_offset = 0 if min([f[2] for f in metrics]) < stag.font.get_descent() * 0.1: line_offset = stag.font.get_linesize() - 1.95 * (stag.font.get_ascent() + abs(stag.font.get_descent() * 0.9) - stag.rect.height) else: line_offset = stag.font.get_linesize() - 1.95 * (stag.font.get_ascent() - stag.rect.height) tag = { 'tag': stag.tag['tag'], 'cls': color_map[stag.tag['color']], 'top': stag.rect.y - 10, 'left': stag.rect.x, 'size': stag.tag['size'] - 6, 'height': stag.rect.height * 1.15, 'width': stag.rect.width, 'lh': line_offset } data['links'].append(tag) data['size'] = (sizeRect.w, sizeRect.h * 1.15) return data
def colorize(nns): N = len(nns) HLS_tuples = [(x*1.0/N, 0.5, 0.6) for x in range(N)] RGB_tuples = [colorsys.hls_to_rgb(*hls) for hls in HLS_tuples] HEX_tuples = ['%02x%02x%02x' % (int(r*256), int(g*256), int(b*256)) for (r, g, b) in RGB_tuples] return HEX_tuples
def get_color_for(val): """Get proper color to render the occ values""" color = 'green' if val != -1: rgb = hls_to_rgb(0, (100 - val) / 100.0, 1) color = '#%0.2X%0.2X%0.2X' % (int(255 * rgb[0]), int(255 * rgb[1]), int(255 * rgb[2])) return color
def ascii_and_color_for_region(region, luminances): # Do a simple average of HSL. # Use the L to determine which character to use # Use RGB average for the actual letter color # This should give a mix of whitespace and color to represent the cell source = region.load() total_h, total_s, total_l = (0,0,0) total_r, total_g, total_b = (0,0,0) region_x, region_y = region.size total_pixels = region_x * region_y for x in range(region_x): for y in range(region_y): r, g, b, a = source[x,y] h, l, s = rgb_to_hls(r/255, g/255, b/255) total_h += h total_l += l total_s += s total_r += r total_g += g total_b += b avg_h, avg_l, avg_s = (total_h/total_pixels, total_l/total_pixels, total_s/total_pixels) letter = ascii_for_luminance(avg_l, luminances) color_percentage = hls_to_rgb(avg_h, avg_l, avg_s) return (letter, (total_r/total_pixels, total_g/total_pixels, total_b/total_pixels))
def get_rgb_from_hue_spectrum(percent, start_hue, end_hue): # spectrum is red (0.0), orange, yellow, green, blue, indigo, violet (0.9) hue = percent * (end_hue - start_hue) + start_hue lightness = 0.7 saturation = 0.5 r, g, b = colorsys.hls_to_rgb(hue, lightness, saturation) return r * 255, g * 255, b * 255
def get_cont_col(col): (h, l, s) = colorsys.rgb_to_hls(int(col[1:3], 16)/255.0, int(col[3:5], 16)/255.0, int(col[5:7], 16)/255.0) l1 = 1 - l if abs(l1 - l) < .15: l1 = .15 (r, g, b) = colorsys.hls_to_rgb(h, l1, s) return tohex(int(r * 255), int(g * 255), int(b * 255)) # true complementary
def write_to_strip(self): # GPIO.setup(self.dancer.channel_pins[0], GPIO.OUT) # GPIO.setup(self.dancer.channel_pins[1], GPIO.OUT) # GPIO.output(self.dancer.channel_pins[1], False) # GPIO.output(self.dancer.channel_pins[0], True) for si in range(self.dancer.num_channels): # print si for ch_ri, ri in enumerate(self.dancer.channel_rays[si]): # print 'ray', ch_ri, ri for index in range(self.ray_length): rgb = map(clamp_value, hls_to_rgb(self.pixel_matrix[ri][index]['h'] % 1.0, self.pixel_matrix[ri][index]['l'], self.pixel_matrix[ri][index]['s'])) # offset = self.pixel_to_strip_map[ci][ri][index] * 4 + 1 pixel = ch_ri * self.dancer.ray_length + self.dancer.ray_offsets[ri] + index offset = pixel * 4 + 1 # print pixel self.raw_arrays[si][offset] = int(rgb[2] * 255) self.raw_arrays[si][offset + 1] = int(rgb[1] * 255) self.raw_arrays[si][offset + 2] = int(rgb[0] * 255) # set channel select pins, False is enable for ch in range(self.dancer.num_channels): if ch == si: GPIO.output(self.dancer.channel_pins[ch], False) else: GPIO.output(self.dancer.channel_pins[ch], True) # time.sleep(0.1) self.strips[si].show(self.raw_arrays[si])
def to_rgb( scale ): ''' convert an hsl or numeric rgb color scale to string rgb color scale. ie, [ "hsl(360,100,100)", "hsl(360,100,100)", "hsl(360,100,100)" ] --> [ "rgb(255, 255, 255)", "rgb(255, 255, 255)", "rgb(255, 255, 255)" ] ''' rgb = [] s_t = scale_type(scale) if s_t == 'rgb': return scale elif s_t == 'numeric': for ea in scale: rgb.append( 'rgb'+str(ea) ) return rgb elif s_t == 'hsl': numeric_hsl_scale = [] for s in scale: s = s[s.find("(")+1:s.find(")")].replace(' ','').replace('%','').split(',') numeric_hsl_scale.append( ( float(s[0]), float(s[1]), float(s[2]) ) ) scale = numeric_hsl_scale for ea in scale: h,s,l = [ float(x) for x in ea ] r,g,b = colorsys.hls_to_rgb(h/360.0, l/100.0, s/100.0) r,g,b = [ str(int(round(x*255.0))) for x in (r,g,b) ] rgb_str = 'rgb(' + ', '.join([r,g,b]) + ')' rgb.append( rgb_str ) return rgb
def color_ramp(number_of_colour): """Generate list of color in hexadecimal. This will generate colors using hsl model by playing around with the hue see: https://coderwall.com/p/dvsxwg/smoothly-transition-from-green-to-red :param number_of_colour: The number of intervals between R and G spectrum. :type number_of_colour: int :returns: List of color. :rtype: list """ if number_of_colour < 1: raise Exception('The number of colours should be > 0') colors = [] if number_of_colour == 1: hue_interval = 1 else: hue_interval = 1.0 / (number_of_colour - 1) for i in range(number_of_colour): hue = (i * hue_interval) / 3 light = 127.5 saturation = -1.007905138339921 rgb = colorsys.hls_to_rgb(hue, light, saturation) hex_color = '#%02x%02x%02x' % (int(rgb[0]), int(rgb[1]), int(rgb[2])) colors.append(hex_color) return colors
def hsla(h, s, l, a): return rgba(*colorsys.hls_to_rgb(h, l, s), a)
def hsl(h, s, l): return rgb(*colorsys.hls_to_rgb(h, l, s))
def make_vott_output(all_predictions, output_location_param, user_folders, image_loc_param, blob_credentials=None, tag_names: List[str] = ["stamp"], tag_colors: List[str] = "#ed1010", max_tags_per_pixel=None): if max_tags_per_pixel is not None: max_tags_per_pixel = int(max_tags_per_pixel) tag_names = remove_bkg_class_name(tag_names) # The tag_colors list generates random colors for each tag. To ensure that these colors stand out / are easy to see on a picture, the colors are generated # in the hls format, with the random numbers biased towards a high luminosity (>=.8) and saturation (>=.75). if tag_colors is None: tag_colors = [ '#%02x%02x%02x' % (int(256 * r), int(256 * g), int(256 * b)) for r, g, b in [ colorsys.hls_to_rgb(random.random(), 0.8 + random.random() / 5.0, 0.75 + random.random() / 4.0) for _ in tag_names ] ] using_blob_storage = blob_credentials is not None dict_predictions_per_folder = {} #defaultdict(list) i = 0 n_err = 0 for prediction in all_predictions[:]: #print(i) image_loc = get_image_loc(prediction, user_folders, image_loc_param) output_location = get_output_location(prediction, user_folders, output_location_param) if output_location not in dict_predictions_per_folder: output_location.mkdir(parents=True, exist_ok=True) dict_predictions_per_folder[output_location] = [] print("Created dir ", str(output_location)) if using_blob_storage: blob_dest = str(output_location / prediction[0][FILENAME_LOCATION]) if image_loc: blob_name = image_loc + "/" + prediction[0][FILENAME_LOCATION] else: blob_name = prediction[0][FILENAME_LOCATION] if not butils.attempt_get_blob(blob_credentials, blob_name, blob_dest): all_predictions.remove(prediction) n_err = n_err + 1 continue else: shutil.copy( os.path.join(image_loc, prediction[0][FILENAME_LOCATION]), str(output_location)) dict_predictions_per_folder[output_location].append(prediction) i = i + 1 print("Dowloaded {0} files. Number of errors: {1}".format(i, n_err)) #TBD: enum through dict and make json per folder! for output_location, folder_predictions in dict_predictions_per_folder.items( ): folder_predictions.sort(key=lambda x: x[0][FILENAME_LOCATION]) dirjson = {} dirjson["frames"] = {} for i, predictions in enumerate(folder_predictions): all_frames = [] file_name = "" set_predictions = defaultdict(list) if max_tags_per_pixel is None: for prediction in predictions: x_1, x_2, y_1, y_2, height, width = map( float, prediction[TAG_STARTING_LOCATION:TAG_ENDING_LOCATION + 1]) if prediction[TAG_LOCATION] != "NULL" and ( x_1, x_2, y_1, y_2) != (0, 0, 0, 0): x_1 = int(x_1 * width) x_2 = int(x_2 * width) y_1 = int(y_1 * height) y_2 = int(y_2 * height) set_predictions[(x_1, x_2, y_1, y_2, height, width)].append( prediction[TAG_LOCATION]) file_name = prediction[FILENAME_LOCATION] else: if predictions: num_tags = np.zeros((int(predictions[0][HEIGHT_LOCATION]), int(predictions[0][WIDTH_LOCATION])), dtype=int) for prediction in sorted( predictions, key=lambda x: float(x[TAG_CONFIDENCE_LOCATION]), reverse=True): x_1, x_2, y_1, y_2, height, width = map( float, prediction[ TAG_STARTING_LOCATION:TAG_ENDING_LOCATION + 1]) if prediction[TAG_LOCATION] != "NULL" and ( x_1, x_2, y_1, y_2) != (0, 0, 0, 0): x_1 = int(x_1 * width) x_2 = int(x_2 * width) y_1 = int(y_1 * height) y_2 = int(y_2 * height) if np.amax(num_tags[y_1:y_2, x_1:x_2]) < max_tags_per_pixel: num_tags[y_1:y_2, x_1:x_2] += 1 set_predictions[(x_1, x_2, y_1, y_2, height, width)].append( prediction[TAG_LOCATION]) file_name = prediction[FILENAME_LOCATION] for j, (coordinates, tags) in enumerate(set_predictions.items(), 1): # filename,tag,x1,x2,y1,y2,true_height,true_width,image_directory x_1, x_2, y_1, y_2, height, width = coordinates curframe = {} curframe["x1"] = x_1 curframe["y1"] = y_1 curframe["x2"] = x_2 curframe["y2"] = y_2 curframe["id"] = j curframe["width"] = width curframe["height"] = height curframe["type"] = "Rectangle" curframe["tags"] = tags curframe["name"] = j all_frames.append(curframe) dirjson["frames"][file_name] = all_frames dirjson["framerate"] = "1" dirjson["inputTags"] = ",".join(tag_names) dirjson["suggestiontype"] = "track" dirjson["scd"] = False dirjson["tag_colors"] = tag_colors with open(str(output_location) + ".json", "w") as json_out: json.dump(dirjson, json_out, sort_keys=True)
def asRGB(self): h, s, l = self.get_values() return tuple(round(i * 255) for i in colorsys.hls_to_rgb(h, l, s))
def update_event(self, inp=-1): self.set_output_val( 0, colorsys.hls_to_rgb(self.input(0), self.input(1), self.input(2)))
#!/usr/bin/env python2 # # This takes the output of extract_nexrad and generates images. # It isn't very smart at the moment and won't draw anything # until all input has been consumed, so it's not very useful # for realtime continuous generation of maps. # import sys, math import cairo, colorsys intensities = { 0: colorsys.hls_to_rgb(240.0 / 360.0, 0.15, 1.0), 1: colorsys.hls_to_rgb(240.0 / 360.0, 0.2, 1.0), 2: colorsys.hls_to_rgb(200.0 / 360.0, 0.4, 1.0), 3: colorsys.hls_to_rgb(160.0 / 360.0, 0.4, 1.0), 4: colorsys.hls_to_rgb(120.0 / 360.0, 0.5, 1.0), 5: colorsys.hls_to_rgb(80.0 / 360.0, 0.5, 1.0), 6: colorsys.hls_to_rgb(40.0 / 360.0, 0.6, 1.0), 7: colorsys.hls_to_rgb(0.0 / 360.0, 0.5, 1.0), 8: colorsys.hls_to_rgb(0.0 / 360.0, 0.75, 1.0), 9: colorsys.hls_to_rgb(60.0 / 360.0, 0.5, 1.0), 10: colorsys.hls_to_rgb(60.0 / 360.0, 0.7, 1.0), 11: colorsys.hls_to_rgb(0.0 / 360.0, 0.25, 1.0), 12: colorsys.hls_to_rgb(0.0 / 360.0, 0.7, 1.0), 13: colorsys.hls_to_rgb(300.0 / 360.0, 0.25, 1.0), 14: colorsys.hls_to_rgb(180.0 / 360.0, 0.25, 1.0), 15: colorsys.hls_to_rgb(120.0 / 360.0, 0.7, 1.0) }
import colorsys # It turns out Python already does HSL -> RGB! def trim(s): return s if not s.endswith('.0') else s[:-2] print('[') print(',\n'.join( '"hsl%s(%s, %s%%, %s%%%s)", [%s, %s, %s, %s]' % (('a' if a is not None else '', h, trim(str(s / 10.)), trim(str(l / 10.)), ', %s' % a if a is not None else '') + tuple( trim(str(round(v, 10))) for v in colorsys.hls_to_rgb(h / 360., l / 1000., s / 1000.)) + (a if a is not None else 1, )) for a in [None, 1, .2, 0] for l in range(0, 1001, 125) for s in range(0, 1001, 125) for h in range(0, 360, 30))) print(']')
def fill_gfx_commands_for_heatmap(gfx_commands, locs_and_values, board, normalization_div, is_percent): divisor = 1.0 if normalization_div == "max": max_abs_value = max(abs(value) for (loc, value) in locs_and_values) divisor = max(0.0000000001, max_abs_value) #avoid divide by zero elif normalization_div is not None: divisor = normalization_div #Caps value at 1.0, using an asymptotic curve def loose_cap(x): def transformed_softplus(x): return -math.log(math.exp(-(x - 1.0) * 8.0) + 1.0) / 8.0 + 1.0 base = transformed_softplus(0.0) return (transformed_softplus(x) - base) / (1.0 - base) #Softly curves a value so that it ramps up faster than linear in that range def soft_curve(x, x0, x1): p = (x - x0) / (x1 - x0) def curve(p): return math.sqrt(p + 0.16) - 0.4 p = curve(p) / curve(1.0) return x0 + p * (x1 - x0) for (loc, value) in locs_and_values: if loc != Board.PASS_LOC: value = value / divisor if value < 0: value = -value huestart = 0.50 huestop = 0.86 else: huestart = -0.02 huestop = 0.45 value = loose_cap(value) def lerp(p, x0, x1, y0, y1): return y0 + (y1 - y0) * (p - x0) / (x1 - x0) if value <= 0.04: hue = huestart lightness = 0.5 saturation = value / 0.04 (r, g, b) = colorsys.hls_to_rgb((hue + 1) % 1, lightness, saturation) elif value <= 0.70: # value = soft_curve(value,0.04,0.70) hue = lerp(value, 0.04, 0.70, huestart, huestop) val = 1.0 saturation = 1.0 (r, g, b) = colorsys.hsv_to_rgb((hue + 1) % 1, val, saturation) else: hue = huestop lightness = lerp(value, 0.70, 1.00, 0.5, 0.95) saturation = 1.0 (r, g, b) = colorsys.hls_to_rgb((hue + 1) % 1, lightness, saturation) r = ("%02x" % int(r * 255)) g = ("%02x" % int(g * 255)) b = ("%02x" % int(b * 255)) gfx_commands.append("COLOR #%s%s%s %s" % (r, g, b, str_coord(loc, board))) locs_and_values = sorted(locs_and_values, key=lambda loc_and_value: loc_and_value[1]) locs_and_values_rev = sorted(locs_and_values, key=lambda loc_and_value: loc_and_value[1], reverse=True) texts = [] texts_rev = [] maxlen_per_side = 10 if len(locs_and_values) > 0 and locs_and_values[0][1] < 0: maxlen_per_side = 5 for i in range(min(len(locs_and_values), maxlen_per_side)): (loc, value) = locs_and_values[i] if is_percent: texts.append("%s %4.1f%%" % (str_coord(loc, board), value * 100)) else: texts.append("%s %.3f" % (str_coord(loc, board), value)) texts.reverse() for i in range(min(len(locs_and_values_rev), maxlen_per_side)): (loc, value) = locs_and_values_rev[i] if is_percent: texts_rev.append("%s %4.1f%%" % (str_coord(loc, board), value * 100)) else: texts_rev.append("%s %.3f" % (str_coord(loc, board), value)) gfx_commands.append("TEXT " + ", ".join(texts_rev + texts))
def rgb_add_hls(source, h=0, l=0, s=0): c = colorsys.rgb_to_hls(source[0] / 255, source[1] / 255, source[2] / 255) colour = colorsys.hls_to_rgb(c[0] + h, min(max(c[1] + l, 0), 1), min(max(c[2] + s, 0), 1)) return [int(colour[0] * 255), int(colour[1] * 255), int(colour[2] * 255), source[3]]
def fromhsl(cls, hsla): h, s, l, alpha = hsla r, g, b = colorsys.hls_to_rgb(h, l, s) return cls(255 * r, 255 * g, 255 * b, alpha)
def get_saturated_color(self, color): """Increase the saturation of the current color.""" hls = colorsys.rgb_to_hls(color[0] / 255, color[1] / 255, color[2] / 255) rgb_saturated = colorsys.hls_to_rgb(hls[0], 0.5, 0.5) return [int(rgb_saturated[0] * 255), int(rgb_saturated[1] * 255), int(rgb_saturated[2] * 255)]
def smooth_rainbow(num): time.sleep(.01) return (num + 1) % 360 def random_color(num): time.sleep(.25) return random.randrange(0, 360) def bold_rainbow(num): time.sleep(.6) return (num + 60) % 360 color = 0 while True: color = smooth_rainbow(color) brightness = 1 r, g, b = colorsys.hls_to_rgb(color / 360, .5, 1) red, green, blue = (r * 254 * brightness) // 1 + 1, ( g * 254 * brightness) // 1 + 1, (b * 254 * brightness) // 1 + 1 requests.post(url + '/rgb', json={ 'red': red, 'green': green, 'blue': blue })
def hls2hex(h, l, s): ''' Converts from HLS to RGB ''' return '#%02x%02x%02x' % tuple( map(lambda x: int(x * 255), hls_to_rgb(h, l, s)))
def hsl_to_rgb(h, s, l): h /= 360.0 s /= 100.0 l /= 100.0 # noqa return hls_to_rgb(h, l, s)
def from_hsla(hsla: HSLA): (r, g, b) = colorsys.hls_to_rgb(hsla.hue / 360, hsla.lightness / 100, hsla.saturation / 100) return RGBA(r * 255, g * 255, b * 255, hsla.a)
def random_color(): h,s,l = random(), 0.5 + random()/2.0, 0.6 + random()/10.0 r,g,b = colorsys.hls_to_rgb(h,l,s) return r, g, b, 0.5
def hls_to_rgb(h, l, s): colour = colorsys.hls_to_rgb(h, l, s) return [int(colour[0] * 255), int(colour[1] * 255), int(colour[2] * 255), 255]
while True: read, _, _ = select.select([sys.stdin, port], [], [], 0.01) if port in read: r = port.read() print("\rStatus bits: " + bin(r[0]).replace("0b", "").zfill(8) + "\r", end="") if sys.stdin in read: r = sys.stdin.read(1) if r == "1": send([0x02, 0xe8, 0x03]) elif r == "2": send([0x12, 0xe8, 0x03]) # Run a color sweep light show on the LEDs color = list(map(lambda x: int(x*255), colorsys.hls_to_rgb(a/512, 0.03, 1))) send([0x01] + color) color = list(map(lambda x: int(x*255), colorsys.hls_to_rgb(((a + 256) % 512)/512, 0.03, 1))) send([0x11] + color) a += 1 if a == 512: a = 0 except KeyboardInterrupt: pass finally: # Reset previous terminal settings termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_attr) print("\x1b[?25h")
def getrgb(color): """ Convert a color string to an RGB tuple. If the string cannot be parsed, this function raises a :py:exc:`ValueError` exception. .. versionadded:: 1.1.4 :param color: A color string :return: ``(red, green, blue[, alpha])`` """ color = color.lower() rgb = colormap.get(color, None) if rgb: if isinstance(rgb, tuple): return rgb colormap[color] = rgb = getrgb(rgb) return rgb # check for known string formats if re.match("#[a-f0-9]{3}$", color): return (int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16)) if re.match("#[a-f0-9]{4}$", color): return ( int(color[1] * 2, 16), int(color[2] * 2, 16), int(color[3] * 2, 16), int(color[4] * 2, 16), ) if re.match("#[a-f0-9]{6}$", color): return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)) if re.match("#[a-f0-9]{8}$", color): return ( int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16), int(color[7:9], 16), ) m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color) if m: return (int(m.group(1)), int(m.group(2)), int(m.group(3))) m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color) if m: return ( int((int(m.group(1)) * 255) / 100.0 + 0.5), int((int(m.group(2)) * 255) / 100.0 + 0.5), int((int(m.group(3)) * 255) / 100.0 + 0.5), ) m = re.match( r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color ) if m: from colorsys import hls_to_rgb rgb = hls_to_rgb( float(m.group(1)) / 360.0, float(m.group(3)) / 100.0, float(m.group(2)) / 100.0, ) return ( int(rgb[0] * 255 + 0.5), int(rgb[1] * 255 + 0.5), int(rgb[2] * 255 + 0.5), ) m = re.match( r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color ) if m: from colorsys import hsv_to_rgb rgb = hsv_to_rgb( float(m.group(1)) / 360.0, float(m.group(2)) / 100.0, float(m.group(3)) / 100.0, ) return ( int(rgb[0] * 255 + 0.5), int(rgb[1] * 255 + 0.5), int(rgb[2] * 255 + 0.5), ) m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color) if m: return (int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))) raise ValueError("unknown color specifier: %r" % color)
"#a6761d", "#666666", "#8dd3c7", "#bebada", "#fb8072", "#80b1d3", "#fdb462", "#b3de69", "#fccde5", "#d9d9d9", "#bc80bd", "#ccebc5", "#ffed6f", "#ffffb3", "#aadd88", "#889933", "#22bbcc", "#d9dbb5" ] def rgb2hex(r, g, b): return "#%02x%02x%02x" % (r * 255, g * 255, b * 255) # Generate some colors to add to the list s = .7 for l in [.70, .55]: for h in range(0, 101, 10): if h == 40: continue rgb = colorsys.hls_to_rgb(h / 100.0, l, s) COLORS.append(rgb2hex(*rgb)) class DAG: def __init__(self): self.nodes = {} class Node(object): def __init__(self): self.id = None self.label = None self.level = 0 self.parents = [] self.children = []
def random_colour(saturation, luminance): h = round(random.random(), 2) colour = colorsys.hls_to_rgb(h, luminance, saturation) return [int(colour[0] * 255), int(colour[1] * 255), int(colour[2] * 255), 255]
def rlabel(r): return Rectangle(SIZE, RGBA(hls_to_rgb(counts_hue.index[r], 0.5, 0.7)))
# create a GIFSurface instance and set the colors surface = gm.GIFSurface.from_image('./resources/bg.png') palette = [ 52, 51, 50, # wall color, the same with the blackboard's 200, 200, 200, # tree color 255, 0, 255 ] # path color for i in range(256): rgb = hls_to_rgb((i / 360.0) % 1, 0.5, 1.0) palette += [int(round(255 * x)) for x in rgb] surface.set_palette(palette) # create a maze instance and set its position in the image size = (surface.width, surface.height) mask = generate_text_mask(size, 'UST', './resources/ubuntu.ttf', 350) maze = gm.Maze(111, 67, mask=mask).scale(4).translate((75, 56)) # create an animation environment anim = gm.Animation(surface) # here `trans_index=1` is for compatible with eye of gnome in linux, # you may always use the default 0 for chrome and firefox. anim.pause(100, trans_index=1)
for i in range(0, 5): st.sidebar.write("——————Change color: ", i+1, '——————') h.append(st.sidebar.slider('Hue:', 0.0, 360.0, hsl[i][0]*360)) st.sidebar.write("Hue is ", '%.2f' % h[i], '°') l.append(st.sidebar.slider('Lightness:', 0.0, 1.0, hsl[i][1])) st.sidebar.write("Lightness is ", '{:.2%}'.format(l[i])) s.append(st.sidebar.slider('Saturation:', 0.0, 1.0, hsl[i][2])) st.sidebar.write("Saturation is ", '{:.2%}'.format(s[i])) HEX_change = [] for i in range(0, 5): rgb_change = colorsys.hls_to_rgb(h[i]/360, l[i], s[i]) r = int(rgb_change[0]*255) g = int(rgb_change[1]*255) b = int(rgb_change[2]*255) HEX_change.append('#%02X%02X%02X' % (r, g, b)) palette_images = [Image.new('RGB', (100, 100), color=item) for item in HEX_change] st.image(palette_images) st.subheader( 'Please copy the palette HEX that you are satisfied with: ') st.write(HEX_change[0], HEX_change[1], HEX_change[2], HEX_change[3], HEX_change[4])
def _hls2hex(h, l, s): return '#%02x%02x%02x' % tuple( map(lambda x: int(x * 255), colorsys.hls_to_rgb(h, l, s)))
def hsl_to_rgb(hue, saturation, lightness=0.5): (red, green, blue) = colorsys.hls_to_rgb(hue, lightness, saturation) return '%02x%02x%02x' % (min(1.0, red) * 255.0, min(1.0, green) * 255.0, min(1.0, blue) * 255.0)
def hls_to_plt_rgb(h, l, s): (r, g, b) = colorsys.hls_to_rgb(h, l, s) return [r, g, b]
def hls_palette(n_colors=6, h=.01, l=.6, s=.65): # noqa """Get a set of evenly spaced colors in HLS hue space. h, l, and s should be between 0 and 1 Parameters ---------- n_colors : int number of colors in the palette h : float first hue l : float lightness s : float saturation Returns ------- palette : seaborn color palette List-like object of colors as RGB tuples. See Also -------- husl_palette : Make a palette using evently spaced circular hues in the HUSL system. Examples -------- Create a palette of 10 colors with the default parameters: .. plot:: :context: close-figs >>> import seaborn as sns; sns.set() >>> sns.palplot(sns.hls_palette(10)) Create a palette of 10 colors that begins at a different hue value: .. plot:: :context: close-figs >>> sns.palplot(sns.hls_palette(10, h=.5)) Create a palette of 10 colors that are darker than the default: .. plot:: :context: close-figs >>> sns.palplot(sns.hls_palette(10, l=.4)) Create a palette of 10 colors that are less saturated than the default: .. plot:: :context: close-figs >>> sns.palplot(sns.hls_palette(10, s=.4)) """ hues = np.linspace(0, 1, int(n_colors) + 1)[:-1] hues += h hues %= 1 hues -= hues.astype(int) palette = [colorsys.hls_to_rgb(h_i, l, s) for h_i in hues] return _ColorPalette(palette)
def generate_preview_image(texts=None, picture=None, rating=None, show_instance_layer=True): """Puts everything together""" texts = texts or {} # Cover try: inner_img_layer = Image.open(picture) inner_img_layer.thumbnail((inner_img_width, inner_img_height), Image.ANTIALIAS) color_thief = ColorThief(picture) dominant_color = color_thief.get_color(quality=1) except: # pylint: disable=bare-except inner_img_layer = generate_default_inner_img() dominant_color = ImageColor.getrgb(DEFAULT_COVER_COLOR) # Color if BG_COLOR in ["use_dominant_color_light", "use_dominant_color_dark"]: image_bg_color = "rgb(%s, %s, %s)" % dominant_color # Adjust color image_bg_color_rgb = [ x / 255.0 for x in ImageColor.getrgb(image_bg_color) ] image_bg_color_hls = colorsys.rgb_to_hls(*image_bg_color_rgb) if BG_COLOR == "use_dominant_color_light": lightness = max(0.9, image_bg_color_hls[1]) else: lightness = min(0.15, image_bg_color_hls[1]) image_bg_color_hls = ( image_bg_color_hls[0], lightness, image_bg_color_hls[2], ) image_bg_color = tuple( math.ceil(x * 255) for x in colorsys.hls_to_rgb(*image_bg_color_hls)) else: image_bg_color = BG_COLOR # Background (using the color) img = Image.new("RGBA", (IMG_WIDTH, IMG_HEIGHT), color=image_bg_color) # Contents inner_img_x = margin + inner_img_width - inner_img_layer.width inner_img_y = math.floor((IMG_HEIGHT - inner_img_layer.height) / 2) content_x = margin + inner_img_width + gutter content_width = IMG_WIDTH - content_x - margin contents_layer = Image.new("RGBA", (content_width, IMG_HEIGHT), color=TRANSPARENT_COLOR) contents_composite_y = 0 if show_instance_layer: instance_layer = generate_instance_layer(content_width) contents_layer.alpha_composite(instance_layer, (0, contents_composite_y)) contents_composite_y = contents_composite_y + instance_layer.height + gutter texts_layer = generate_texts_layer(texts, content_width) contents_layer.alpha_composite(texts_layer, (0, contents_composite_y)) contents_composite_y = contents_composite_y + texts_layer.height + gutter if rating: # Add some more margin contents_composite_y = contents_composite_y + gutter rating_layer = generate_rating_layer(rating, content_width) if rating_layer: contents_layer.alpha_composite(rating_layer, (0, contents_composite_y)) contents_composite_y = contents_composite_y + rating_layer.height + gutter contents_layer_box = contents_layer.getbbox() contents_layer_height = contents_layer_box[3] - contents_layer_box[1] contents_y = math.floor((IMG_HEIGHT - contents_layer_height) / 2) if show_instance_layer: # Remove Instance Layer from centering calculations contents_y = contents_y - math.floor( (instance_layer.height + gutter) / 2) contents_y = max(contents_y, margin) # Composite layers img.paste(inner_img_layer, (inner_img_x, inner_img_y), inner_img_layer.convert("RGBA")) img.alpha_composite(contents_layer, (content_x, contents_y)) return img.convert("RGB")
def _get_easing_node(cfg, easing, curve_zoom, color_program, nb_points=128): text_vratio = 1 / 8. graph_hpad_ratio = 1 / 16. area_size = 2.0 width, height = area_size, area_size text_height = text_vratio * height pad_height = graph_hpad_ratio * height # Colors hue = random.uniform(0, 0.6) color = list(colorsys.hls_to_rgb(hue, 0.6, 1.0)) + [1] ucolor = ngl.UniformVec4(value=color) graph_bg_ucolor = ngl.UniformVec4(value=(.15, .15, .15, 1)) normed_graph_bg_ucolor = ngl.UniformVec4(value=(0, 0, 0, 1)) line_ucolor = ngl.UniformVec4(value=(1, 1, 1, .4)) # Text legend text = ngl.Text(text=easing, fg_color=color, padding=3, bg_color=(0, 0, 0, 1), box_corner=(-width / 2., height / 2. - text_height, 0), box_width=(width, 0, 0), box_height=(0, text_height, 0), label='%s legend' % easing) # Graph drawing area (where the curve may overflow) graph_size = area_size - text_height - pad_height * 2 graph_block = _block(graph_size, graph_size, color_program, corner=(-graph_size / 2, -(graph_size + text_height) / 2, 0), color=graph_bg_ucolor) # Normed area of the graph normed_graph_size = graph_size * curve_zoom normed_graph_block = _block(normed_graph_size, normed_graph_size, color_program, corner=(-normed_graph_size / 2, -(normed_graph_size + text_height) / 2, 0), color=normed_graph_bg_ucolor) # Curve easing_name, easing_args = _easing_split(easing) curve_scale_factor = graph_size / area_size * curve_zoom vertices_data = array.array('f') for i in range(nb_points + 1): t = i / float(nb_points) v = ngl.easing_evaluate(easing_name, t, easing_args) x = curve_scale_factor * (t * width - width / 2.) y = curve_scale_factor * (v * height - height / 2.) y -= text_height / 2. vertices_data.extend([x, y, 0]) vertices = ngl.BufferVec3(data=vertices_data) geometry = ngl.Geometry(vertices, topology='line_strip') curve = ngl.Render(geometry, color_program, label='%s curve' % easing) curve.update_uniforms(color=ucolor) # Value cursor y = 2 / 3. * pad_height x = y * math.sqrt(3) cursor_geometry = ngl.Triangle((-x, y, 0), (0, 0, 0), (-x, -y, 0)) cursor = ngl.Render(cursor_geometry, color_program, label='%s cursor' % easing) cursor.update_uniforms(color=ucolor) # Horizontal value line hline_data = array.array('f', (0, 0, 0, graph_size, 0, 0)) hline_vertices = ngl.BufferVec3(data=hline_data) hline_geometry = ngl.Geometry(hline_vertices, topology='line_strip') hline = ngl.Render(hline_geometry, color_program, label='%s value line' % easing) hline.update_uniforms(color=line_ucolor) # Value animation (cursor + h-line) value_x = -graph_size / 2. value_y = (-text_height - normed_graph_size) / 2. value_animkf = ( ngl.AnimKeyFrameVec3(0, (value_x, value_y, 0)), ngl.AnimKeyFrameVec3(cfg.duration, (value_x, value_y + normed_graph_size, 0), easing_name, easing_args), ) value_anim = ngl.Group(children=(hline, cursor)) value_anim = ngl.Translate(value_anim, anim=ngl.AnimatedVec3(value_animkf), label='%s value anim' % easing) # Vertical time line vline_data = array.array('f', (0, 0, 0, 0, graph_size, 0)) vline_vertices = ngl.BufferVec3(data=vline_data) vline_geometry = ngl.Geometry(vline_vertices, topology='line_strip') vline = ngl.Render(vline_geometry, color_program, label='%s time line' % easing) vline.update_uniforms(color=line_ucolor) # Time animation (v-line only) time_x = -normed_graph_size / 2. time_y = (-text_height - graph_size) / 2. time_animkf = (ngl.AnimKeyFrameVec3(0, (time_x, time_y, 0)), ngl.AnimKeyFrameVec3( cfg.duration, (time_x + normed_graph_size, time_y, 0))) time_anim = ngl.Translate(vline, anim=ngl.AnimatedVec3(time_animkf), label='%s time anim' % easing) group = ngl.Group(label='%s block' % easing) group.add_children(text, graph_block, normed_graph_block, curve, value_anim, time_anim) return group