Python colour.Color() Examples
The following are 30
code examples of colour.Color().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
colour
, or try the search function
.
Example #1
Source File: engine.py From opencv-engine with MIT License | 9 votes |
def gen_image(self, size, color_value): img0 = cv.CreateImage(size, self.image_depth, self.image_channels) if color_value == 'transparent': color = (255, 255, 255, 255) else: color = self.parse_hex_color(color_value) if not color: raise ValueError('Color %s is not valid.' % color_value) cv.Set(img0, color) return img0
Example #2
Source File: geopatterns.py From geopatterns with MIT License | 7 votes |
def generate_background(self): hue_offset = promap(int(self.hash[14:][:3], 16), 0, 4095, 0, 359) sat_offset = int(self.hash[17:][:1], 16) base_color = Color(hsl=(0, .42, .41)) base_color.hue = base_color.hue - hue_offset if sat_offset % 2: base_color.saturation = base_color.saturation + sat_offset / 100 else: base_color.saturation = base_color.saturation - sat_offset / 100 rgb = base_color.rgb r = int(round(rgb[0] * 255)) g = int(round(rgb[1] * 255)) b = int(round(rgb[2] * 255)) return self.svg.rect(0, 0, '100%', '100%', **{ 'fill': 'rgb({}, {}, {})'.format(r, g, b) })
Example #3
Source File: autotune_advanced_notebook.py From scVI with MIT License | 6 votes |
def plot_histories_single( self, benchmarkable, ax, name=None, ylim=None, xlim=None, alpha=0.1 ): histories = [] for trial in benchmarkable.trials.trials: histories.append(trial["result"]["history"]["elbo_test_set"]) benchmarkable.history_df = pd.DataFrame(histories).T red = Color("red") colors = list(red.range_to(Color("green"), benchmarkable.n_evals)) colors = [c.get_rgb() for c in colors] benchmarkable.history_df.plot( ax=ax, ylim=ylim, xlim=xlim, color=colors, alpha=alpha, legend=False, label=None, ) name = name if name else benchmarkable.name ax.set_title(name + " : Held-out ELBO") ax.set_xlabel("epoch") ax.set_xlabel("ELBO")
Example #4
Source File: engine.py From opencv-engine with MIT License | 6 votes |
def parse_hex_color(cls, color): try: color = Color(color).get_rgb() return tuple(c * 255 for c in reversed(color)) except Exception: return None
Example #5
Source File: get_color_data.py From pd-visualization with Creative Commons Zero v1.0 Universal | 6 votes |
def colorz(filename, n=3): global resizeTo try: img = Image.open(filename) w, h = img.size if w > resizeTo or h > resizeTo: img.thumbnail((resizeTo, resizeTo)) w, h = img.size points = get_points(img) clusters = kmeans(points, n, 1) rgbs = [map(int, c.center.coords) for c in clusters] weights = [1.0*len(c.points)/(w*h) for c in clusters] hexs = map(rtoh, rgbs) colors = [Color(h) for h in hexs] weighted_colors = [WeightedColor(c, weights[i]) for i,c in enumerate(colors)] return weighted_colors except IOError: return [] except: return []
Example #6
Source File: utils.py From doccano with MIT License | 6 votes |
def to_serializer_format(cls, labels, created): existing_shortkeys = {(label.suffix_key, label.prefix_key) for label in created.values()} serializer_labels = [] for label in sorted(labels): serializer_label = {'text': label} shortkey = cls.get_shortkey(label, existing_shortkeys) if shortkey: serializer_label['suffix_key'] = shortkey[0] serializer_label['prefix_key'] = shortkey[1] existing_shortkeys.add(shortkey) background_color = Color(pick_for=label) text_color = Color('white') if background_color.get_luminance() < 0.5 else Color('black') serializer_label['background_color'] = background_color.hex serializer_label['text_color'] = text_color.hex serializer_labels.append(serializer_label) return serializer_labels
Example #7
Source File: __init__.py From GeoVis with MIT License | 6 votes |
def AskColor(text="unknown graphics"): """ Pops up a temporary tk window asking user to visually choose a color. Returns the chosen color as a hex string. Also prints it as text in case the user wants to remember which color was picked and hardcode it in the script. | __option__ | __description__ | --- | --- | *text | an optional string to identify what purpose the color was chosen for when printing the result as text. """ def askcolor(): tempwindow = tk.Tk() tempwindow.state("withdrawn") rgb,hexcolor = tkColorChooser.askcolor(parent=tempwindow, title="choose color for "+text) ; tempwindow.destroy() print("you picked the following color for "+str(text)+": "+str(hexcolor)) return hexcolor hexcolor = askcolor() return colour.Color(hexcolor).hex #GENERAL UTILITIES
Example #8
Source File: openedx_theme.py From opencraft with GNU Affero General Public License v3.0 | 6 votes |
def get_contrasting_font_color(background_color, delta=0.5): """ Takes in a hexcolor code and returns black or white, depending which gives the better contrast """ # Return black if background_color not set if not background_color: return "#000000" try: color = Color(background_color) except (ValueError, AttributeError): return "#000000" # Using Web Content Accessibility Guidelines (WCAG) 2.0 and comparing # the background to the black color we can define which is the # best color to improve readability on the page # More info: # https://www.w3.org/TR/WCAG20/ if color.luminance > delta: return '#000000' else: return '#ffffff'
Example #9
Source File: hit.py From open-syllabus-project with Apache License 2.0 | 6 votes |
def color(self, steps=100): """ Get a green -> red scoring color. Args: steps (int): The number of gradient steps. Returns: str: A hex color. """ low = Color('#000000') high = Color('#29b730') gradient = list(low.range_to(high, steps)) idx = round(self.field('score')*(steps-1)) return gradient[idx].get_hex()
Example #10
Source File: __init__.py From GeoVis with MIT License | 5 votes |
def _UniqueCategories(self, classification): """ Remember, with unique categories the symbolrange doesn't matter, and only works for colors """ symboltype = classification.get("symboltype") classifytype = classification.get("classifytype") if not "color" in symboltype: raise TypeError("the categorical classification can only be used with color related symboltypes") #initiate self.sortedvalues = sorted([(uniqid, value) for uniqid, value in self.values.iteritems()], key=operator.itemgetter(1)) sortedvalues = [value[symboltype] for uniqid,value in self.sortedvalues] #populate classes classes = [] #then set symbols olduniq = None for index, uniq in enumerate(sortedvalues): if uniq != olduniq: classsymbol = Color("random") classmin = uniq classmax = uniq minvalue = classmin maxvalue = classmax #create and add class classes.append( _SymbolClass(classmin, classmax, minvalue, maxvalue, index, classsymbol) ) olduniq = uniq classification["classes"] = classes
Example #11
Source File: __init__.py From GeoVis with MIT License | 5 votes |
def _CheckTextOptions(customoptions): customoptions = customoptions.copy() #text and font if not customoptions.get("textfont"): customoptions["textfont"] = "default" if not customoptions.get("textsize"): customoptions["textsize"] = MAPWIDTH*0.0055 #equivalent to textsize 7 else: #input is percent textheight of MAPWIDTH percentheight = customoptions["textsize"] #so first get pixel height pixelheight = MAPWIDTH*percentheight #to get textsize textsize = int(round(pixelheight*0.86)) customoptions["textsize"] = textsize if not customoptions.get("textcolor"): customoptions["textcolor"] = Color("black") if not customoptions.get("textopacity"): customoptions["textopacity"] = 255 if not customoptions.get("texteffect"): customoptions["texteffect"] = None if not customoptions.get("textanchor"): customoptions["textanchor"] = "center" #text background box if not customoptions.get("textboxfillcolor"): customoptions["textboxfillcolor"] = None else: if customoptions.get("textboxoutlinecolor","not specified") == "not specified": customoptions["textboxoutlinecolor"] = Color("black") if not customoptions.get("textboxfillsize"): customoptions["textboxfillsize"] = 1.1 #proportion size of text bounding box if not customoptions.get("textboxoutlinecolor"): customoptions["textboxoutlinecolor"] = None if not customoptions.get("textboxoutlinewidth"): customoptions["textboxoutlinewidth"] = 1.0 #percent of fill, not of map if not customoptions.get("textboxopacity"): customoptions["textboxopacity"] = 0 #both fill and outline return customoptions
Example #12
Source File: __init__.py From GeoVis with MIT License | 5 votes |
def SetMapBackground(mapbackground): """ Sets the mapbackground of the next map to be made. At startup the mapbackground is transparent (None). | __option__ | __description__ | --- | --- | mapbackground | takes a hex color string, as can be created with the Color function. It can also be None for a transparent background (default). """ global MAPBACKGROUND MAPBACKGROUND = mapbackground
Example #13
Source File: listy.py From GeoVis with MIT License | 5 votes |
def Show(self): import numpy, PIL, PIL.Image, PIL.ImageTk, PIL.ImageDraw import Tkinter as tk import colour win = tk.Tk() nparr = numpy.array(self.grid.lists) npmin = numpy.min(nparr) npmax = numpy.max(nparr) minmaxdiff = npmax-npmin colorstops = [colour.Color("red").rgb,colour.Color("yellow").rgb,colour.Color("green").rgb] colorstops = [list(each) for each in colorstops] colorgrad = Listy(*colorstops) colorgrad.Convert("250*value") colorgrad.Resize(int(minmaxdiff)) valuerange = range(int(npmin),int(npmax)) colordict = dict(zip(valuerange,colorgrad.lists)) print len(valuerange),len(colorgrad.lists),len(colordict) print "minmax",npmin,npmax for ypos,horizline in enumerate(self.grid.lists): for xpos,value in enumerate(horizline): relval = value/float(npmax) self.grid.lists[ypos][xpos] = colorgrad.lists[int((len(colorgrad.lists)-1)*relval)] nparr = numpy.array(self.grid.lists,"uint8") print "np shape",nparr.shape img = PIL.Image.fromarray(nparr) drawer = PIL.ImageDraw.ImageDraw(img) size = 3 for knowncell in self.knowncells: x,y = (knowncell.x,knowncell.y) drawer.ellipse((x-size,y-size,x+size,y+size),fill="black") img.save("C:/Users/BIGKIMO/Desktop/test.png") tkimg = PIL.ImageTk.PhotoImage(img) lbl = tk.Label(win, image=tkimg) lbl.pack() win.mainloop() #INTERNAL USE ONLY
Example #14
Source File: gets.py From Discord-SelfBot with MIT License | 5 votes |
def getColor(incolor): if len(incolor.split(',')) == 3: try: incolor = incolor.strip("()").split(',') if float(incolor[0]) > 1.0 or float(incolor[1]) > 1.0 or float(incolor[2]) > 1.0: red = float(int(incolor[0]) / 255) blue = float(int(incolor[1]) / 255) green = float(int(incolor[2]) / 255) else: red = incolor[0] blue = incolor[1] green = incolor[2] outcolor = Color(rgb=(float(red), float(green), float(blue))) except: outcolor = None else: try: outcolor = Color(incolor) except: outcolor = None if outcolor is None: try: outcolor = Color('#' + incolor) except: outcolor = None if outcolor is None: try: outcolor = Color('#' + incolor[2:]) except: outcolor = None return outcolor # Find Emote
Example #15
Source File: utils.py From upribox with GNU General Public License v3.0 | 5 votes |
def get_weekly_traffic(year, week, dev_ip): from collections import Counter total_protocols = Counter() days = [] total = 0 colors = list() for date in get_week_days(year, week): traffic = device_day_stats(date, dev_ip, sent_recv=True, metric=Metric.PROTOCOLS) traffic, texts = get_protocol_sums(traffic) #traffic = device_day_stats(date, dev.ip, metric=Metric.CATEGORIES) days.append({ 'date': date.strftime('%Y-%m-%d'), 'traffic': traffic, 'text': texts }) total += sum(traffic.values()) total_protocols.update(traffic) protocols_sorted = sorted(total_protocols, key=total_protocols.get, reverse=True) if len(protocols_sorted) > 0: colors = list(Color('#47ADC0').range_to(Color('black'), len(protocols_sorted))) return days, total, colors, texts, protocols_sorted
Example #16
Source File: vis_tree.py From neural_graph_evolution with MIT License | 5 votes |
def genealogy_with_style(genealogy): ''' add more styles such as coloring the connection link in the visualization ''' def process_node(node): ''' ''' if len(node['children']) == 0: return node child_r_list = [c['best_r'] for c in node['children']] sorted_r = sorted(child_r_list) sorted_color = list(Color('black').range_to(Color('black'), len(sorted_r))) max_c = max(child_r_list) min_c = min(child_r_list) for i, child in enumerate(node['children']): try: color_idx = sorted_r.index(child['best_r']) red, green, blue = (x * 255 for x in sorted_color[color_idx].rgb) child['level'] = 'rgb(%f %f %f)' % (red, green, blue) except: child['level'] = 'rgb(128, 128, 128)' child = process_node(child) return node genealogy = process_node(genealogy) with open('genealogy.json', 'w') as fh: json.dump(genealogy, fh, indent=2) return genealogy
Example #17
Source File: utils.py From ansible-playbook-grapher with MIT License | 5 votes |
def get_play_colors(play): """ Generate two colors (in hex) for a given play: the main color and the color to use as a font color :param play :type play: :rtype (str, str) :return: """ # TODO: Check the if the picked color is (almost) white. We can't see a white edge on the graph picked_color = Color(pick_for=play) play_font_color = "#000000" if picked_color.get_luminance() > 0.6 else "#ffffff" return picked_color.get_hex_l(), play_font_color
Example #18
Source File: __init__.py From GeoVis with MIT License | 5 votes |
def __hex_to_rgb(self, hexcolor): return colour.Color(hexcolor).rgb
Example #19
Source File: __init__.py From GeoVis with MIT License | 5 votes |
def RunTk(self): self.drawer.create_rectangle(0,0,MAPWIDTH,MAPHEIGHT, fill="", outline=Color("black")) #this is the map outline edge self.window.mainloop() #Internal use only
Example #20
Source File: render.py From PyGraphArt with MIT License | 5 votes |
def draw_line(self, p1, p2, color=None): ''' Draw a line from p1 to p2, black to red if color is True (FIXME) ''' r, g, b = self.colors[(NUM) % self.n_colors] self.ctx.set_source_rgba(r, g, b, .5) steps = int(max([abs(p2[0] - p1[0]), abs(p2[1] - p1[1])]) / ONE) step1 = (max(p1[0], p2[0])-min(p1[0], p2[0]))/steps step1 = -step1 if p1[0] >= p2[0] else step1 step2 = (max(p1[1], p2[1])-min(p1[1], p2[1]))/steps step2 = -step2 if p1[1] >= p2[1] else step2 # colors = polylinear_gradient(['#0000ff','#ff0000'], steps+1) if color: #color = Color('black') colors = list(Color('black').range_to(Color('red'), steps+1)) alpha = 1 else: colors = list(Color('blue').range_to(Color('red'), steps+1)) alpha = .2 step = 0 for x, y in zip(np.arange(p1[0], p2[0], step1), np.arange(p1[1], p2[1], step2)): self.ctx.set_source_rgba(*(colors[step].rgb + (alpha,))) # self.ctx.set_source_rgba( # colors['r'][step], colors['g'][step], colors['b'][step], 1) step += 1 self.ctx.rectangle(x, y, ONE, ONE) self.ctx.fill()
Example #21
Source File: utils.py From GpxTrackPoster with MIT License | 5 votes |
def interpolate_color(color1: str, color2: str, ratio: float) -> str: if ratio < 0: ratio = 0 elif ratio > 1: ratio = 1 c1 = colour.Color(color1) c2 = colour.Color(color2) c3 = colour.Color( hue=((1 - ratio) * c1.hue + ratio * c2.hue), saturation=((1 - ratio) * c1.saturation + ratio * c2.saturation), luminance=((1 - ratio) * c1.luminance + ratio * c2.luminance), ) return c3.hex_l
Example #22
Source File: test_column.py From AnyBlok with Mozilla Public License 2.0 | 5 votes |
def test_setter_color(self): color = '#F5F5F5' registry = self.init_registry(simple_column, ColumnType=Color) test = registry.Test.insert() test.col = color assert test.col.hex == colour.Color(color).hex
Example #23
Source File: test_column.py From AnyBlok with Mozilla Public License 2.0 | 5 votes |
def test_color(self): color = '#F5F5F5' registry = self.init_registry(simple_column, ColumnType=Color) test = registry.Test.insert(col=color) assert test.col.hex == colour.Color(color).hex
Example #24
Source File: tiling.py From pywonderland with MIT License | 5 votes |
def dimmed(c): return Color(hue=c.hue, saturation=c.saturation, luminance=c.luminance*0.6)
Example #25
Source File: engine_cv3.py From opencv-engine with MIT License | 5 votes |
def gen_image(self, size, color_value): if color_value == 'transparent': color = (255, 255, 255, 255) img = np.zeros((size[1], size[0], 4), self.image_depth) else: img = np.zeros((size[1], size[0], self.image_channels), self.image_depth) color = self.parse_hex_color(color_value) if not color: raise ValueError('Color %s is not valid.' % color_value) img[:] = color return img
Example #26
Source File: engine_cv3.py From opencv-engine with MIT License | 5 votes |
def parse_hex_color(cls, color): try: color = Color(color).get_rgb() return tuple(c * 255 for c in reversed(color)) except Exception: return None
Example #27
Source File: get_colors.py From pd-visualization with Creative Commons Zero v1.0 Universal | 4 votes |
def getNearestColor(c, the_list): global black_luminance_threshold global white_luminance_threshold hue = c[0] saturation = c[1] luminance = c[2] # Create a copy color_list = copy.deepcopy(the_list) # Check for black if luminance < black_luminance_threshold: return next(iter([_c for _c in color_list if _c['label']=='Black'])) # Check for white elif luminance > white_luminance_threshold: return next(iter([_c for _c in color_list if _c['label']=='White'])) # Check for gray elif saturation < gray_saturation_threshold: return next(iter([_c for _c in color_list if _c['label']=='Gray'])) # Remove black/white/gray from list color_list = [_c for _c in color_list if _c['value'][0] and _c['label']!='Black' and _c['label']!='White' and _c['label']!='Gray'] # Find the color with the smallest distance in hue min_color_i = 0 min_color = Color(color_list[min_color_i]['value'][0]) # min_distance = abs(hue - min_color.hue) min_distance = distance_3d((hue, saturation, luminance), min_color.hsl) for _g in color_list: for _c in _g['value']: _color = Color(_c) # _distance = abs(hue - _color.hue) _distance = distance_3d((hue, saturation, luminance), _color.hsl) if _distance < min_distance: min_color_i = _g['index'] min_color = _color min_distance = _distance return color_list[min_color_i] # analyze colors
Example #28
Source File: __init__.py From GeoVis with MIT License | 4 votes |
def Color(basecolor, intensity="not specified", brightness="not specified", style=None): """ Returns a hex color string of the color options specified. NOTE: New in v0.2.0, basecolor, intensity, and brightness no longer defaults to random, and it is no longer possible to call an empty Color() function (a basecolor must now always be specified). | __option__ | __description__ | __input__ | --- | --- | --- | basecolor | the human-like name of a color. Always required, but can also be set to 'random'. | string | *intensity | how strong the color should be. Must be a float between 0 and 1, or set to 'random' (by default uses the 'strong' style values, see 'style' below). | float between 0 and 1 | *brightness | how light or dark the color should be. Must be a float between 0 and 1 , or set to 'random' (by default uses the 'strong' style values, see 'style' below). | float between 0 and 1 | *style | a named style that overrides the brightness and intensity options (optional). | For valid style names, see below. Valid style names are: - 'strong' - 'dark' - 'matte' - 'bright' - 'pastelle' """ #first check on intens/bright if style and basecolor not in ("black","white","gray"): #style overrides manual intensity and brightness options intensity = COLORSTYLES[style]["intensity"] brightness = COLORSTYLES[style]["brightness"] else: #special black,white,gray mode, bc random intens/bright starts creating colors, so have to be ignored if basecolor in ("black","white","gray"): if brightness == "random": brightness = random.randrange(20,80)/100.0 #or normal else: if intensity == "random": intensity = random.randrange(20,80)/100.0 elif intensity == "not specified": intensity = 0.7 if brightness == "random": brightness = random.randrange(20,80)/100.0 elif brightness == "not specified": brightness = 0.5 #then assign colors if basecolor in ("black","white","gray"): #graymode if brightness == "not specified": return colour.Color(color=basecolor).hex else: #only listen to gray brightness if was specified by user or randomized return colour.Color(color=basecolor, luminance=brightness).hex elif basecolor == "random": #random colormode basecolor = random.randrange(300) return colour.Color(pick_for=basecolor, saturation=intensity, luminance=brightness).hex else: #custom made color return colour.Color(color=basecolor, saturation=intensity, luminance=brightness).hex
Example #29
Source File: flexidot_v1.03.py From flexidot with GNU Lesser General Public License v2.1 | 4 votes |
def create_color_list(number, color_map=None, logging=False, max_grey="#595959"): """ create color list with given number of entries grey by default, matplotlib color_map can be provided """ try: # create pylab colormap cmap = eval("P.cm." + color_map) # get descrete color list from pylab cmaplist = [cmap(i) for i in range(cmap.N)] # extract colors from map # determine positions for number of colors required steps = (len(cmaplist)-1)/(number) numbers = range(0, len(cmaplist), steps) # extract color and convert to hex code colors = [] for idx in numbers[:-1]: rgb_color = cmaplist[idx] col = rgb2hex(rgb_color[0]*255, rgb_color[1]*255, rgb_color[2]*255) colors.append(col) # grey except: if not color_map == None: logprint("Invalid color_map (%s) provided! - Examples: jet, Blues, OrRd, bwr,..." % color_map) logprint("See https://matplotlib.org/users/colormaps.html\n") old_max_grey = "#373737" old_max_grey = "#444444" colors = list(Color("#FFFFFF").range_to(Color(max_grey), number)) # grey for idx in range(len(colors)): colors[idx] = str(colors[idx]).replace("Color ", "") if "#" in colors[idx] and len(colors[idx]) != 7: # print colors[idx] colors[idx] = colors[idx] + colors[idx][-(7-len(colors[idx])):] text = "%d Colors: %s" % (len(colors), ", ".join(colors)) if logging: logprint(text, start=False, printing=True) if len(colors) < number: logprint("\nError in color range definition! %d colors missing\n" % (number - len(colors))) return colors ############################### # File Handling # ###############################
Example #30
Source File: flexidot_v1.06.py From flexidot with GNU Lesser General Public License v2.1 | 4 votes |
def create_color_list(number, color_map=None, logging=False, max_grey="#595959"): """ create color list with given number of entries grey by default, matplotlib color_map can be provided """ try: # create pylab colormap cmap = eval("P.cm." + color_map) # get descrete color list from pylab cmaplist = [cmap(i) for i in range(cmap.N)] # extract colors from map # determine positions for number of colors required steps = (len(cmaplist)-1)/(number) numbers = range(0, len(cmaplist), steps) # extract color and convert to hex code colors = [] for idx in numbers[:-1]: rgb_color = cmaplist[idx] col = rgb2hex(rgb_color[0]*255, rgb_color[1]*255, rgb_color[2]*255) colors.append(col) # grey except: if not color_map == None: logprint("Invalid color_map (%s) provided! - Examples: jet, Blues, OrRd, bwr,..." % color_map) logprint("See https://matplotlib.org/users/colormaps.html\n") old_max_grey = "#373737" old_max_grey = "#444444" colors = list(Color("#FFFFFF").range_to(Color(max_grey), number)) # grey for idx in range(len(colors)): colors[idx] = str(colors[idx]).replace("Color ", "") if "#" in colors[idx] and len(colors[idx]) != 7: # print colors[idx] colors[idx] = colors[idx] + colors[idx][-(7-len(colors[idx])):] text = "%d Colors: %s" % (len(colors), ", ".join(colors)) if logging: logprint(text, start=False, printing=True) if len(colors) < number: logprint("\nError in color range definition! %d colors missing\n" % (number - len(colors))) return colors ############################### # File Handling # ###############################