def _loadconfig(self): logger.info("Loading configuration from config.txt") config = None if os.path.isfile("config.txt"): try: config = load(open("config.txt",'r')) required_settings = ['hue_bridge_ip','twitch_username','twitch_oauth','twitch_channel','color_1','color_2','times_to_flash','flash_speed'] for setting in required_settings: if not setting in config: logger.critical('%s is not present in config.txt, please put it there! check config_example.txt!' %setting) sys.exit() #don't allow unicode! if isinstance(config[setting],unicode): config[setting] = str(remove_nonascii(config[setting])) try: config['color_1'] = webcolors.name_to_rgb(config['color_1']) config['color_2'] = webcolors.name_to_rgb(config['color_2']) except Exception, e: logger.critical("Problem interpreting your color choices, please consult http://www.cssportal.com/css3-color-names/ for valid color names") logger.debug(e.message) sys.exit() except SystemExit: sys.exit() except Exception, e: logger.info(e) logger.critical("Problem loading configuration file, try deleting config.txt and starting again")
def handle_action(self, device, cfg): for key , value in cfg['action'].iteritems(): if key == 'flash': c1 = webcolors.name_to_rgb(value['color_1']) c2 = webcolors.name_to_rgb(value['color_2']) count = value['times_to_flash'] speed = value['flash_speed'] device.flash(c1, c2, count, speed) elif key == 'set_color': c1 = webcolors.name_to_rgb(value['color']) device.set_color(c1) elif key == 'turn_on': device.turn_on() elif key == 'turn_off': device.turn_off() elif key == 'turn_on_timer': duration = value['duration'] device.turn_on_timer(duration) elif key == 'turn_off_timer': duration = value['duration'] device.turn_off_timer(duration) elif key == 'light_wave': c1 = webcolors.name_to_rgb(value['color_1']) c2 = webcolors.name_to_rgb(value['color_2']) duration = value['duration'] device.light_wave(c1, c2, duration) elif key == 'lightning': device.lightning(1500) elif key == 'play_sound': sound_fn = value['sound_wav'] winsound.PlaySound(sound_fn, winsound.SND_FILENAME | winsound.SND_ASYNC)
def name_to_color(name, opacity=0): try: r, g, b = webcolors.name_to_rgb(name) except ValueError: r, g, b = 0, 0, 0 return Colors._format_color(r, g, b, opacity)
def autocrop_image(inputfilename, outputfilename = None, color = 'white', newWidth = None, doShow = False ): im = Image.open(inputfilename) try: # get hex colors rgbcolor = hex_to_rgb( color ) except Exception: if color not in _all_possible_colornames: raise ValueError("Error, color name = %s not in valid set of color names.") rgbcolor = webcolors.name_to_rgb(color) bg = Image.new(im.mode, im.size, rgbcolor) diff = ImageChops.difference(im, bg) diff = ImageChops.add(diff, diff, 2.0, -100) bbox = diff.getbbox() if bbox: cropped = im.crop(bbox) if newWidth is not None: height = int( newWidth * 1.0 / cropped.size[0] * cropped.size[1] ) cropped = cropped.resize(( newWidth, height )) if outputfilename is None: cropped.save(inputfilename) else: cropped.save(os.path.expanduser(outputfilename)) if doShow: cropped.show( ) return True else: return False
def __parseColor(color): try: return webcolors.name_to_rgb(color) except ValueError: if not color.startswith('#'): color = "#" + color return webcolors.hex_to_rgb(color)
def strobe(color="white"): if color != "white": rgb = re.sub('[() ]', '', str(webcolors.name_to_rgb(color))) else: rgb = "255,255,255" call(["python", "%s/FluxScripts/flux_led.py" % os.getcwd(), "10.0.1.4", "-C", "strobe", "100", rgb])
def frame_edges_of_all_images(wide, color, directory=None): if directory == None: directory = os.getcwd() # Use working directory if unspecified # Create a new directory 'Framed' new_directory = os.path.join(directory, 'Framed') try: os.mkdir(new_directory) except OSError: pass # if the directory already exists, proceed #load all the images image_list, file_list = get_images(directory) color = webcolors.name_to_rgb(color) #go through the images and save modified versions for n in range(len(image_list)): # Parse the filename filename, filetype = file_list[n].split('.') new_image = frame_edges(image_list[n],wide,color) #save the altered image, suing PNG to retain transparency new_image_filename = os.path.join(new_directory, filename + '.png') new_image.save(new_image_filename)
def test_parse_legacy_color_names(self): """ Test the HTML5 legacy color parsing of SVG/CSS3 color names. """ for name in webcolors.CSS3_NAMES_TO_HEX.keys(): self.assertEqual(webcolors.name_to_rgb(name), webcolors.html5_parse_legacy_color(name))
def rgb(self, rgb): if type(rgb) is StringType and rgb[0] == '#': rgb = hex_to_rgb(rgb) elif type(rgb) is StringType: rgb = name_to_rgb(rgb) r,g,b = rgb return (b << 16) + (g << 8) + r
def text_color(css_color, light, dark): if css_color[0] == '#': color = webcolors.hex_to_rgb(css_color) else: color = webcolors.name_to_rgb(css_color) color = colorsys.rgb_to_hls(*(a / 255. for a in color)) return light if color[1] < 0.7 else dark
def parsecolor(cc): if multiplier.search(cc): (fact, cc) = multiplier.split(cc, 1) fact = float(fact) else: fact = 1. cc = cc.strip() try: c = numpy.array(map(float, cc.split(','))) if c.size == 1: c = c.repeat(3) if c.size != 3: raise StandardError() return c * fact except ValueError: pass try: c = webcolors.hex_to_rgb(cc) return numpy.array(c)/255. * fact except ValueError: pass c = webcolors.name_to_rgb(cc) return numpy.array(c)/255. * fact
def make_ica_maps(data, imgs, img_size_x, img_size_y, num_ica_colors, color_map, colors_ica): reference = data.seriesMean().pack() maps = Colorize(cmap=color_map, colors = colors_ica[0:np.size(imgs,0)], scale=num_ica_colors).transform(abs(imgs),background=reference, mixing=1.5) #Count number of unique colors in the images #Get number of planes based on map dimesnions if len(maps.shape)==3: num_planes = 1 else: num_planes = np.size(maps,2) unique_clrs = [] for ii in xrange(0, np.size(colors_ica[0:np.size(imgs,0)])): unique_clrs.append( np.round(np.array(webcolors.name_to_rgb(colors_ica[ii]), dtype=np.float)/255)) #From maps get number of pixel matches with color for each plane matched_pixels = np.zeros((np.size(unique_clrs,0),num_planes)) array_maps = np.round(maps.astype(np.float16)) matched_pixels = np.zeros((np.size(unique_clrs,0),num_planes)) if len(maps.shape) == 3: array_maps_plane = np.reshape(array_maps, (np.size(array_maps,0)*np.size(array_maps,1),3)) matched_pixels[:,0] = [np.size(np.where((np.array(array_maps_plane) == match).all(axis=1))) for match in unique_clrs] else: for ii in xrange(0,num_planes): array_maps_plane = np.reshape(array_maps[:,:,ii,:], (np.size(array_maps,0)*np.size(array_maps,1),3)) matched_pixels[:,ii] = [np.size(np.where((np.array(array_maps_plane) == match).all(axis=1))) for match in unique_clrs] return maps, matched_pixels
def _format_color(color, prog='tikz'): """Encode color in syntax for given program. @type color: - C{str} for single color or - C{dict} for weighted color mix @type prog: 'tikz' or 'dot' """ if isinstance(color, basestring): return color if not isinstance(color, dict): raise Exception('color must be str or dict') if prog is 'tikz': s = '!'.join([k + '!' + str(v) for k, v in color.iteritems()]) elif prog is 'dot': t = sum(color.itervalues()) try: import webcolors # mix them result = np.array((0.0, 0.0, 0.0)) for c, w in color.iteritems(): result += w/t * np.array(webcolors.name_to_rgb(c)) s = webcolors.rgb_to_hex(result) except: logger.warn('failed to import webcolors') s = ':'.join([k + ';' + str(v/t) for k, v in color.iteritems()]) else: raise ValueError('Unknown program: ' + str(prog) + '. ' "Available options are: 'dot' or 'tikz'.") return s
def draw(self): pygame.init() screen_edge = 400 cell_count = self.grid * self.grid cell_edge = screen_edge / self.grid screen = pygame.display.set_mode((screen_edge+100, screen_edge)) myfont = pygame.font.SysFont("calibri", 30) for row in range(0, len(self.board)): for col in range(0, len(self.board[row])): #color_input = input("Enter color: ") rndm_clr = (255, 255, 255) value = str(self.board[row][col]) if self.board[row][col] is not None else "*" x = col*cell_edge y = row*cell_edge pygame.draw.rect(screen,rndm_clr,(x, y,cell_edge,cell_edge), 3) # render text if self.board[row][col] is not None: value = str(self.board[row][col]) label = myfont.render(value, 1, webcolors.name_to_rgb("white")) else: value = "*" label = myfont.render(value, 1, webcolors.name_to_rgb("red")) #draw number on rectangle screen.blit(label, (x+(cell_edge/self.grid),y+(cell_edge/self.grid))) # pygame.time.wait(40) small_font = pygame.font.SysFont("calibri", 18) label = small_font.render("Chances: " + str(self.chance), 1, webcolors.name_to_rgb("white")) screen.blit(label, (screen_edge + 5, 0)) pygame.event.pump() pygame.display.flip() if self.state == "w": pygame.display.quit()
def get_usercolor(self, username, usercolor=None): if usercolor: usercolor = usercolor[1:] # cut off the # from the start of the string hexcolor = (int(usercolor[:2], 16), int(usercolor[2:4], 16), int(usercolor[4:], 16)) return hexcolor elif username not in self.usercolors: self.usercolors[username] = webcolors.name_to_rgb(random.choice(TWITCH_COLORS)) return self.usercolors[username]
def test_svg_definition_conformance(self): """ Compare the results of name-to-rgb-triplet conversion to the canonical triplet values provided in the SVG specification. """ for color, triplet in SVG_COLOR_DEFINITIONS.items(): assert triplet == webcolors.name_to_rgb(color)
def parse_eastereggs(cmd, state): if _match(cmd, 'let there be light'): state.power = True if _match(cmd, 'sleep'): state.power = False if _match(cmd, 'go to hell'): state.color = webcolors.name_to_rgb('red') return (cmd, state)
def parse_color(cmd, state): for word in cmd: try: state.color = webcolors.name_to_rgb(word) cmd.remove(word) break except ValueError: continue return (cmd, state)
def fade_to_color(self, fade_milliseconds, color): """ Fade the light to a known colour in a :param fade_milliseconds: Duration of the fade in milliseconds :param color: Named color to fade to :return: None """ red, green, blue = webcolors.name_to_rgb(color) return self.fade_to_rgb(fade_milliseconds, red, green, blue)
def color_to_rgb(color): import webcolors if color == 'none' or isinstance(color, (list, tuple)): rgb = color elif re.match('#', color): rgb = webcolors.hex_to_rgb(color) else: rgb = webcolors.name_to_rgb(color) return rgb
def cmd_set_color(self, *args): color = args[0][0] try: if color.startswith('#'): self._magic_blue.set_color(webcolors.hex_to_rgb(color)) else: self._magic_blue.set_color(webcolors.name_to_rgb(color)) except ValueError as e: logger.error('Invalid color value : {}'.format(str(e))) self.print_usage('set_color')
def map_RGB_to_color_word(self, colors): """ Purpose: Creates a mapping of rgb colors to "css colors" Inputs: List of css colors Outputs: Dictionary of rgbs to css colors """ rgbsToColors = {} for color in colors: rgbsToColors[webcolors.name_to_rgb(color)] = color return rgbsToColors
def type_color(var): try: return webcolors.name_to_rgb(var) except ValueError as e: pass try: return webcolors.hex_to_rgb(var) except ValueError as e: pass raise ArgumentTypeError("invalid color value: '%s'" % var)
def test_name_to_rgb(self): """ Test conversion from color name to integer RGB triplet. """ test_pairs = ((u'white', (255, 255, 255)), (u'navy', (0, 0, 128)), (u'goldenrod', (218, 165, 32))) for name, triplet in test_pairs: self.assertEqual(triplet, webcolors.name_to_rgb(name))
def parse_sms(): import subprocess, webcolors message = request.form['Body'] print "Received text message: " + str(message) color = webcolors.name_to_rgb(message) cmd = 'blinkm set-rgb -d 9 -r ' + str(color[0]) + ' -g ' + str(color[1]) + ' -b ' + str(color[2]) subprocess.Popen([cmd], shell=True) #f = open('/var/www/public/thermostat-target.txt', 'w') #f.write(str(message)) #f.close() return ('Message processed')
def handle_color(color): strand = rgb_strand.RGBStrand(NUM_BULBS) try: rgb = webcolors.name_to_rgb(color) strand.set_strand_color(rgb[0]/16, rgb[1]/16, rgb[2]/16) time.sleep(10) # respond to user? except: # Shame user? pass
def makeImage(my_list, imageName): listDimensions = numpy.array(my_list).shape for i in range(0, len(my_list)): for j in range(0, len(my_list[i])): my_list[i][j] = webcolors.name_to_rgb(my_list[i][j]) new_list = [] for current in my_list: new_list += current img = Image.new('RGB', (listDimensions[1], listDimensions[0])) img.putdata(new_list) img.save(imageName)
def color_attributes(self): result = [] for key, value in self.attributes.items(): if "color" in key.lower(): colorAttr = {} colorAttr["key"] = key[0].lower() + key[1:] rgbTuple = webcolors.name_to_rgb(value) if value[0] != '#' else webcolors.hex_to_rgb(value) colorAttr["red"] = rgbTuple[0]/255 colorAttr["green"] = rgbTuple[1]/255 colorAttr["blue"] = rgbTuple[2]/255 result.append(colorAttr) return result
def _normalize_color(self, value): rgb = None try: if is_strtype(value): if value.startswith("#"): rgb = webcolors.hex_to_rgb(value) else: rgb = webcolors.name_to_rgb(value) elif hasattr(value, '__iter__'): rgb = tuple(value) except ValueError as e: print(e, file=sys.stderr) return rgb
def color_to_rgb(color): if isinstance(color, tuple): return color if color.startswith('#'): try: return webcolors.hex_to_rgb(color) except ValueError: raise InvalidColor(color) try: return webcolors.name_to_rgb(color) except ValueError: raise InvalidColor(color)
def test_name_to_rgb(self): """ Test conversion from color name to integer RGB triplet. """ test_pairs = ( ("white", (255, 255, 255)), ("navy", (0, 0, 128)), ("goldenrod", (218, 165, 32)), ) for name, triplet in test_pairs: result = webcolors.name_to_rgb(name) assert isinstance(result, webcolors.IntegerRGB) assert triplet == result
def __init__(self, red=0, green=0, blue=0): if isinstance(red, str): # hex to tuple to Color color = red.lstrip("#") hexcolor = re.search(r"^(?:[0-9a-fA-F]{3}){1,2}$", color) if not hexcolor: try: wcrgb = webcolors.name_to_rgb(color) except: wcrgb = webcolors.hex_to_rgb("#0" + color) c = (wcrgb.red, wcrgb.green, wcrgb.blue) else: c = tuple(int(color[c:c + 2], 16) for c in (0, 2, 4)) red, blue, green = c super().__init__(red=red, green=green, blue=blue)
async def remove(self, ctx, colour: str): try: rgb = webcolors.name_to_rgb(colour)[0] except: try: rgb = webcolors.hex_to_rgb(colour) except: try: rgb = webcolors.rgb_percent_to_rgb(colour) except: try: rgb = webcolors.rgb_to_name(colour) rgb = colour except: raise commands.BadArgument("Colour hex, name, RGB or RGB percent not found.")
def game_color(self, msg, answer=None, rgb=None, color=None): if self.game_channel is None: self.game_channel = msg.channel.id logger.warn( f"game channel set to {self.game_channel}\n{msg.channel}") try: _answer = float(answer) if (self.answered is True or self.generating is True or _answer != self.pending_answer): return self.answered_at = datetime.datetime.now() self.answered = True self.total += 1 name = profanity.censor(msg.sender.real_name) msg.react("heavy_check_mark") msg.say(f":champagne: :fireworks: The answer has been found!" f".. it was {self.pending_answer}\nWait for new question") try: color_tuple = None if rgb is not None: color_tuple = hex_to_rgb(rgb) if color is not None: color_tuple = name_to_rgb(color) except Exception as e: msg.reply( f"Sorry, couldn't work out that color, I'll do super green" ) color_tuple = (0, 128, 0) if color_tuple is not None: name = profanity.censor(msg.sender.real_name) logger.warn(f"Changing color to {color_tuple} for {name}") self.screen.fill(color_tuple) self._center_text(name) pygame.display.flip() else: msg.reply(f"Sorry, couldn't work out that color") except Exception as e: msg.reply( f":slightly_frowning_face: Doh, something went wrong, sorry\n`{e}`" )
def main(): parser = argparse.ArgumentParser( description="Change colour on the Luxafor flag") parser.add_argument("--red", dest="colour", action="store_const", const="red") parser.add_argument("--green", dest="colour", action="store_const", const="green") parser.add_argument("--orange", dest="colour", action="store_const", const="orange") parser.add_argument("--blue", dest="colour", action="store_const", const="blue") parser.add_argument("--off", dest="colour", action="store_const", const="black") parser.add_argument("--colour", "--color", help="Name of web colour to set the flag to") args = parser.parse_args() if len(sys.argv) == 1: parser.print_help() sys.exit(255) device = hid.device() device.open(0x04D8, 0xF372) # For explaination, see https://pro.luxafor.com/faq/ , click API, download the # .zip and check the .xls in it. # Fade the change cmd = [2] # Only change the flag LEDs cmd += [0x41] cmd += webcolors.name_to_rgb(args.colour) # Set fade time cmd += [16] device.write(cmd) device.close()
def parse_openscad_color(color): match = RGB_COLOR_REGEX.search(color) if match: return [ float(match.group('r')), float(match.group('g')), float(match.group('b')), ] if '"' in color and webcolors: try: c = webcolors.name_to_rgb(color[1:-1]) # skip the "" return c.red/255., c.green/255., c.blue/255. except ValueError: pass raise ValueError('Failed to parse color. Must be named webcolor or in [<r>, <g>, <b>] format. {}'.format(color))
def streaming_fill(a, args): panels = a.rotated_panel_positions s = a.effect_stream() for color in args.colors: color = webcolors.name_to_rgb(color) panel_ids = [x['panelId'] for x in sorted(a.rotated_panel_positions, key=lambda k: k['y'])] for (i, p_id) in enumerate(panel_ids): s.panel_prepare(p_id, color[0], color[1], color[2], transition_time=int((i / 10)*5)) s.panel_strobe() time.sleep(2.5) for (i, p_id) in enumerate(reversed(panel_ids)): s.panel_set(p_id, 0, 0, 0, transition_time=int((i / 10)*5))
def color_to_rgb(color): """ Convert color name or hexcode to (r,g,b) tuple :param color: a color string, e.g. "#FF00FF" or "red" :raises: InvalidColor: if color string is bad """ if isinstance(color, tuple): return color if color.startswith('#'): try: return webcolors.hex_to_rgb(color) except ValueError: raise InvalidColor(color) try: return webcolors.name_to_rgb(color) except ValueError: raise InvalidColor(color)
def parse_color(s): """Parse a string, and return a color. As a special case, "none" returns an empty tuple (). The color is a tuple of floats 0..1 """ if s.lower() == "none": return () try: return rgb255(*webcolors.name_to_rgb(s)) except ValueError: try: return rgb255(*webcolors.hex_to_rgb(s)) except ValueError: return "foo"
def make_NMF_maps(data, imgs, img_size_x, img_size_y, num_NMF_colors, color_map, colors_NMF): reference = data.seriesMean().pack() maps = Colorize(cmap=color_map, colors=colors_NMF[0:size(imgs, 0)], scale=num_NMF_colors).transform(imgs, background=reference, mixing=0.1) #Count number of unique colors in the images #Get number of planes based on map dimesnions if len(maps.shape) == 3: num_planes = 1 else: num_planes = size(maps, 2) unique_clrs = [] for ii in xrange(0, size(colors_NMF[0:size(imgs, 0)])): unique_clrs.append( round( array(webcolors.name_to_rgb(colors_NMF[ii]), dtype=float) / 255)) #From maps get number of pixel matches with color for each plane matched_pixels = zeros((size(unique_clrs, 0), num_planes)) array_maps = round(maps.astype(float16)) matched_pixels = zeros((size(unique_clrs, 0), num_planes)) if len(maps.shape) == 3: array_maps_plane = reshape( array_maps, (size(array_maps, 0) * size(array_maps, 1), 3)) matched_pixels[:, 0] = [ size(where((array(array_maps_plane) == match).all(axis=1))) for match in unique_clrs ] else: for ii in xrange(0, num_planes): array_maps_plane = reshape( array_maps[:, :, ii, :], (size(array_maps, 0) * size(array_maps, 1), 3)) matched_pixels[:, ii] = [ size(where((array(array_maps_plane) == match).all(axis=1))) for match in unique_clrs ] return maps, matched_pixels, unique_clrs
def __init__(self, bg_color="white", ellipses=[], name="tmp", tile_size=(100, 100)): assert type(bg_color) is str assert type(ellipses) is list assert type(name) is str assert len(tile_size) is 2 self.local_save_dir = HOME_DIRECTORY + "quilts/tiles/" self.bg_color = webcolors.name_to_rgb(bg_color) # self.fg_color = webcolors.name_to_rgb(fg_color) self.ellipses = ellipses self.name = name self.tile_size = tile_size self.edge_colors = [self.bg_color] * 4 self.imagine_tile_layout()
def set_block(self, x, y, z, block): """Sets block for given absolute coordinates. Args: x,y,z (int): absolute coordinates block (Block): the block at these coordinates """ # Obtain the color from the mapping if block.id in block_colors: colorname = block_colors[block.id] else: colorname = 'Red' self.unknown_blocks.add(block.id) color = webcolors.name_to_rgb(colorname) # Set the color at that position self.levels[y].set_block_at_coord(x - self.xmin, z - self.zmin, color)
def set_led_color(led, color): if led not in (LED_LOGO, LED_WHEEL): raise ValueError("Invalid LED: %s" % (led, )) if is_strtype(color): try: color = webcolors.name_to_rgb(color) except ValueError: try: color = webcolors.hex_to_rgb(color) except ValueError: color = webcolors.hex_to_rgb("#" + color) if not hasattr(color, '__iter__'): raise ValueError("Invalid Color: %s" % (color, )) args = (chr(led), ) + tuple([chr(b) for b in color]) return "\x08%s%s%s%s" % args
def __init__(self, parent=None, **kwds): QtGui.QFrame.__init__(self, parent) self.plot_params = kwds self.plotWidget = pg.PlotWidget() self.tweak_context_menu(plot_item=self.plotWidget.plotItem) try: bg_color = kwds['background'] except LookupError: bg_color = None if bg_color: try: bg_color_rgb = wc.name_to_rgb(bg_color) self.plotWidget.setBackground(background=bg_color_rgb) except ValueError as e: print('Could not decode the color %s : Exception : %s'%(bg_color, str(e)), file=sys.stderr) self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)) self.plotInterface = None self.parentWidget = parent layout = QtGui.QBoxLayout(QtGui.QBoxLayout.TopToBottom) layout.addWidget(self.plotWidget) self.plotWidget.setTitle(kwds['title']) self.plotWidget.setLabel(axis='bottom', text=kwds['xAxisTitle']) self.plotWidget.setLabel(axis='left', text=kwds['yAxisTitle']) x_log_flag, y_log_flag = False, False if kwds['xScaleType'].strip().lower() == 'log': x_log_flag = True if kwds['yScaleType'].strip().lower() == 'log': y_log_flag = True self.plotWidget.setLogMode(x=x_log_flag, y=y_log_flag) if kwds['grid']: self.plotWidget.showGrid(x=True, y=True, alpha=1.0) self.setLayout(layout) # needs to be defined to resize smaller than 400x400 self.setMinimumSize(100, 100)
def handle_starttag(self, tag, attrs): if "br" in tag: global op_buffer global static global attrs_machine if attrs_machine != []: op_buffer += " \x1b[0m" + attrs_machine.pop() + "\n" else: op_buffer += "\n" else: for attr in attrs: if "#" != attr[1][0]: rgb = name_to_rgb(attr[1]) else: rgb = hex_to_rgb(attr[1]) op_buffer += "\x1b[38;2;{};{};{}m".format( rgb[0], rgb[1], rgb[2])
def color(self, **kwargs): params = Params() if HEXCODE in kwargs: params['r'] = int(kwargs[HEXCODE][:2], 16) params['g'] = int(kwargs[HEXCODE][2:4], 16) params['b'] = int(kwargs[HEXCODE][4:], 16) elif COLOR in kwargs: params['r'], params['g'], params['b'] = webcolors.name_to_rgb( kwargs[COLOR]) else: if RED in kwargs: params['r'] = kwargs[RED] if BLUE in kwargs: params['b'] = kwargs[BLUE] if GREEN in kwargs: params['g'] = kwargs[GREEN] message = self.message(params) self.send(message)
def _to_color(tokens): rgb = None if len(tokens) == 3: try: rgb = [int(i) for i in tokens] except ValueError: print('\tbad color `{}`'.format(tokens)) elif tokens[0].startswith('#'): try: rgb = webcolors.hex_to_rgb(tokens[0]) except ValueError: print('\tbad color `{}`'.format(tokens[0])) else: try: rgb = webcolors.name_to_rgb(tokens[0]) except ValueError: print('\tbad color `{}`'.format(tokens[0])) # print('\tRGB: ', rgb) return rgb
def convert(paths, attributes, viewbox): for path, path_attributes in zip(paths, attributes): for subpath in path.continuous_subpaths(): yield ("START", *normalize_coord(subpath[0].start, viewbox)) for segment in subpath: if isinstance(segment, Line): yield ("MOVE", *normalize_coord(segment.end, viewbox)) else: for i in range(0, CURVE_RESOLUTION): sample = segment.point(i / (CURVE_RESOLUTION - 1)) yield ("MOVE", *normalize_coord(sample, viewbox)) if "fill" in path_attributes: fill = path_attributes["fill"] if fill.startswith("#"): yield ("FILL", *bytes.fromhex(normalize_hex(fill)[1:])) else: yield ("FILL", *name_to_rgb(fill)) else: yield ("FILL", *DEFAULT_COLOR)
def convert_colour(input_colour): input_colour = input_colour.strip('#') try: colour = input_colour int(colour, 16) if len(colour) == 3: colour = webcolors.normalize_hex("#" + colour).strip('#') if len(colour) == 6: return discord.Colour.from_rgb(int(colour[:2], 16), int(colour[2:4], 16), int(colour[4:6], 16)) else: raise commands.BadArgument() except ValueError: try: return discord.Colour.from_rgb( *(webcolors.name_to_rgb(input_colour.replace(" ", "")))) except ValueError: raise commands.BadArgument()
def visualize(self, image, keypoints, filename): """Visualize an image with its keypoints, and store the result into a file Args: image (PIL.Image): keypoints (torch.Tensor): keypoints in shape K x 2 filename (str): the name of file to store """ assert self.colored_skeleton is not None image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR).copy() for (_, (line, color)) in self.colored_skeleton.items(): for i in range(len(line) - 1): start, end = keypoints[line[i]], keypoints[line[i + 1]] cv2.line(image, (int(start[0]), int(start[1])), (int(end[0]), int(end[1])), color=name_to_rgb(color), thickness=3) for keypoint in keypoints: cv2.circle(image, (int(keypoint[0]), int(keypoint[1])), 3, name_to_rgb('black'), 1) cv2.imwrite(filename, image)
def _callback(self): """Call back method for widget changes""" if not self._send_updates_to_renderer: return for i in range(len(self._palette)): try: color = name_to_rgb(self._color_pickers[i].value) except ValueError: color = hex_to_rgb(self._color_pickers[i].value) c = [ float(color.red) / 255.0, float(color.green) / 255.0, float(color.blue) / 255.0, float(self._alpha_sliders[i].value) / 255.0 ] self._palette[i] = c self._update_palette()
def set_color(self, color, indices=[]): """ Set color for only those lights whose ids are provided Args: color (str): The webcolor name of the color we want to set the lights to indices ([int], optional): Ids of lights we want to set color on. Defaults to []. """ if isinstance(color, str): color = webcolors.name_to_rgb(color) r = color[0] / 255 g = color[1] / 255 b = color[2] / 255 else: r, g, b = color h, s, _ = colorsys.rgb_to_hsv(r, g, b) hue = int((2**16 - 1) * h) saturation = int((2**8 - 1) * s) for light in self.filter_lights(indices): light.set_color(hue, saturation)
def __init__(self, red=0, green=0, blue=0): if isinstance(red, str): # hex to tuple to Color color = red.lstrip("#") hexcolor = re.search(r"^(?:[0-9a-fA-F]{3}){1,2}$", color) wcrgb = None if not hexcolor: for i in range(8): try: wcrgb = webcolors.name_to_rgb("#" + i * "0" + color) except: break if wcrgb is not None: c = (wcrgb.red, wcrgb.green, wcrgb.blue) else: c = (0, 0, 0) else: c = tuple(int(color[c:c + 2], 16) for c in (0, 2, 4)) red, green, blue = c super().__init__(red=red, green=green, blue=blue)
def draw_filled_rectangle(x1, y1, x2, y2, color): # limit to x to 480, y to 272 try: if int(color, 16): hex_color = webcolors.hex_to_rgb('#' + color) elif color == '000000': hex_color = (0, 0, 0) except ValueError: hex_color = webcolors.name_to_rgb(color) upper_color_byte = (hex_color[0] >> 3 << 3) + (hex_color[1] >> 5 ) # RRRRR GGG lower_color_byte = (hex_color[1] >> 2 << 5) % 256 + (hex_color[2] >> 3 ) # GGG BBBBB #print bin(upper_color_byte), bin(lower_color_byte) # probably need to cast x1, x2, y1, y2 to ints here pytronics.serialWrite( chr(0xFF) + chr(0xC4) + chr(x1 / 256) + chr(x1 % 256) + chr(y1 / 256) + chr(y1 % 256) + chr(x2 / 256) + chr(x2 % 256) + chr(y2 / 256) + chr(y2 % 256) + chr(upper_color_byte) + chr(lower_color_byte), 9600) return 'Rectangle drawn'
def srt_line_to_ass(line, box=False): line = line.replace('\n', r'\N') if '<' in line: for tag in ['i', 'b', 'u', 's']: line = line.replace('<%s>' % tag, '{\\%s1}' % tag) line = line.replace('</%s>' % tag, '{\\%s0}' % tag) while '<font color="' in line: pre, color, post = re.match(r'(.*)\<font color="(.*?)"\>(.*)', line).groups() if color.startswith('#'): r, g, b = color[1:3], color[3:5], color[5:] elif webcolors: r, g, b = ["%02X" % x for x in webcolors.name_to_rgb(color)] else: logging.warning( 'Can\'t parse color "%s", please install webcolors module.' % color) break line = pre + '{\c&H%s%s%s&}' % (b, g, r) + post line = line.replace('</font>', '{\c&HFFFFFF&}') return line
def get_basic_color(color): with open('../templates/basic_color.csv', 'r') as b: bc = csv.reader(b) basic_color = [c for c in bc] rgb = webcolors.name_to_rgb(color) r = rgb[0] g = rgb[1] b = rgb[2] min_color = {} for i in basic_color: brgb = i[1] bname = i[0] br = brgb.split(',')[0] bg = brgb.split(',')[1] bb = brgb.split(',')[2] rd = (int(br) - int(r))**2 gd = (int(bg) - int(g))**2 bd = (int(bb) - int(b))**2 diff = rd + gd + bd min_color[diff] = bname return min_color[min(min_color.keys())]
def create_tile_img(filename_list, args): if isinstance(args.space_color, string_types): space_color = webcolors.name_to_rgb(args.space_color) # interpolation = getattr(cv2, args.interpolation, 1) space = args.space tile_num = args.tile_num interpolation = getattr(cv2, args.interpolation, 1) resize_x, resize_y = int(args.size.split('x')[0]), int( args.size.split('x')[1]) image_list = [] for filename in filename_list: img = cv2.imread(filename) if img is None: # create blank image part_img = np.zeros((resize_y, resize_x, 3), np.uint8) else: if args.keep_aspect: part_img = resize_keep_aspect(img, resize_x, resize_y, space_color, interpolation=interpolation) else: part_img = cv2.resize(img, (resize_x, resize_y), interpolation=interpolation) if space > 0: part_img = padding_blank(part_img, space, space, 0, 0, space_color) image_list.append(part_img) horizontal_image_list = [] for horizontal in chunks(image_list, tile_num): while (len(horizontal) < min(len(image_list), tile_num)): height, width = horizontal[0].shape[:2] horizontal.append(create_blank(height, width, space_color)) horizontal_image_list.append(cv2.hconcat(horizontal)) result_img = cv2.vconcat(horizontal_image_list) return result_img
def __init__(self, color=None): if color is None: self.r = self.g = self.b = 160 elif isinstance(color, Color): self.r, self.g, self.b = color.r, color.g, color.b elif isinstance(color, str): if color[0] == "#": c = hex_to_rgb(color) else: c = name_to_rgb(color) self.r = c.red self.g = c.green self.b = c.blue elif isinstance(color, (tuple, list)) and len(color) == 3: if all((isinstance(c, float) and (c <= 1.0) and (c >= 0.0)) for c in color): self.r, self.g, self.b = (int(c * 255) for c in color) elif all((isinstance(c, int) and (c <= 255) and (c >= 0)) for c in color): self.r, self.g, self.b = color else: self._invalid(color) else: self._invalid(color)
def parse_colour(s, alpha=255): r = 0 g = 0 b = 0 if isinstance(s, tuple): try: r = s[0] g = s[1] b = s[2] except Error: pass return (r, g, b, alpha) s = s.lower() try: r, g, b = webcolors.name_to_rgb(s) except ValueError: try: r, g, b = webcolors.hex_to_rgb(s) except ValueError: pass return (r, g, b, alpha)
def plot_coord_rgb(im,class_coords,d,linewidth=1): ''' converts grayscale image to rgb and plot coordinates on it ''' vmn = np.percentile(im, 1) vmx = np.percentile(im, 99) im = 255*np.minimum(np.maximum(im-vmn,0.0)/(vmx-vmn),1.0) im = np.uint8(im) imrgb = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB) colors = ['cyan','blue','red','green','magenta','yellow','black','violet'] idx,cstr,classes = 0,'','' for key in class_coords: color = webcolors.name_to_rgb(colors[idx])[::-1] for coord in class_coords[key]: y, x = coord if x >= 0: cv2.circle(imrgb, (x,y), d // 2, color, thickness=linewidth) cstr += colors[idx] + ',' classes += key + ',' idx += 1 # txtcolor = webcolors.name_to_rgb('blue')[::-1] # cv2.putText(imrgb, "%s = %s" % (cstr[:-1],classes[:-1]),(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 10.0, txtcolor, 3) # ax.set_title("%s = %s" % (cstr[:-1],classes[:-1])) return imrgb