当前位置: 首页>>代码示例>>Python>>正文


Python webcolors.name_to_rgb函数代码示例

本文整理汇总了Python中webcolors.name_to_rgb函数的典型用法代码示例。如果您正苦于以下问题:Python name_to_rgb函数的具体用法?Python name_to_rgb怎么用?Python name_to_rgb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了name_to_rgb函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _loadconfig

 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")
开发者ID:shughes-uk,项目名称:twitchy_hue,代码行数:26,代码来源:twitchy_hue.py

示例2: handle_action

 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)
开发者ID:shughes-uk,项目名称:physical_twitch_notifications,代码行数:31,代码来源:ptn.py

示例3: rgb

 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
开发者ID:RealWorlds,项目名称:blockdiagcontrib-excelshape,代码行数:7,代码来源:excelshape.py

示例4: _format_color

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
开发者ID:ajwagen,项目名称:tulip-control,代码行数:35,代码来源:graph2dot.py

示例5: frame_edges_of_all_images

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)  
开发者ID:mshall88,项目名称:1_4_5,代码行数:25,代码来源:KHallMBrittain_1_4_5.py

示例6: test_parse_legacy_color_names

 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))
开发者ID:abearman,项目名称:whats-the-point1,代码行数:7,代码来源:test_html5.py

示例7: autocrop_image

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
开发者ID:tanimislam,项目名称:nprstuff,代码行数:28,代码来源:autocrop_image.py

示例8: name_to_color

    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)
开发者ID:omriharel,项目名称:lootboy,代码行数:7,代码来源:colors.py

示例9: strobe

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])
开发者ID:Evanc123,项目名称:openJarvis,代码行数:7,代码来源:flux_master.py

示例10: __parseColor

def __parseColor(color):
    try:
        return webcolors.name_to_rgb(color)
    except ValueError:
        if not color.startswith('#'):
            color = "#" + color
        return webcolors.hex_to_rgb(color)
开发者ID:mimfgg,项目名称:elite-prism-ctl,代码行数:7,代码来源:elite-prism-ctl.py

示例11: parsecolor

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
开发者ID:eassmann,项目名称:prima.py,代码行数:25,代码来源:prima.py

示例12: text_color

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
开发者ID:wpf500,项目名称:doughnuts,代码行数:7,代码来源:pie.py

示例13: make_ica_maps

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
开发者ID:seethakris,项目名称:Olfactory-Chip-Scripts,代码行数:30,代码来源:thunder_ica.py

示例14: draw

    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()
开发者ID:mfraihi,项目名称:Sudoko,代码行数:47,代码来源:sudoko.py

示例15: get_usercolor

 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]
开发者ID:shughes-uk,项目名称:twitchchat_display,代码行数:8,代码来源:display.py


注:本文中的webcolors.name_to_rgb函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。