def run(d):
    global out
    if isinstance(d, list):
        for k in d:
            if isinstance(k, dict):
                run(k)

    else:
        for k, v in d.items():
            if isinstance(v, dict) or isinstance(v, list):
                run(v)
            if isinstance(v, str) and v.startswith("#"):
                # v = v.lstrip("#")
                c = Color(v[:7])
                out += c.get_hex_l()
                if 0 < c.saturation < 1:
                    if c.luminance > 0.3:
                        c.luminance = np.clip(c.luminance + 0.1, 0, 1)
                        if c.saturation > 0:
                            c.saturation = np.clip(c.saturation + 0.2, 0, 1)
                elif c.saturation == 0:
                    if c.luminance > 0.5:
                        c.luminance = np.clip(c.luminance + 0.2, 0, 1)
                else:
                    ...
                    # c.luminance = np.clip(c.luminance + 0.05, 0, 1)

                # out = (
                #     "#"
                #     + "".join([format(int(v), "02x") for v in colorsys.hls_to_rgb(*u)])
                #     + v[6:]
                # )
                out += "\t" + c.get_hex_l() + "\n"
                d[k] = c.get_hex_l() + v[7:]
Esempio n. 2
0
 def text_color(self):
     bg_c = Color(self.bg_color)
     txt_c = Color()
     if bg_c.luminance < 0.5:
         txt_c.luminance = 1
     else:
         txt_c.luminance = 0
     return txt_c
Esempio n. 3
0
def background(f):
    core = Color("blue")
    core.luminance = min(f * 2, 1)
    pixels = falloff(core, BLACK, 30, int(NUM_LEDS * 2 * f))
    sun = Color("white")
    sun.luminance = min(f / 2, 0)
    pixels = add(pixels, falloff(sun, BLACK, 30, 5))
    return pixels
Esempio n. 4
0
def betagen(base_dark):

    HL_scale = 0.85
    darkscale = 0.9

    dark = base_dark

    c_dark = Color(dark)

    flag = True

    counts = 0
    new_counts = 0
    while flag:

        try:
            dark_highlight = colorscale(c_dark.hex, HL_scale)

            c = Color(dark)

            c.luminance = c.luminance * 1.7
            c.saturation = c.saturation * 0.55

            mid = c.hex

            mid_highlight = colorscale(mid, HL_scale)

            c = Color(mid)

            c.luminance = c.luminance * 1.35
            c.saturation = c.saturation * 0.95

            light = c.hex

            light_highlight = colorscale(light, HL_scale)

            flag = False
        except:
            counts += 1

            if counts < 100:

                c_dark.luminance = c_dark.luminance * 0.9

            elif new_counts < 500:

                new_counts += 1
                c_dark.luminance = c_dark.luminance * 1.1

            else:

                print(c_dark.luminance)
                print(c_dark.saturation)
                raise RuntimeError("This color sucks")

            dark = c_dark.hex

    return dark, dark_highlight, mid, mid_highlight, light, light_highlight
Esempio n. 5
0
def ref_to_color(ref):
    color = Color(hex=f"#{md5(ref.name.encode()).hexdigest()[2:8]}")
    if color.saturation < 0.6:
        color.saturation = 0.6
    elif color.saturation > 0.7:
        color.saturation = 0.7

    if color.luminance < 0.7:
        color.luminance = 0.7
    elif color.luminance > 0.9:
        color.luminance = 0.9
    return color.get_hex()
Esempio n. 6
0
    def select_fg(self, bg):
        fg, inactive_fg = self.fg_alt, Color(self.fg)
        inactive_fg.luminance = 0.7

        if bg.luminance < 0.5:
            fg = self.fg
            inactive_fg = Color(self.fg_alt)
            if bg.luminance < 0.3:
                inactive_fg.luminance = 0.5
            else:
                inactive_fg.luminance = 0.2

        return fg, inactive_fg
