我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用colorsys.hls_to_rgb()。
def spin(self, color, degree, *args): """ Spin color by degree. (Increase / decrease hue) args: color (str): color degree (str): percentage raises: ValueError returns: str """ if color and degree: if isinstance(degree, str): degree = float(degree.strip('%')) h, l, s = self._hextohls(color) h = ((h * 360.0) + degree) % 360.0 h = 360.0 + h if h < 0 else h rgb = colorsys.hls_to_rgb(h / 360.0, l, s) color = (utility.convergent_round(c * 255) for c in rgb) return self._rgbatohex(color) raise ValueError('Illegal color values')
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 _get_color_string(color): color = color.lower() has_alpha = color.startswith("hsla(") or color.startswith("rgba(") is_hsl = color.startswith("hsl") colors = color.replace("hsla(", "").replace("hsl(", "").replace("rgba(", "").replace("rgb(", "").replace(")", "")\ .replace(" ", "").replace("%", "").split(",") colors = list(map(lambda c: float(c), colors)) a = 1 if has_alpha: a = colors[3] if is_hsl: h = colors[0] / 360.0 s = colors[1] / 100.0 l = colors[2] / 100.0 r, g, b = colorsys.hls_to_rgb(h, l, s) return ",".join(list(map(lambda c: str(int(round(255.0 * c))), [r, g, b, a]))) else: r = colors[0] g = colors[1] b = colors[2] a = round(255.0*a) return ",".join(list(map(lambda c: str(int(c)), [r, g, b, a])))
def generate_random_colors(n, seed=5218): if seed is not None: np.random.seed(seed) colors = [] for i in range(n): hue = 0.05 + i / n # we want maximizing hue lightness = 0.4 + np.random.rand(1)[0] / 3 # lightness saturation = 0.5 + np.random.rand(1)[0] / 10 # saturation rgb = colorsys.hls_to_rgb(hue, lightness, saturation) colors.append(rgb) return colors # =========================================================================== # Helper for spectrogram # ===========================================================================
def float_color(value): """Get a color to describe the safety level. Safety level should be a floating number in range [0.0, 1.0]. The color will be more close to green if the safety level is more close to 1.0, and more close to red if level is more close to 0.0. :param value: The value of safety level. :type value: :class:`float` :return: An html color string, for example, "#ffffff". """ h = value / 3.0 l = 0.3 s = 1.0 rgb = map((lambda i: int(i * 255)), colorsys.hls_to_rgb(h, l, s)) return '#%02X%02X%02X' % tuple(rgb)
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 random_color(): return colorsys.hls_to_rgb( random.choice(range(36))/36, random.choice(range(3, 7))/10, random.choice(range(6, 11))/10, )
def fromhls(self, h, l, s): """Convert to RGB from HSL.""" r, g, b = hls_to_rgb(h, l, s) self.r = round_int(r * 255.0) & 0xFF self.g = round_int(g * 255.0) & 0xFF self.b = round_int(b * 255.0) & 0xFF
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_hls_to_rgb(hls): rgb = colorsys.hls_to_rgb(*tuple(c / 255.0 for c in hls)) return tuple(int(round(c * 255)) for c in rgb)
def hsl(self, *args): """ Translate hsl(...) to color string raises: ValueError returns: str """ if len(args) == 4: return self.hsla(*args) elif len(args) == 3: h, s, l = args rgb = colorsys.hls_to_rgb(int(h) / 360.0, utility.pc_or_float(l), utility.pc_or_float(s)) color = (utility.convergent_round(c * 255) for c in rgb) return self._rgbatohex(color) raise ValueError('Illegal color values')
def hsla(self, *args): """ Translate hsla(...) to color string raises: ValueError returns: str """ if len(args) == 4: h, s, l, a = args rgb = colorsys.hls_to_rgb(int(h) / 360.0, utility.pc_or_float(l), utility.pc_or_float(s)) color = [float(utility.convergent_round(c * 255)) for c in rgb] color.append(utility.pc_or_float(a)) return "rgba(%s,%s,%s,%s)" % tuple(color) raise ValueError('Illegal color values')
def _ophsl(self, color, diff, idx, operation): if isinstance(diff, str): diff = float(diff.strip('%')) hls = list(self._hextohls(color)) hls[idx] = self._clamp(operation(hls[idx], diff / 100.0)) rgb = colorsys.hls_to_rgb(*hls) color = (utility.away_from_zero_round(c * 255) for c in rgb) return self._rgbatohex(color)
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 create_colors(self, hue, num_colors=5, saturation=None, lightness=None): if saturation is None: saturation = 0.9 if lightness is None: lightness = 40 else: lightness *= 100 import math saturation -= math.trunc(saturation) print hue, saturation import colorsys ''' Create n related colours ''' colors = [] for i in xrange(num_colors): ix = i * (1.0/num_colors) _lightness = (lightness + (ix * 40))/100. if _lightness > 1.0: _lightness = 1.0 color = colorsys.hls_to_rgb(hue, _lightness, saturation) hex_color = '#' for part in color: hex_color += '%02x' % int(part * 255) # check and remove any bad values if not re.match('^\#[0-9a-f]{6}$', hex_color): hex_color = '#FFFFFF' colors.append(hex_color) return colors
def _color_to_rgb(color, input): """Add some more flexibility to color choices.""" if input == "hls": color = colorsys.hls_to_rgb(*color) elif input == "husl": color = husl.husl_to_rgb(*color) elif input == "xkcd": color = xkcd_rgb[color] return color
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 default_color_function(ctx, z): if ctx.isinf(z): return (1.0, 1.0, 1.0) if ctx.isnan(z): return (0.5, 0.5, 0.5) pi = 3.1415926535898 a = (float(ctx.arg(z)) + ctx.pi) / (2*ctx.pi) a = (a + 0.5) % 1.0 b = 1.0 - float(1/(1.0+abs(z)**0.3)) return hls_to_rgb(a, b, 0.8)
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 hsl_to_rgb(h, s, l): hsl = [h, l, s] hsl_clean = hsl for i in range(3): if hsl[i] <= 0: hsl_clean[i] = 0 elif hsl[i] >= 255: hsl_clean[i] = 1 else: hsl_clean[i] = float(hsl[i]) / 255.0 rgb = colorsys.hls_to_rgb(*hsl_clean) return [int(each * 255) for each in rgb]
def _get_colors(num_colors): colors=[] for i in np.arange(0., 360., 360. / num_colors): hue = i/360. lightness = (50 + np.random.rand() * 10)/100. saturation = (90 + np.random.rand() * 10)/100. colors.append(colorsys.hls_to_rgb(hue, lightness, saturation)) return colors #colors = ['g','c','r','b','m','k','y',"orange",'indigo','salmon','crimson','hotpink','saddlebrown','lightgreen','yellowgreen','peru','gray','darkred']
def __init__(self, templateData, parcelationData, axis, correlationTable, colorTable, selectedColor): super(SliceViewer, self).__init__() self.template = templateData self.regionId = None self.parcelation = parcelationData self.axis = axis self.CommunityMode = False self.correlationTable = correlationTable self.colorTable= colorTable self.selectedColor = selectedColor self.displayedSlice = 0 self.QImage = [] scalefactor = 350 self.scaleFactor = int(math.ceil(scalefactor / self.parcelation.shape[0])) numColors = self.parcelation.max() self.clut = np.zeros(numColors, dtype=np.uint32) for i in range(numColors): r, g, b = colorsys.hls_to_rgb(float(i) / float(numColors), 0.5, 1.0) self.clut[i] = (255 << 24 | int(255*r) << 16 | int(255*g) << 8 | int(255*b)) slice_view_layout = QtGui.QHBoxLayout() self.setLayout(slice_view_layout) slider = QtGui.QSlider() slider.setRange(0, self.template.shape[self.axis]-1) slider.valueChanged.connect(self.setDisplayedSlice) slider.sliderReleased.connect(self.handleSliderRelease) slider.setValue(self.displayedSlice) slice_view_layout.addWidget(slider) self.label = QtGui.QLabel() self.updateSliceLabel() slice_view_layout.addWidget(self.label)
def ColorForCommunities(self,counter): k=self.updateCommunityColors(counter) self.ColorVisit = [] m = len(self.oneLengthCommunities) for i in range(counter): if i in self.oneLengthCommunities: r,g,b = 0.5,0.5,0.5 self.clut[i] = (255 << 24 | int(255*r) << 16 | int(255*g) << 8 | int(255*b)) self.ColorVisit.append((r*255,g*255,b*255,255)) else: r, g, b = colorsys.hls_to_rgb(float(i) / float(counter-m), 0.8, 0.9) self.clut[i] = (255 << 24 | int(255*r) << 16 | int(255*g) << 8 | int(255*b)) self.ColorVisit.append((r*255,g*255,b*255,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 from_hls(cls, h, l, s): """ Construct a :class:`Color` from `HLS`_ (hue, lightness, saturation) floats between 0.0 and 1.0. """ return super(Color, cls).__new__(cls, *colorsys.hls_to_rgb(h, l, s))
def create_poster(net, icon_size, poster_path): icon_size_2 = (icon_size + 2) poster = Image.new('RGB', (icon_size_2 * 20, icon_size_2 * 15), color=(255, 255, 255)) net.run_step(embed([icon_size + 1], icon_size + 2), True) for x in range(20): for y in range(15): icon_coos = generate_icon(net, icon_size) rgb = colorsys.hls_to_rgb(random.random(), 0.30, 0.9) rgb = tuple(int(v * 255) for v in rgb) for x1, y1 in icon_coos: poster.putpixel((icon_size_2 * x + x1, icon_size_2 * y + y1), rgb) poster.save(poster_path)
def nick_color(nick): """ Generate a color from a given string. :param str nick: Input string :return: A hex color :rtype: str >>> nick_color("A") '005ad0' >>> nick_color("Hello!") 'f20c1a' """ try: return STATIC_COLOR[nick.lower()] except KeyError: pass nick_int = sum(ord(n)*3 for n in nick) hue = (nick_int % 100) / 100 color = hls_to_rgb(hue, 0.5, 0.9) return ''.join(["{:02x}".format(int(c*255)) for c in color])
def HSLToRGB(hue, saturation, luminosity): red, green, blue = colorsys.hls_to_rgb(hue, luminosity, saturation) return int(red * 0xff), int(green * 0xff), int(blue * 0xff)