我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用colorsys.rgb_to_hls()。
def _annotate_heatmap(self, ax, mesh): import numpy as np import colorsys """Add textual labels with the value in each cell.""" try: mesh.update_scalarmappable() xpos, ypos = np.meshgrid(ax.get_xticks(), ax.get_yticks()) for x, y, val, color in zip(xpos.flat, ypos.flat, mesh.get_array(), mesh.get_facecolors()): if val is not np.ma.masked: _, l, _ = colorsys.rgb_to_hls(*color[:3]) text_color = ".15" if l > .5 else "w" val = ("{:" + self.fmt + "}").format(val) ax.text(x, y, val, color=text_color, ha="center", va="center", **self.annot_kws) except Exception as e: print(e) raise e
def test_hls_values(self): values = [ # rgb, hls ((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black ((0.0, 0.0, 1.0), (4./6., 0.5, 1.0)), # blue ((0.0, 1.0, 0.0), (2./6., 0.5, 1.0)), # green ((0.0, 1.0, 1.0), (3./6., 0.5, 1.0)), # cyan ((1.0, 0.0, 0.0), ( 0 , 0.5, 1.0)), # red ((1.0, 0.0, 1.0), (5./6., 0.5, 1.0)), # purple ((1.0, 1.0, 0.0), (1./6., 0.5, 1.0)), # yellow ((1.0, 1.0, 1.0), ( 0 , 1.0, 0.0)), # white ((0.5, 0.5, 0.5), ( 0 , 0.5, 0.0)), # grey ] for (rgb, hls) in values: self.assertTripleEqual(hls, colorsys.rgb_to_hls(*rgb)) self.assertTripleEqual(rgb, colorsys.hls_to_rgb(*hls))
def main(): # Load image and convert it to RGBA, so it contains alpha channel file_path = sys.argv[1] name, ext = os.path.splitext(file_path) im = Image.open(file_path) im = im.convert('RGBA') # Go through all pixels and turn each 'white' pixel to transparent pix = im.load() width, height = im.size for x in range(width): for y in range(height): r, g, b, a = pix[x, y] h, l, s = rgb_to_hls(r, g, b) min_h, min_l, min_s = WHITE_RANGE_MIN_HLS max_h, max_l, max_s = WHITE_RANGE_MAX_HLS if min_h <= h <= max_h and min_l <= l <= max_l and min_s <= s <= max_s: pix[x, y] = (0, 0, 0, 0) im.save(name + '.png')
def lighten(color, pct): """Make a color `pct` percent lighter.""" h, l, s = colorsys.rgb_to_hls(*color) l += (1 - l) * (pct / 100) return colorsys.hls_to_rgb(h, l, s)
def tohls(self): """Convert to HLS color format.""" return rgb_to_hls(self.r * RGB_CHANNEL_SCALE, self.g * RGB_CHANNEL_SCALE, self.b * RGB_CHANNEL_SCALE)
def get_contrast_color(col): """ gets contrast color for *col (used to ensure readability) """ (hue, l, saturation) = 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) lightness = 1 - l if abs(lightness - l) < .15: lightness = .15 (red, green, blue) = colorsys.hls_to_rgb(hue, lightness, saturation) return to_hex(int(red * 255), int(green * 255), int(blue * 255)) # true complementary
def byte_rgb_to_hls(rgb): hls = colorsys.rgb_to_hls(*tuple(c / 255.0 for c in rgb)) return tuple(int(round(c * 255)) for c in hls)
def _hextohls(self, hex): rgb = self._hextorgb(hex) return colorsys.rgb_to_hls(*[c / 255.0 for c in rgb])
def rgb_hash_brighter(hash, percent_brighter): rgb = hex_to_rgb(hash) hls = list(rgb_to_hls(*rgb)) hls[1] = min(1, hls[1] + percent_brighter * (1 - hls[1])) return rgb_to_hex(tuple(map(lambda x: int(x * 255), hls_to_rgb(*hls))))
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 = mplcolors.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 rgb_to_hls(red, green, blue): """Convert an RGB tuple to an HLS tuple.""" hue, lightness, saturation = colorsys.rgb_to_hls(red/255, green/255, blue/255) return int(hue*360), int(lightness*100), int(saturation*100)
def test_hls_roundtrip(self): for r in frange(0.0, 1.0, 0.2): for g in frange(0.0, 1.0, 0.2): for b in frange(0.0, 1.0, 0.2): rgb = (r, g, b) self.assertTripleEqual( rgb, colorsys.hls_to_rgb(*colorsys.rgb_to_hls(*rgb)) )
def rgb_to_hsl(r, g, b, a=255): hsl = colorsys.rgb_to_hls(r / 255.0, g / 255.0, b / 255.0) hsl255 = [int(each * 255) for each in hsl] hsl255 = [hsl255[0], hsl255[2], hsl255[1]] return hsl255
def hls(x): """Transformation function. 1. Refactors each Red Green and Blue value in our flattened list of pixel tuples to a number between 0 and 1. 2. Uses the colorsys library to convert RGB values into Hue, Lightness, and Saturation. """ (r, g, b) = map(to_float, x) h, l, s = colorsys.rgb_to_hls(r, g, b) h = h if 0 < h else 1 return h, l, s
def hls(x): """Transformation function. 1. Refactors each Red Green and Blue value in our flattened list of pixel tuples to a number between 0 and 1. 2. Uses the colorsys library to convert RGB values into Hue, Lightness, and Saturation. """ to_float = lambda x: x / 255.0 (r, g, b) = map(to_float, x) h, l, s = colorsys.rgb_to_hls(r, g, b) h = h if 0 < h else 1 return h, l, s
def hls(x): """Transformation function. Divides each individual pixel value by 255 to normalize it to a value between 0 and 1. Converts each tuple into hue, lightness, and saturation values with the colorsys library. """ to_float = lambda x: x / 255 (r, g, b) = map(to_float, x) h, l, s = colorsys.rgb_to_hls(r, g, b) h = h if 0 < h else 1 return h, l, s
def rgb_to_hls(r, g ,b): """Convert R(0-255) G(0-255) B(0-255) to H(0-360) L(0-255) S(0-255). """ rgb = [x / 255.0 for x in (r, g, b)] h, s, v = colorsys.rgb_to_hls(*rgb) return (h * 360, s * 255, v * 255)
def rgb_lighten_saturate(rgb, dl,ds): hls = colorsys.rgb_to_hls(*rgb) hls = (hls[0], hls[1] + dl, hls[2] + ds) return colorsys.hls_to_rgb(*hls)
def hex_lighten_saturate(hexstr, dl, ds): hls = colorsys.rgb_to_hls(*hex2rgb(hexstr)) hls = (hls[0], hls[1] + dl, hls[2] + ds) return rgb2hex(colorsys.hls_to_rgb(*hls))
def rgb_lighten_saturate(rgb, amount): hls = colorsys.rgb_to_hls(*rgb) hls = (hls[0], hls[1] + dl, hls[2] + ds) return colorsys.hls_to_rgb(*hls)
def hex_lighten_saturate(hexstr, dl,ds): hls = colorsys.rgb_to_hls(*hex2rgb(hexstr)) hls = (hls[0], hls[1] + dl, hls[2] + ds) return rgb2hex(colorsys.hls_to_rgb(*hls))
def hls(self): """ Returns a 3-tuple of (hue, lightness, saturation) float values (between 0.0 and 1.0). """ return colorsys.rgb_to_hls(self.red, self.green, self.blue)
def RGBToHSL(red, green, blue): hue, luminosity, saturation = colorsys.rgb_to_hls( float(red) / 0xff, float(green) / 0xff, float(blue) / 0xff) return hue, saturation, luminosity
def lighten(rgb, p): h,l,s = colorsys.rgb_to_hls(*(c / 255.0 for c in rgb)) l = p + l - p*l return tuple(int(c * 255) for c in colorsys.hls_to_rgb(h,l,s))
def command(self): hue = None saturation = None lightness = None path = os.path.dirname(__file__) path = os.path.join(path, '..', 'public', 'base', 'less', 'custom.less') if self.args: arg = self.args[0] rgb = None if arg == 'clear': os.remove(path) print 'custom colors removed.' elif arg.startswith('#'): color = arg[1:] if len(color) == 3: rgb = [int(x, 16) * 16 for x in color] elif len(color) == 6: rgb = [int(x, 16) for x in re.findall('..', color)] else: print 'ERROR: invalid color' elif arg.lower() in self.color_list: color = self.color_list[arg.lower()][1:] rgb = [int(x, 16) for x in re.findall('..', color)] else: try: hue = float(self.args[0]) except ValueError: print 'ERROR argument `%s` not recognised' % arg if rgb: import colorsys hue, lightness, saturation = colorsys.rgb_to_hls(*rgb) lightness = lightness / 340 # deal with greys if not (hue == 0.0 and saturation == 0.0): saturation = None else: import random hue = random.random() if hue is not None: f = open(path, 'w') colors = self.create_colors(hue, saturation=saturation, lightness=lightness) for i in xrange(len(self.rules)): f.write('%s: %s;\n' % (self.rules[i], colors[i])) print '%s: %s;\n' % (self.rules[i], colors[i]) f.close print 'Color scheme has been created.' print 'Make sure less is run for changes to take effect.'
def color(self, ctx, *, color: str=None): """Display a color. Accepts CSS color names and hex input. * color - Either a CSS color or hex input. """ try: color = webcolors.name_to_hex(color) except (ValueError, AttributeError): pass try: if color: color = color.lstrip("#") # Remove the pound sign. color = int(f"0x{color}", 16) else: color = systemrandom.randint(0, 16777215) color = discord.Color(color) except ValueError: raise commands.UserInputError(("Not a valid color. " "Color must either be A) in hex format (e.g. `808080`)" " and between `FFFFFF` and `000000`, or B) A named CSS" " color (e.g. `red` or `purple`.")) color_hex_value = "%0.2X%0.2X%0.2X" % (color.r, color.g, color.b) embed = discord.Embed() embed.colour = color image_url = BASE_URL_COLOR_API.format(color_hex_value) embed.set_thumbnail(url=image_url) color_as_rgb = color.to_rgb() color_as_rgba = color_as_rgb + (1.0,) embed.add_field(name="RGB", value=f"rgb{color_as_rgb}") embed.add_field(name="RGBA", value=f"rgba{color_as_rgba}") embed.add_field(name="HSV*", value=f"{rgb_to_hsv(*color_as_rgb)}") embed.add_field(name="HLS*", value=f"{rgb_to_hls(*color_as_rgb)}") embed.add_field(name="Hex code", value=f"#{color_hex_value}") embed.add_field(name="Images", value=BASE_URL_TINEYE_MULTICOLR.format(color_hex_value.lower())) embed.add_field(name="Information", value=BASE_URL_COLOR_HEX.format(color_hex_value.lower())) embed.add_field(name="Notes", value="* These values may be slightly wrong due to floating point errors.", inline=False) embed.set_footer(text="Thumbnail provided by AlexFlipnote's API") await ctx.send(embed=embed)
def desaturate_pal(color, prop, reverse=False): """ Create a palette that desaturate a color by some proportion Parameters ---------- color : matplotlib color hex, rgb-tuple, or html color name prop : float saturation channel of color will be multiplied by this value reverse : bool Whether to reverse the palette. Returns ------- out : function Continuous color palette that takes a single parameter either a :class:`float` or a sequence of floats maps those value(s) onto the palette and returns color(s). The float(s) must be in the range [0, 1]. >>> palette = desaturate_pal('red', .1) >>> palette([0, .25, .5, .75, 1]) ['#ff0000', '#e21d1d', '#c53a3a', '#a95656', '#8c7373'] """ if not 0 <= prop <= 1: raise ValueError("prop must be between 0 and 1") # Get rgb tuple rep # Convert to hls # Desaturate the saturation channel # Convert back to rgb rgb = mcolors.colorConverter.to_rgb(color) h, l, s = colorsys.rgb_to_hls(*rgb) s *= prop desaturated_color = colorsys.hls_to_rgb(h, l, s) colors = [color, desaturated_color] if reverse: colors = colors[::-1] return gradient_n_pal(colors, name='desaturated')
def create_svg(name): swatch_w = 10 # swatch width swatch_h = 10 # swatch height if not os.path.exists(RGB_TXT): print("Error. The data file is not readable. File name is: %s" % RGB_TXT) sys.exit(1) # 1050 = 1000 width of color + width of last rectangle which might start at 1000 + approx width of font name text svg_size = 1050 dwg = svgwrite.Drawing(name, (svg_size, svg_size)) dwg.add(dwg.rect(insert=(0, 0), size=('100%', '100%'), fill='grey')) dwg.add(dwg.text('XKCD.com color name survey x=hue, y=lightness', insert=(svg_size/2, '28px'), text_anchor='middle', font_family="sans-serif", font_size='25px', fill='black')) # http://www.svgbasics.com/using_fonts.html # http://www.w3.org/TR/2008/REC-CSS2-20080411/fonts.html#propdef-font-family # 'serif', 'sans-serif', 'cursive', 'fantasy', and 'monospace' from the CSS specification # You can also use other family names like "Times", "Baskerville", "Verdena", and "Symbol." I got those names from the CSS specification and some experimenting, but I'm looking for more. # 'font-weight' Value: normal | bold + others. for line_count, line in enumerate(open(RGB_TXT)): colour_item = line.split('\t') # strip the trailing newline \n char then split by the tab chars colour_item = line.strip().split('\t') rgb = hex_to_rgb(colour_item[1]) # hsl is also called hls #hsl = #h, l, s = colorsys.rgb_to_hls(r, g, b) # rgb values are integer but colorsys wants float(0..1) and returns float h, l, s = colorsys.rgb_to_hls(rgb[0]/255.0, rgb[1]/255.0, rgb[2]/255.0) hsl = (h, s, l) swatch_x=int(h*1000) # hue by lightness swatch_y=svg_size - 25 - int(l*1000) # hue by saturation #swatch_y=int(s*1000) + 25 ## svg can handle colors in hex mode so no conversion is necessary. group_rec_text = dwg.add(dwg.g()) group_rec_text.add(dwg.rect(insert=(swatch_x, swatch_y), size=(swatch_w, swatch_h), rx=None, ry=None, fill=colour_item[1])) # text is to start on the right side of swatch in the middle. tx_x = int(swatch_x + swatch_w) tx_y = int(swatch_y + swatch_h/2) group_rec_text.add(dwg.text(colour_item[0], insert = (tx_x, tx_y), font_family="sans-serif", font_size='6px', fill='white', stroke='black', stroke_width='0.1px')) dwg.save()
def get_random_pastel_color(tone=None, black_list: list=None) -> namedtuple: """Get a random dark or light color as string, useful for CSS styling.""" light_colors_tuple = ( 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'cornsilk', 'floralwhite', 'ghostwhite', 'grey', 'honeydew', 'ivory', 'lavender', 'lavenderblush', 'lemonchiffon', 'lightcyan', 'lightgoldenrodyellow', 'lightgrey', 'lightpink', 'lightskyblue', 'lightyellow', 'linen', 'mint', 'mintcream', 'oldlace', 'papayawhip', 'peachpuff', 'seashell', 'skyblue', 'snow', 'thistle', 'white') dark_colors_tuple = ( 'brown', 'chocolate', 'crimson', 'darkblue', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkolivegreen', 'darkorange', 'darkred', 'darkslateblue', 'darkslategray', 'dimgray', 'dodgerblue', 'firebrick', 'forestgreen', 'indigo', 'maroon', 'mediumblue', 'midnightblue', 'navy', 'olive', 'olivedrab', 'royalblue', 'saddlebrown', 'seagreen', 'sienna', 'slategray', 'teal') if tone.lower() == "light": colors_tuple = light_colors_tuple elif tone.lower() == "dark": colors_tuple = dark_colors_tuple else: colors_tuple = light_colors_tuple + dark_colors_tuple if black_list: colors_tuple = tuple(set(colors_tuple).difference(set(black_list))) color = choice(colors_tuple) hexa = NAMED2HEX[color] rgb = hex2rgb(hexa) hls = rgb_to_hls(rgb.red, rgb.green, rgb.blue) hsv = rgb_to_hsv(rgb.red, rgb.green, rgb.blue) yiq = rgb_to_yiq(rgb.red, rgb.green, rgb.blue) hls = namedtuple("HLS", "h l s")( # Round bcause default precision is huge round(hls[0], 2), round(hls[1], 2), round(hls[2], 2)) hsv = namedtuple("HSV", "h s v")( round(hsv[0], 2), round(hsv[1], 2), round(hsv[2], 2)) yiq = namedtuple("YIQ", "y i q")( round(yiq[0], 2), round(yiq[1], 2), round(yiq[2], 2)) per = lambda value: int(value * 100 / 255) # To Percentage, 0~255 > 0~100% return namedtuple("PastelColor", "name hex rgb hls hsv yiq css css_prcnt")( color, hexa, rgb, hls, hsv, yiq, f"rgb({rgb.red},{rgb.green},{rgb.blue})", # rgb(int, int, int) f"rgb({per(rgb.red)}%,{per(rgb.green)}%,{per(rgb.blue)}%)") # rgb(%,%)