Esempio n. 7
0
 def draw_raw3d_pose(cls, ax, thedata, pose_raw, zdir='z'):
     p3wrist = np.array([pose_raw[0, :]])
     for fii, joints in enumerate(thedata.join_id):
         p3joints = pose_raw[joints, :]
         color_v0 = Color(thedata.join_color[fii + 1])
         color_v0.luminance = 0.3
         color_range = [
             C.rgb
             for C in make_color_range(color_v0, thedata.join_color[fii +
                                                                    1],
                                       len(p3joints) + 1)
         ]
         for jj, joint in enumerate(p3joints):
             ax.scatter(p3joints[jj, 0],
                        p3joints[jj, 1],
                        p3joints[jj, 2],
                        color=color_range[jj + 1],
                        zdir=zdir)
         p3joints_w = np.vstack((p3wrist, p3joints))
         ax.plot(p3joints_w[:, 0],
                 p3joints_w[:, 1],
                 p3joints_w[:, 2],
                 '-',
                 linewidth=2.0,
                 color=thedata.join_color[fii + 1].rgb,
                 zdir=zdir)
     ax.scatter(p3wrist[0, 0],
                p3wrist[0, 1],
                p3wrist[0, 2],
                color=thedata.join_color[0].rgb,
                zdir=zdir)
Esempio n. 8
0
    def read(self):
        # read the current color index
        self.encoder.read()
        diff = self.encoder.counter - self.encoder.prev_counter
        self.cur_idx = (self.cur_idx + diff) % self.led_count

        # save the current color as the value (retaining prev_value)
        color_idx = self.cur_idx / (self.led_count / len(self.COLORS))
        cur_color = self.COLORS[color_idx]
        self.value = cur_color['name']

        # do we need to update the led array?
        if self.cur_idx != self.prev_idx:
            self.prev_idx = self.cur_idx

            # build an array of colors to populate the string
            new_colors = []
            for i in xrange(self.led_count):
                color_index = len(self.COLORS) * i / self.led_count
                color = Color(self.COLORS[color_index]['color'])

                # dim inactive colors
                if i != self.cur_idx:
                    color.luminance = color.luminance * self.DIM_PCT

                new_colors.append(color)

            peripherals.MAPLE.set_led_batch(self.first_led, new_colors)

        self.prev_value = self.value
Esempio n. 9
0
def segments(request, account_key):
    segments = Segment.objects.filter(account_key=account_key)
    formatted_segments = [{s.id: s.name} for s in segments]
    backgroundColor = Color(
        request.GET.get("backgroundColor", settings.DEFAULT_DIALOG_BACKGROUND))
    lightColor = Color(backgroundColor)
    lightColor.luminance += 0.1
    darkColor = Color(backgroundColor)
    darkColor.luminance -= 0.1
    darkestColor = Color(backgroundColor)
    darkestColor.luminance -= 0.6
    if darkestColor.luminance < 0:
        darkestColor.luminance = 0.1
    response_data = json.dumps({
        "segments":
        formatted_segments,
        "template":
        render_to_string(
            'segments/dialog.html', {
                'segments': segments,
                'backgroundColor': backgroundColor,
                "lightColor": lightColor.hex,
                "darkColor": darkColor.hex,
                "darkestColor": darkestColor.hex,
                "buttonColor": settings.DEFAULT_DIALOG_BUTTON,
            }),
    })
    return HttpResponse(response_data, content_type="application/json")
Esempio n. 10
0
    async def colour(self, ctx, colour:discord.Colour):
        '''Change your colour.
        Usage: colour hex_value
        '''
        try:
            bot_channel = self.bot.get_channel(load_redis().hget(ctx.message.server.id, "botchannel").decode('utf-8'))
            r = colour.r/255
            g = colour.g/255
            b = colour.b/255
            c = Color(rgb=(r, g, b))
            if c.luminance < 0.45:
                c.luminance = 0.45
            if c.saturation > 0.80:
                c.saturation = 0.80
            colour_new = discord.Colour(int(c.hex[1:], 16))
            if colour.value != colour_new.value:
                colour = colour_new
                em = discord.Embed(description='{0} your colour has been adjusted to look better on discord. New colour: {1}'.format(ctx.message.author.mention,c.hex), colour=colour)
                await self.bot.send_message(bot_channel, embed=em)

            role = discord.utils.find(lambda r: r.name.startswith(str(ctx.message.author)), list(ctx.message.server.roles))
            em = discord.Embed(description='New color set for {0}'.format(ctx.message.author.mention), colour=colour)
            if role:
                await self.bot.edit_role(ctx.message.server,role,colour=colour)
                await self.bot.add_roles(ctx.message.author,role)
                await self.bot.send_message(bot_channel, embed=em) 
            else:
                await self.bot.create_role(ctx.message.server,name=str(ctx.message.author),colour=colour)
                await asyncio.sleep(2)
                role = discord.utils.find(lambda r: r.name.startswith(str(ctx.message.author)), list(ctx.message.server.roles))
                await self.bot.add_roles(ctx.message.author, role)
                await self.bot.send_message(bot_channel, embed=em) 
        except Exception as e:
            await self.bot.say(embed=discord.Embed(title=self.err_title, description=str(e), colour=self.colourRed))
Esempio n. 11
0
 def _calc_new_hex_from_theme_hex_and_tint(theme_hex, color_tint):
     if not theme_hex.startswith('#'):
         theme_hex = '#' + theme_hex
     color_obj = Color(theme_hex)
     color_obj.luminance = _calc_lum_from_tint(color_tint,
                                               color_obj.luminance)
     return color_obj.hex_l[1:]
Esempio n. 12
0
 def bg_color_lighten(self):
     delta = 0.1
     c = Color(self.bg_color)
     if (c.luminance + delta > 1):
         c.luminance = 1
     else:
         c.luminance += delta
     return c.hex_l
Esempio n. 13
0
 def card_color(self):
     delta = 0.3
     c = Color(self.bg_color)
     if (c.luminance + delta > 1):
         c.luminance = 1
     else:
         c.luminance += delta
     return c.hex_l
Esempio n. 14
0
def generate_palette(_color, _hue_variance, _saturation_variance,
                     _luminance_variance):
    base_color = Color(_color)
    palette = [base_color.hex_l]

    for i in range(1, 4):
        new_color = Color(base_color)
        new_color.hue = rotate_hue(base_color.hue, -(_hue_variance * i))
        new_color.saturation = max(
            0.0, base_color.saturation - (_saturation_variance * i))
        new_color.luminance = max(
            0.0, base_color.luminance - (_luminance_variance * i))
        palette.append(new_color.hex_l)

    for i in range(1, 4):
        new_color = Color(base_color)
        new_color.hue = rotate_hue(base_color.hue, (_hue_variance * i))
        new_color.saturation = min(
            1.0, base_color.saturation + (_saturation_variance * i))
        new_color.luminance = min(
            1.0, base_color.luminance + (_luminance_variance * i))
        palette.insert(0, new_color.hex_l)

    lighter_palette = []
    for color in palette:
        new_color = Color(color)
        new_color.hue = rotate_hue(new_color.hue, -_hue_variance / 2)
        new_color.saturation = max(
            0.0, base_color.saturation - (_saturation_variance * i))
        new_color.luminance = min(
            1.0, base_color.luminance + (_luminance_variance * i))
        lighter_palette.append(new_color.hex_l)

    darker_palette = []
    for color in palette:
        new_color = Color(color)
        new_color.hue = rotate_hue(new_color.hue, _hue_variance / 2)
        new_color.saturation = min(
            1.0, base_color.saturation + (_saturation_variance * i))
        new_color.luminance = max(
            0.0, base_color.luminance - (_luminance_variance * i))
        darker_palette.append(new_color.hex_l)

    palettes = [lighter_palette, palette, darker_palette]

    return palettes
Esempio n. 15
0
def twoS_colormaker(lik):
    """
    Given node likelihood, return approrpiate color
    """
    s0 = lik[0]
    s1 = lik[1]
    col = Color(rgb=(s0,0.1,s1))
    col.luminance = 0.75
    return col
Esempio n. 16
0
    def generate_branding_style_secondary(self):
      styles = dict();

      if self.has_accent_color:
        accent = Color(self.safe_accent_color)
        accent.luminance = accent.luminance * 0.9 if accent.luminance * 0.9 >= 0 else 0;
        accent.saturation = accent.saturation * 1.1 if accent.saturation * 1.1 <= 1 else 1
        styles['background-color'] = accent.hex

      return self.css_style(styles);
Esempio n. 17
0
def color_for_count(count: int) -> ColorStr:
    if not count:
        return Color('white').get_hex()
    c = Color('green')
    max = 10
    count_real = min(max, count)
    c.hue = (max - count_real) / max * 0.33
    c.saturation = 1.0
    c.luminance = 0.7
    return c.get_hex()
Esempio n. 18
0
def sequence(x):
    for i in range(x + 1):
        squarel = w * sperc / x
        sstart = (square[0][0] + squarel * i, square[0][1] + squarel * i)
        send = (sstart[0] + squarel * i, sstart[1] + squarel * i)
        msquare = [sstart, send]
        if (args.color):
            fill = Color(args.color)
            fill.luminance = random.randint(10, 90) / 100
        else:
            fill = Color(pick_for=random.randrange(256))
        ImageDraw.Draw(img).rectangle(msquare, fill=fill.hex)
Esempio n. 19
0
File: cylon.py Progetto: q3w3e3/rgbd
    def gen_colors(self, cfg_color):
        self.colors = [self.color]

        if self.atonce == 1:
            return

        needed = (self.atonce - 1) // 2

        color = Color(cfg_color)
        for dist in range(1, needed + 1):
            color.luminance = color.luminance / ((dist + 1)**2)
            self.colors.append(common.from_colour(color))
Esempio n. 20
0
def shape_p1(name):

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.patches import Polygon
    from matplotlib  import cm
    import pandas as pd
    import math
    from colour import Color
    import random
    from pylab import savefig

    plt.figure(figsize=(1,0.62))
    plt.axis('off')
    c = Color(rgb=(0.5,1,0.5))
    c.luminance = 0.2

    for i in range(1000):
        coordinates = [[x,y] for x, y in np.random.normal(0.5,0.075,(10,2))]
        axes = plt.gca()
        try:
            lum = np.random.normal(0,0.3)
            if c.luminance+lum >= 0 and  c.luminance+lum <= 1:
                c.luminance += lum
            else: 
                c.luminance -= lum
            r = np.random.normal(0,0.0005)
            if c.red+r >= 0 and  c.red+r <= 1:
                c.red += r
            else: 
                c.red -= r
            g = np.random.normal(0,0.0005)
            if c.green+g >= 0 and  c.green+g <= 1:
                c.green += g
            else: 
                c.green -= r        
            b = np.random.normal(0,0.0005)
            if c.blue+b >= 0 and  c.blue+b <= 1:
                c.blue += b
            else: 
                c.green -= r
        except ValueError:
            pass
        try:
            axes.add_patch(Polygon([[x,y] for x,y in coordinates],
                           facecolor= c.hex,
                           alpha = 0.1,
                           closed=False))
        except ValueError:
            pass

    savefig(name, transparent=True)
Esempio n. 21
0
 def save(self, *args, **kwargs):
     # Custom save method to create color gradient based on primary_color
     dark_shade = Color(self.primary_color)
     dark_shade.luminance = .35
     color_gradient = linear_gradient(self.primary_color, "#FFFFFF", 5)
     print(color_gradient)
     # remove white
     color_gradient.pop()
     # add dark_shade
     color_gradient.insert(0, dark_shade.hex)
     color_gradient.reverse()
     self.color_gradient = color_gradient
     super(TargetSpecies, self).save(*args, **kwargs)
Esempio n. 22
0
def cont(x):
    if (args.color):
        fill = Color(args.color)
    for i in range(x):
        for j in range(x):
            squarel = w * sperc * 2 / x
            sstart = (square[0][0] + squarel * j, square[0][1] + squarel * i)
            send = (square[0][0] + squarel * (j + 1),
                    square[0][1] + squarel * (i + 1))
            msquare = [sstart, send]
            if (args.color):
                fill.luminance = random.randint(10, 70) / 100
            else:
                fill = Color(pick_for=random.randrange(256))
            ImageDraw.Draw(img).rectangle(msquare, fill=fill.hex)
Esempio n. 23
0
 def draw_pose2d(cls, ax, thedata, pose2d, show_margin=True):
     """ Draw 2D pose on the image domain.
         Args:
             pose2d: nx2 array, image domain coordinates
     """
     pose2d = pose2d[:, ::-1]
     p2wrist = np.array([pose2d[0, :]])
     for fii, joints in enumerate(thedata.join_id[2:]):
         p2joints = pose2d[joints, :]
         color_v0 = Color(thedata.join_color[fii + 2])
         color_v0.luminance = 0.3
         color_range = [C.rgb for C in make_color_range(
             color_v0, thedata.join_color[fii + 2], len(p2joints) + 1)]
         for jj, joint in enumerate(p2joints):
             ax.plot(
                 p2joints[jj, 0], p2joints[jj, 1],
                 'o',
                 color=color_range[jj + 1]
             )
         p2joints = np.vstack((p2wrist, p2joints))
         ax.plot(
             p2joints[:, 0], p2joints[:, 1],
             '-',
             linewidth=2.0,
             color=thedata.join_color[fii + 2].rgb
         )
     ax.plot(
         p2wrist[0, 0], p2wrist[0, 1],
         'o',
         color=thedata.join_color[0].rgb
     )
     p2joints = np.array(pose2d[thedata.join_id[1], :])
     ax.plot(
         p2joints[:, 0], p2joints[:, 1],
         'o',
         color=thedata.join_color[1].rgb
     )
     p2joints = np.vstack((p2wrist, p2joints))
     p2joints[[0, 1], :] = p2joints[[1, 0], :]
     ax.plot(
         p2joints[:, 0], p2joints[:, 1],
         '-',
         linewidth=2.0,
         color=thedata.join_color[1].rgb
     )
Esempio n. 24
0
def l_shift_range(pixel, shift_range, direction=None):
    shift_color = Color(rgb=(pixel.r_n, pixel.g_n, pixel.b_n))

    upper_bound = shift_color.luminance
    lower_bound = shift_color.luminance

    if direction is None or direction > 0:
        upper_bound += shift_range

    if direction is None or direction < 0:
        lower_bound -= shift_range

    shift_color.luminance = max(0.0, min(1.0, uniform(upper_bound,
                                                      lower_bound)))

    shifted_pixel = pixel.copy()
    shifted_pixel.set_color_n(shift_color.red, shift_color.green,
                              shift_color.blue, pixel.a_n)
    return shifted_pixel
Esempio n. 25
0
def twoS_twoR_colormaker(lik):
    """
    Given node likelihood, return appropriate color

    State 0 corresponds to red, state 1 corresponds to blue
    Regime 1 corresponds to grey, regime 2 corresponds to highly saturated
    """
    s0 = sum([lik[0], lik[2]])
    s1 = sum([lik[1], lik[3]])

    r0 = sum([lik[0], lik[1]])
    r1 = sum([lik[2], lik[3]])

    lum = 0.30 + (r0*0.45)

    col = Color(rgb=(0.1,s0,s1))
    col.luminance = lum
    col.saturation = 0.35 + (r1*0.35)
    col.hue *= 1 - (0.2*r0)
    return col
Esempio n. 26
0
def changecolour(colourcode, action, amount=100):
    c = Color(colourcode)
    if action == 'red':
        c.red = amount / 100
        return c
    elif action == 'blue':
        c.blue = amount / 100
        return c
    elif action == 'green':
        c.green = amount / 100
        return c
    elif action == 'hue':
        c.hue = amount / 100
        return c
    elif action == 'sat':
        c.saturation = amount / 100
        return c
    elif action == 'lum':
        c.luminance = amount / 100
        return c
Esempio n. 27
0
    def _visualize_beacon(self, data, beacon):
        if beacon == self.LEFT_BEACON:
            prefix = 'left_'
        else:
            prefix = 'right_'

        if not self.is_active_on_spectrum(data, prefix):
            return self.layout.set_beacon(beacon, self.layout._off)

        color = Color(rgb=self.container.get_conf(prefix + 'color'))
        color.luminance = self.container.get_conf(prefix + 'lum') / 100.0
        if self.config[beacon]['Luminance'] == 'Beat':
            color = self.beat_lum(data, color, prefix, beacon)
        elif self.config[beacon]['Luminance'] == 'Energy':
            color = self.energy_lum(data, color, prefix, beacon)
        elif self.config[beacon]['Luminance'] == 'Onset':
            color = self.onset_lum(data, color, prefix, beacon)

        if self.config[beacon]['Color'] == 'Beat':
            color = self.beat_color(data, color, prefix, beacon)
        elif self.config[beacon]['Color'] == 'Energy':
            color = self.energy_color(data, color, prefix, beacon)
        elif self.config[beacon]['Color'] == 'Onset':
            color = self.onset_color(data, color, prefix, beacon)

        if self.config[beacon]['Side'] == 'Beat':
            self.beat_side(data, color, prefix, beacon)
        elif self.config[beacon]['Side'] == 'Energy':
            self.energy_side(data, color, prefix, beacon)
        elif self.config[beacon]['Side'] == 'Onset':
            self.onset_side(data, color, prefix, beacon)
        elif self.config[beacon]['Row'] == 'Beat':
            self.beat_row(data, color, prefix, beacon)
        elif self.config[beacon]['Row'] == 'Energy':
            self.energy_row(data, color, prefix, beacon)
        elif self.config[beacon]['Row'] == 'Energy (R)':
            self.energy_row(data, color, prefix, beacon, reverse=True)
        elif self.config[beacon]['Row'] == 'Onset':
            self.onset_row(data, color, prefix, beacon)
        else:
            self.layout.set_beacon(beacon, color)
Esempio n. 28
0
def color_scale(num):
    ''' Convert a number in (-1,1) to a colour.  

    Blue for negative, red for positive. '''
    positive_colour = Color("red")
    negative_colour = Color("blue")
    c = None
    if num >= 0:
        c = Color("red")
    else:
        num = num * (-1)
        c = Color("blue")

    # Clip 1 or -1 if necessary.
    if num > 1:
        num = 1
    elif num < -1:
        num = -1

    c.luminance = 1 - 0.3 * num
    c.saturation = 1
    return c.rgb
Esempio n. 29
0
 def add_line(self, x, y, name='plot', xerr=None, yerr=None, linewidth=0.5,
              linestyle=None, linecolor='black', legend=True, axes=None):
     if axes is None:
         axes = self.ax
     self.plotnum = self.plotnum + 1
     if name is 'plot':
         name = 'plot%d' % (self.plotnum)
     if linestyle is None:
         _ls = self.linestyle[self.plotnum % 4]
     else:
         _ls = linestyle
     if xerr is None and yerr is None:
         line = axes.plot(x, y, label=name, color=linecolor,
                          marker=self.marker[self.plotnum % 7],
                          ls=_ls, lw=linewidth, solid_capstyle='butt',
                          clip_on=True)
         for i in range(0, len(line)):
             self.lines[name + '%d' % (i)] = (line[i])
     else:
         if linecolor == 'black':
             ecolor = '#A7A9AC'
         else:
             col = Color(linecolor)
             col.saturation = 0.5
             col.luminance = 0.75
             ecolor = col.hex
         line, caplines, barlinecols = axes.errorbar(x, y, label=name,
                                                     color=linecolor,
                                                     xerr=xerr,
                                                     yerr=yerr,
                                                     marker=self.marker[self.plotnum % 7],
                                                     ls=_ls,
                                                     ecolor=ecolor,
                                                     lw=linewidth,
                                                     clip_on=True)
         self.lines[name] = (line)
     self.markers_on()
     self.lines_off()
Esempio n. 30
0
def increase_luminance(color_str, multiplier=0):
    """Increase the luminance of the color represented by `color_str`.

    Parameters
    ----------
    color_str : str
        A color in one of the formats recognized by `colour.Color`.

    multipler : int
        The final color will be decreased by 0.1*multiplier, from
        a starting point of 0.8.

    Returns
    -------
    dict
        {'color': str} where str is the modified color. (This is the
        format required by `mosaic`.
    """

    c = Color(color_str)
    lum = 0.8 - np.repeat(0.1, multiplier).sum()
    c.luminance = lum
    return {'color': str(c)}
Esempio n. 31
0
from colour import Color

input = []
while (len(input) < 49):
    input.extend(raw_input().split())

output = []
for color_text in input:
    c = Color(color_text)
    c.luminance = c.luminance / 2
    output.append(c.hex_l)

for _ in range(7):
    for _ in range(7):
        print output.pop(0) + " ",
    print
Esempio n. 32
0
def plot_conjugate_conics(ax, axes, width=None, plot_foci=False, plot_inverse_hyperbola=False):
    hyp, = ax.plot(*hyperbola(axes), color='dodgerblue', label='Hyperboloid (bundle of planes)')

    # Normal vector ellipse axes lengths
    # scales inversely\ with axes but can
    # be rescaled at will

    ax1,center = __inverse_ellipse(axes)

    if plot_inverse_hyperbola:
        # Plot inverse hyperbola
        color = Color('red')
        color.saturation = 0.8
        color.luminance = 0.85
        hyp_inv, = ax.plot(*hyperbola(1/axes, opens_up=True),
                            color=str(color), zorder=-1,
                           label='Inverse hyperboloid')

    ell, = ax.plot(*ellipse(ax1, center=[0,center]), color='red',
                label='Normal vector endpoint (fixed length)')

    ax.plot(*ellipse(axes), zorder=-5, color=hyp.get_color(),alpha=0.5, linewidth=1,
            label='Variance ellipsoid')


    if plot_foci:
        # Plot hyperbola focus
        hyp_c = N.sqrt(N.sum(axes**2))
        ax.plot([0,0],[hyp_c,-hyp_c], '.', color=hyp.get_color())

        # Plot ellipse foci
        c = ax1**2
        c.sort()
        c[0] *= -1
        ell_c = N.sqrt(N.sum(c))
        # Plot ellipse foci
        ax.plot([0,0],[center+ell_c,center-ell_c], '.', color=ell.get_color())

    # Plot tangents
    xvals = N.array([-500,500])
    yvals = axes[1]/axes[0]*xvals
    kw = dict(zorder=-1, color=hyp.get_color(), linewidth=0.5)
    ax.plot(xvals, yvals, ':', **kw, label='Hyperbolic tangents')
    ax.plot(xvals, -yvals, ':', **kw)

    #yvals = axes[0]/axes[1]*xvals
    kw = dict(zorder=-1, color=ell.get_color(), linewidth=0.5)
    ax.plot(yvals, xvals, ':', **kw, label='Normal vector tangents')
    ax.plot(yvals, -xvals, ':', **kw)

    _ = 4
    if axes[1] > 0.5*axes[0]:
        _ = 6

    if width is None:
        width = N.linalg.norm(axes)*_
    lim = N.array([-width,width])/2
    ax.set_xlim(lim)
    ax.set_ylim(lim*0.6)
    ax.set_aspect(1)

    return ax
Esempio n. 33
0
@author: mucs_b
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib import cm
import pandas as pd
import math
from colour import Color
import random
from pylab import savefig

plt.figure(figsize=(2, 1.25))
plt.axis('off')
c = Color(rgb=(0.5, 1, 0.5))
c.luminance = 0.2

for i in range(1000):
    coordinates = [[x, y] for x, y in np.random.normal(0.5, 0.075, (10, 2))]
    axes = plt.gca()
    try:
        lum = np.random.normal(0, 0.3)
        if c.luminance + lum >= 0 and c.luminance + lum <= 1:
            c.luminance += lum
        else:
            c.luminance -= lum
        r = np.random.normal(0, 0.0005)
        if c.red + r >= 0 and c.red + r <= 1:
            c.red += r
        else:
            c.red -= r
Esempio n. 34
0
    def draw_pose2d(cls,
                    ax,
                    thedata,
                    pose2d,
                    with_color=True,
                    show_margin=True):
        """ Draw 2D pose on the image domain.
            Args:
                pose2d: nx2 array, image domain coordinates
        """
        plot_list = []
        p2wrist = np.array([pose2d[0, :]])
        no_color = Color('black').rgb
        for fii, joints in enumerate(thedata.join_id):
            p2joints = pose2d[joints, :]
            # color_list = make_color_range(
            #     Color('black'), thedata.join_color[fii + 1], 4)
            # color_range = [C.rgb for C in make_color_range(
            #     color_list[-2], thedata.join_color[fii + 1], len(p2joints) + 1)]
            color_v0 = Color(thedata.join_color[fii + 1])
            color_v0.luminance = 0.3
            color_range = [
                C.rgb
                for C in make_color_range(color_v0, thedata.join_color[fii +
                                                                       1],
                                          len(p2joints) + 1)
            ]
            for jj, joint in enumerate(p2joints):
                if with_color:
                    pp = ax.plot(
                        p2joints[jj, 1],
                        p2joints[jj, 0],
                        # p2joints[jj, 0], p2joints[jj, 1],
                        'o',
                        color=color_range[jj + 1])
                    plot_list.append(pp)
                else:
                    pp = ax.plot(
                        p2joints[jj, 1],
                        p2joints[jj, 0],
                        # p2joints[jj, 0], p2joints[jj, 1],
                        'o',
                        color=no_color)
                    plot_list.append(pp)
            p2joints = np.vstack((p2wrist, p2joints))
            if with_color:
                pp = ax.plot(
                    p2joints[:, 1],
                    p2joints[:, 0],
                    # p2joints[:, 0], p2joints[:, 1],
                    '-',
                    linewidth=2.0,
                    color=thedata.join_color[fii + 1].rgb)
                plot_list.append(pp)
            else:
                pp = ax.plot(
                    p2joints[:, 1],
                    p2joints[:, 0],
                    # p2joints[:, 0], p2joints[:, 1],
                    '-',
                    linewidth=2.0,
                    color=no_color)
                plot_list.append(pp)
            # path = mpath.Path(p2joints)
            # verts = path.interpolated(steps=step).vertices
            # x, y = verts[:, 0], verts[:, 1]
            # z = np.linspace(0, 1, step)
            # colorline(x, y, z, cmap=mpplot.get_cmap('jet'))
        # ax.add_artist(
        #     ax.Circle(
        #         p2wrist[0, :],
        #         20,
        #         color=[i / 255 for i in thedata.join_color[0]]
        #     )
        # )
        if with_color:
            pp = ax.plot(
                p2wrist[0, 1],
                p2wrist[0, 0],
                # p2wrist[0, 0], p2wrist[0, 1],
                'o',
                color=thedata.join_color[0].rgb)
            plot_list.append(pp)
        else:
            pp = ax.plot(
                p2wrist[0, 1],
                p2wrist[0, 0],
                # p2wrist[0, 0], p2wrist[0, 1],
                'o',
                color=no_color)
            plot_list.append(pp)
        # for fii, bone in enumerate(thedata.bone_id):
        #     for jj in range(4):
        #         p0 = pose2d[bone[jj][0], :]
        #         p2 = pose2d[bone[jj][1], :]
        #         ax.plot(
        #             (int(p0[0]), int(p0[1])), (int(p2[0]), int(p2[1])),
        #             color=[i / 255 for i in thedata.join_color[fii + 1]],
        #             linewidth=2.0
        #         )
        #         # cv2.line(img,
        #         #          (int(p0[0]), int(p0[1])),
        #         #          (int(p2[0]), int(p2[1])),
        #         #          thedata.join_color[fii + 1], 1)

        # return fig2data(mpplot.gcf(), show_margin)
        return plot_list