コード例 #1
0
ファイル: a1_exp_fit.py プロジェクト: mkawalec/masters
def plot_coeffs(coeffs):
    rcParams['figure.figsize'] = get_dims()
    fig, ax1 = plt.subplots()

    toplot = dict(x=[], y1=[], y2=[])

    for domain in sorted(coeffs.keys(), key=lambda x: float(x)):
        toplot['x'].append(float(domain))
        toplot['y1'].append(coeffs[domain][1])
        toplot['y2'].append(coeffs[domain][2])

    ax1.plot(toplot['x'], toplot['y1'], marker='o',
            color=hsv_to_rgb(0, 0.7, 0.9), label='$b_1$')

    plt.subplots_adjust(bottom=0.3, left=0.20)
    ax1.set_yscale('log')
    ax1.set_xlabel('Domain size/$\pi$')
    savefig('b1_vs_domain.png', dpi=600)

    fig, ax2 = plt.subplots()
    ax2.plot(toplot['x'], toplot['y2'], marker='o',
            color=hsv_to_rgb(0.5, 0.7, 0.9), label='$b_2$')

    ax2.set_xlabel('Domain size/$\pi$')
    plt.subplots_adjust(bottom=0.3)
    savefig('b2_vs_domain.png', dpi=600)
コード例 #2
0
ファイル: color.py プロジェクト: AnthonyAlers/topographica
    def Retina(self, properties):
        input_generator=self['training_patterns'][properties['eye']+'Retina'
                                                     if 'eye' in properties
                                                     else 'Retina']
        if 'cr' in self.dims and self.dataset!='Gaussian':
            for pattern_number, individual_generator in enumerate(input_generator.generators):
                brightness_difference=numbergen.UniformRandom(lbound=(-1.0+self.dim_fraction)/2.0,
                                                              ubound=(1.0-self.dim_fraction)/2.0,
                                                              seed=456+pattern_number,
                                                              name="Dim"+str(pattern_number))
                if 'eye' in properties and properties['eye']=='Left':
                    hsv = colorsys.rgb_to_hsv(*self.cone_scale)
                    hsv_dimmed=(hsv[0],hsv[1],hsv[2]+brightness_difference)
                    channel_factors = list(colorsys.hsv_to_rgb(*hsv_dimmed))
                elif 'eye' in properties and properties['eye']=='Right':
                    hsv = colorsys.rgb_to_hsv(*self.cone_scale)
                    hsv_dimmed=(hsv[0],hsv[1],hsv[2]-brightness_difference)
                    channel_factors = list(colorsys.hsv_to_rgb(*hsv_dimmed))
                else:
                    channel_factors = self.cone_scale

                individual_generator.channel_transforms.append(
                    ScaleChannels(channel_factors = channel_factors))

        return Model.ChannelGeneratorSheet.params(
            period=self['period'],
            phase=0.05,
            nominal_density=self.retina_density,
            nominal_bounds=sheet.BoundingBox(radius=self.area/2.0
                                + self.v1aff_radius*self.sf_spacing**(max(self['SF'])-1)
                                + self.lgnaff_radius*self.sf_spacing**(max(self['SF'])-1)
                                + self.lgnlateral_radius),
            input_generator=input_generator)
コード例 #3
0
ファイル: visualizer.py プロジェクト: gdkar/beat-off
    def step(self):
        def maxat(a): return max(enumerate(a), key=lambda x: x[1])[0] 
        #self.read_midi_events()

        audio, fft = self.analyze_audio()
        self.write_spectrum(fft)

        mind = self.inp(24, 4)
        dom_chk = maxat(fft[mind:-mind]) + mind
        dom_freq = self.RATE * dom_chk / self.CHUNK
        #self.dom_freq = dom_freq

        dom_freq = self.smooth("dom_freq", dom_freq, self.inp(14, 10) / 500.0)
        #sys.stdout.write("\rdom_freq %d" % dom_freq)

        octave = 2.0 ** math.floor(math.log(dom_freq) / math.log(2))
        self.octave = octave
        self.hue = ((dom_freq - octave) / octave + self.hueoff)
        self.hue += self.inp(14, 0) / 127.0
        self.hue = self.hue % 1.0

        self.lpf_audio=[self.lpf(float(data),mem,self.alpha) for data,mem in zip(audio,self.lpf_audio)]

        self.history.append(self.lpf_audio)
        if len(self.history)>self.HISTORY_SIZE:
            self.history.popleft()

        scaling_factor=[max(max([d[j] for d in self.history]),1) for j in range(len(self.RANGES))]

        levels=[a/f for a,f in zip(self.lpf_audio,scaling_factor)]
        bass_val = max(min((levels[0]-0.1)/0.9,1.), 0.0)
        bass_val = self.smooth("bass_val", bass_val, 0.6)
        bass_hue = (self.hue + 0.95) % 1.0
        if bass_val < 0.1: # Switch colors for low bass values
            bass_hue = (bass_hue + 0.9) % 1.0
            bass_val *= 1.1

        bass_val = max(bass_val ** 0.9 , 0.1)

        bass_color=self.makecolor(colorsys.hsv_to_rgb(bass_hue,1. * self.whiteout,bass_val * self.mute))
        treble_color=self.makecolor(colorsys.hsv_to_rgb(self.hue,0.7 * self.whiteout,1. * self.mute))

        #treble_size = (0.5-0.3*levels[1]) 
        #treble_size = self.smooth("treble_size", levels[1], 0.3)
        treble_size = levels[1]

        self.mute += self.mute_delta
        self.mute = max(min(self.mute, 1.0), 0.0)
        self.whiteout += self.whiteout_delta
        #self.whiteout = max(min(self.whiteout, 1.0), 0.0)
        self.mute = self.inp(11, 0) / 127.0


        self.update_strip([
            #self.solid_color(bass_color, alpha=0xff, id=0x00),
            (0x10, 0x00)+bass_color+(0xFF,),
            (0x05,0x01)+treble_color+(0xFF,self.makebyte(self.STRIP_LENGTH*(0.5-0.3*treble_size)),self.makebyte(self.STRIP_LENGTH*(0.5+0.3*treble_size))),
            #self.vu_stripe(treble_color, 0.5 - 0.3 * treble_size,  0.5 + 0.3 * treble_size),
            #(0x05,0x02,0x00,0xFF,0xFF,0xFF,self.makebyte(self.STRIP_LENGTH*(0.5-0.2*levels[2])),self.makebyte(self.STRIP_LENGTH*(0.5+0.2*levels[2]))),
        ])
コード例 #4
0
ファイル: GraGL_tools.py プロジェクト: kylestetz/GraGL
def hsv_rgba(c, astype=0):
    if astype == AS_INT:
        color = colorsys.hsv_to_rgb(c[0], c[1], c[2])
        color = (color[0], color[1], color[2], 1)
        return rgb_to_int(color)
    color = colorsys.hsv_to_rgb(c[0], c[1], c[2])
    return (color[0], color[1], color[2], 1)
コード例 #5
0
ファイル: a1_exp_fit.py プロジェクト: mkawalec/masters
def execute_fit():
    fits = gen_fits(0.3, 0.1)
    print fits[24][1.04]

    rcParams['figure.figsize'] = 4.981320049813201, 4
    gs = gridspec.GridSpec(5, 1)
    gs.update(wspace=0)
    ax1 = plt.subplot(gs[:4, 0])
    ax2 = plt.subplot(gs[4, 0], sharex=ax1)

    coefficients = {}

    for n, domain in enumerate(sorted(fits.keys(), key=lambda x: float(x))):
        if domain == 10:
            continue

        curr_keys = sorted(fits[domain].keys(), key=lambda x: float(x))
        x = map(lambda x: float(x), curr_keys)
        y = map(lambda x: fits[domain][x]['avg'][1], curr_keys)

        with open('domain_' + str(domain), 'w') as f:
            for i,R in enumerate(x):
                f.write("%f %f\n" % (R, y[i]))

        try:
            popt, pcov = opt.curve_fit(model_function, np.array(x), np.array(y),
                                       (0.5324, -0.0090589, 6.2374),
                                       maxfev=100000)
            coefficients[domain] = popt
        except RuntimeError:
            continue

        color1 = hsv_to_rgb(float(n) / len(fits.keys()), 0.7, 0.9)
        color2 = hsv_to_rgb(float(n + 1) / len(fits.keys()), 0.7, 0.9)

        if int(domain)%4 == 0 and int(domain) != 20:
            ax1.plot(x, y,
                    label='Data at %s$\pi$' % (domain),
                    color=color1)

            ax1.plot(x,
                    [model_function(x_val, *popt) for x_val in x],
                    label='Fit at %s$\pi$' % (domain), color=color2)

        if domain == 24:
            values = [model_function(x_val, *popt) for x_val in x]
            residuals = map(lambda x: abs(x[0] - x[1]) / x[0], zip(y, values))
            ax2.plot(x, residuals, marker='o')
            ax2.set_yscale('log')

    ax1.legend(loc=0)
    ax1.xaxis.set_visible(False)
    ax2.set_xlabel('R')
    ax1.set_ylabel('Value of $a_1$')
    ax2.set_ylabel('Residue\nat 24$\pi$')
    ax2.yaxis.tick_right()
    plt.subplots_adjust(bottom=0.15)

    savefig('double_exp_fit.png', dpi=600)
    plot_coeffs(coefficients)
コード例 #6
0
ファイル: clustering.py プロジェクト: kerkira96/uses_cases
def ccolor (cluster):
    rnd.seed(cluster)
    hue = rnd.random()
    val = rnd.uniform(0.3,0.7)
    fill = colorsys.hsv_to_rgb(hue, 0.5, val)
    border = colorsys.hsv_to_rgb(hue, 1, val)
    return (fill, border)
コード例 #7
0
ファイル: sniffy.py プロジェクト: spikelynch/holiday
def local_ip_to_rgb(ip):
    ipa = ip.split('.')
    if ipa:
        last = ipa.pop()
        if last in DEVICE_COLOURS:
            return colorsys.hsv_to_rgb(DEVICE_COLOURS[last] / 360.0, 1, VALUE)
    return colorsys.hsv_to_rgb(1, 0, VALUE)
コード例 #8
0
def main(argv):
    w = Wall(24,17)
    while True:
        rgb =  colorsys.hsv_to_rgb(random.random(), 1, intensity)
        color = [int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255)]
        up=True
        for i in range(0,len(w.sticks)/2):
            x1 = len(w.sticks)-1-i
            x2 = i
            print("Updating " + str(x1) + " and " + str(x2))
            for y in range(59*(not up),60*up, -1+(2*up) ):
                w.sticks[x1].setLed(y+1, *color)
                w.sticks[x1].updateLeds()
                w.sticks[x2].setLed(y+1, *color)
                w.sticks[x2].updateLeds()
                time.sleep(0.005)
            up=not up
        rgb =  colorsys.hsv_to_rgb(random.random(), 1, intensity)
        color = [int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255)]
        for i in range(0,len(w.sticks)/2):
            z1 = (len(w.sticks)/2) - i - 1
	    z2 = (len(w.sticks)/2) + i
            for x in range(59*(not up),60*up, -1+(2*up) ):
                w.sticks[z1].setLed(x+1, *color)
                w.sticks[z1].updateLeds()
                w.sticks[z2].setLed(x+1, *color)
                w.sticks[z2].updateLeds()
                time.sleep(0.005)
            up=not up
コード例 #9
0
ファイル: GVBoard.py プロジェクト: member2ofTEAM/hpsa
def create_image(): 
    img = Image.new( 'RGB', (1000,1000), "black") # create a new black image
    pixels = img.load() # create the pixel map
     
    for i in range(img.size[0]):    # for every pixel:
        for j in range(img.size[1]):
    	    if(board[i][j]==float("Inf")):
		continue
            if(board[i][j]==10000000):
                print "player1"
		pixels[i,j] = (player1[0]*255,player1[1]*255,player1[2]*255)
            elif(board[i][j]==-10000000):
                print "player2"
                pixels[i,j] = (player2[0]*255,player2[1]*255,player2[2]*255)
            elif(board[i][j]>0):
                p_color = colorsys.rgb_to_hsv(player1_area[0], player1_area[1], player1_area[2])
                value = [p_color[0],p_color[1],p_color[2]]
                value[1] = math.sqrt(math.sqrt(math.sqrt(abs(board[i][j]))))
                value = colorsys.hsv_to_rgb(value[0], value[1], value[2])
                pixels[i,j] = (int(value[0]*255),int(value[1]*255),int(value[2]*255)) # set the colour accordingly
            elif(board[i][j]<0):
                p_color = colorsys.rgb_to_hsv(player2_area[0], player2_area[1], player2_area[2])
                value = [p_color[0],p_color[1],p_color[2]]
                value[1] = math.sqrt(math.sqrt(math.sqrt(abs(board[i][j]))))
                value = colorsys.hsv_to_rgb(value[0], value[1], value[2])
                pixels[i,j] = (int(value[0]*255),int(value[1]*255),int(value[2]*255)) # set the colour accordingly
            else:
                pixels[i,j] = background
     
    
    img.save('board.gif')
コード例 #10
0
ファイル: main.py プロジェクト: inclement/fourierdroid
def phase_to_rgb(phase):
    frac = (phase + n.pi) / (2*n.pi)
    rgb = [min(255, int(j*255)) for j in hsv_to_rgb(frac, 1, 1)]
    return rgb
    return [val,val,val]
    colour = list(hsv_to_rgb(frac,1,1))
    return map(lambda j: int(j*255),colour)
コード例 #11
0
    def updateDamage(self):
        # recolor the percentage
        old_redness = self.redness
        self.redness = min(1.0, float(self.percent) / 300)
        # the lighter color first
        rgb_from = tuple(int(i * 255) for i in colorsys.hsv_to_rgb(0, old_redness, 1.0))
        rgb_to = tuple(int(i * 255) for i in colorsys.hsv_to_rgb(0, self.redness, 1.0))
        self.percent_sprites.recolor(self.percent_sprites.sheet, rgb_from, rgb_to)
        # the darker color next
        rgb_from = tuple(int(i * 255) for i in colorsys.hsv_to_rgb(0, old_redness, 0.785))
        rgb_to = tuple(int(i * 255) for i in colorsys.hsv_to_rgb(0, self.redness, 0.785))
        self.percent_sprites.recolor(self.percent_sprites.sheet, rgb_from, rgb_to)

        self.percent_sprite.image = pygame.Surface((196, 64), pygame.SRCALPHA, 32).convert_alpha()

        percent_string = str(int(self.percent))  # converting it to a string so we can iterate over it.
        length = 0
        for ch in percent_string:
            i = int(ch)
            self.percent_sprite.image.blit(self.percent_sprites.getImageAtIndex(i), (length, 0))
            length += self.kerning_values[i]

        # add the % sign at the end
        self.percent_sprite.image.blit(self.percent_sprites.getImageAtIndex(10), (length, 0))

        self.percent_sprite.image = pygame.transform.smoothscale(self.percent_sprite.image, (96, 32))
        length += self.kerning_values[10]
コード例 #12
0
ファイル: Generate.py プロジェクト: mattjoyce/SightWordImages
def generate(im_width, im_height, text, img_scale, fontfile, 
             jpg_quality, hsv_color):
    """Create a new jpg file.
    Render the text, in the middle
    Adjust the font size to utilize the space
    """
        
    text = str(text).replace("\n", "").strip()
    new_image = Image.new("RGB", (im_width, im_height), (0, 0, 0))
    draw = ImageDraw.Draw(new_image)

    fontsize = 1
    font = ImageFont.truetype(fontfile, fontsize)
    text_width, text_height = font.getsize(text)
    
    while (text_width < img_scale*im_width and 
            text_height < img_scale * im_height)  :
        fontsize += 1
        font = ImageFont.truetype(fontfile, fontsize)
        text_width, text_height = font.getsize(text)
        
    font = ImageFont.truetype(fontfile, fontsize-1)
    if hsv_color[0]==-1:
        color = colorsys.hsv_to_rgb(random(), hsv_color[1], hsv_color[2])
    else:    
        color = colorsys.hsv_to_rgb(hsv_color[0], hsv_color[1], hsv_color[2])
    color_rgb = tuple([int(256*x) for x in color])
    draw.text(((im_width-text_width) / 2, (im_height-text_height) / 2), 
                text, fill = (color_rgb), font=font)
    filename = text.translate(string.maketrans("",""), string.punctuation)+".jpg"
    new_image.save(filename, "jpeg",quality=jpg_quality)
    print filename
コード例 #13
0
ファイル: colorfade.py プロジェクト: C3MA/lightstick
def main(argv):
    w = Wall(24,17)
    while True:
        colx = random.random()
        print(colx)
        color = colorsys.hsv_to_rgb(colx, 1, 0.20)
        print(color[1])
        for i in range(0,len(w.sticks)):
            x = len(w.sticks)-1-i
            w.sticks[x].setAllLeds(int(color[0]*255),int(color[1]*255),int(color[2]*255))
            time.sleep(0.04)
        while True:
            col = random.random()
            if col+0.45 < colx or col-0.45 > colx:
                break
            print("reroll")
            print("reroll")
            print("reroll")
            print("reroll")
            print("reroll")
            print("reroll")
            print("reroll")
            print("reroll")
        print(col)
        color = colorsys.hsv_to_rgb(col, 1, 0.5)  
        print(color[1])
        for i in range(0,len(w.sticks)):
            w.sticks[i].setAllLeds(int(color[0]*255),int(color[1]*255),int(color[2]*255))
            time.sleep(0.04)
コード例 #14
0
ファイル: engulf.py プロジェクト: jceipek/Engulf
    def __init__(self, world):

        self.world = world
        self.radius = 5
        x = random.randint(int(world.window.width*0.05),int(world.window.width*0.95))
        y = random.randint(int(world.window.height*0.05),int(world.window.height*0.95))
        ps.Group.__init__(self, x=x, y=y) 

        self.rect = ps.Rect(x=-self.radius,y=-self.radius,width=10,height=10, 
                            color=(0,1,0,1))
        self.call_to_action = ps.Rect(x=-self.radius*2,y=-self.radius*2,width=20,height=20,
                            color=(0,0,0,0),stroke_color=(0,1,0,1), stroke_thickness=1)

        if random.random()>0.5:
            self.rect.color.values = colorsys.hsv_to_rgb(0.9,1,1) # Blue
            self.call_to_action.stroke_color.values = colorsys.hsv_to_rgb(0.9,1,1)
            self.type = "B"
        else:
            self.rect.color.values = colorsys.hsv_to_rgb(0.3,1,1) # Green
            self.call_to_action.stroke_color.values = colorsys.hsv_to_rgb(0.3,1,1)
            self.type = "G"

        self.add(self.rect)
        self.add(self.call_to_action)
        self.remove_me = False
コード例 #15
0
ファイル: fft_avg.py プロジェクト: mkawalec/masters
def plot_avg():
    maxlen = -1
    for filename in glob('/tmp/e-02/process0-output*'):
        with open(filename) as f:
            length = len(f.readlines())
            if length > maxlen:
                maxlen = length

    for filename in glob('/tmp/e-05/process0-output*'):
        with open(filename) as f:
            length = len(f.readlines())
            if length > maxlen:
                maxlen = length

    second = get_avg('/tmp/e-02/', maxlen)
    fifth = get_avg('/tmp/e-05/', maxlen)


    color1 = hsv_to_rgb(0, 0.7, 0.9)
    color2 = hsv_to_rgb(0.5, 0.7, 0.9)
    fig, ax = plt.subplots()
    ax.plot(fifth['x'], fifth['y'], label='$\lambda=10^{-5}$', color=color2)
    ax.plot(second['x'], second['y'], alpha=0.8, label='$\lambda=10^{-2}$', color=color1)
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.legend(loc=0)
    plt.subplots_adjust(bottom=0.15)
    ax.set_xlabel('frequency')
    savefig('fourier.png', dpi=600)
コード例 #16
0
ファイル: projects.py プロジェクト: Einarin/Observatory
 def css(count):
   grad_top = hsv_to_rgb(0.3 * count / projects.count(), 0.9, 0.5)
   grad_bottom = hsv_to_rgb(0.3 * count / projects.count(), 0.9, 0.9)
   border = hsv_to_rgb(0.3 * count / projects.count(), 0.9, 0.7)
   
   return """
     background:rgb({3},{4},{5});
     background-image: -webkit-gradient(linear, left bottom, left top,
       from(rgb({0},{1},{2})),
       to(rgb({3},{4},{5})));
     background-image: -moz-linear-gradient(100% 100% 90deg,
       rgb({0},{1},{2}),
       rgb({3},{4},{5})
     );
     border: 1px solid rgb({6},{7},{8});
     width:{9}px;display: block;""".format(
       int(grad_top[0] * 255),
       int(grad_top[1] * 255),
       int(grad_top[2] * 255),
       int(grad_bottom[0] * 255),
       int(grad_bottom[1] * 255),
       int(grad_bottom[2] * 255),
       int(border[0] * 255),
       int(border[1] * 255),
       int(border[2] * 255),
       int(424 * (1.0 * count / projects.count()))
     )
コード例 #17
0
ファイル: cm.py プロジェクト: neishm/pygeode
def build_stops(hues, sat, rval):
# {{{
  from colorsys import hsv_to_rgb
  nstops = len(hues) + 1
  stops = [dict(s=S) for S in np.linspace(0, 1, nstops)]
  flipped = False
  j = [0, 1]
  for i, h in enumerate(hues):
    r1, g1, b1 = hsv_to_rgb(np.fabs(h), sat[j[0]], rval[j[0]])
    r2, g2, b2 = hsv_to_rgb(np.fabs(h), sat[j[1]], rval[j[1]])
    if h < 0.:
      if flipped:
        r1, g1, b1 = 1., 1., 1.
      else:
        r2, g2, b2 = 1., 1., 1.
        j = [1, 0]
        flipped = True

    if i == 0:
      stops[i].update(dict(r=r1, g=g1, b=b1))
    else:
      stops[i].update(dict(r2=r1, g2=g1, b2=b1))
    stops[i+1].update(dict(r=r2, g=g2, b=b2))

  return stops
コード例 #18
0
ファイル: DataContainer.py プロジェクト: rpool/GWATools
    def SetColorsPerChr(self,
                        boGreyScale=bool,
                        NChr=int):
        HSV_tuples = None
        RGB_tuples = None
        if(boGreyScale):
            boGrey     = True
            GreyHSV    = (0.0,0.0,0.4)
            BlackHSV   = (0.0,0.0,0.0)
            HSV_tuples = []
            for i in range(NChr):
                if(boGrey):
                    HSV_tuples.append(GreyHSV)
                    boGrey = False
                else:
                    HSV_tuples.append(BlackHSV)
                    boGrey = True
            RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)
        else:
            HSV_tuples = [(x*1.0/NChr, 0.75, 0.75) for x in range(NChr)]
            RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)

        self.RGBTupleDict = {}
        for i in range(len(RGB_tuples)):
            Tuple = RGB_tuples[i]
            Chr   = str(i+1)
            self.RGBTupleDict[Chr] = Tuple
        return
コード例 #19
0
	def draw(self):
		background(0, 0, 0)
		last_beat = int(self.beat)
		self.beat += 1.0/7.5
		self.beat %= 16
		play = int(self.beat) != last_beat
		for y in xrange(16):
			beat_row = int(self.beat) == y
			for x in xrange(8):
				if self.grid[x][y]:
					h = x / 8.0
					r, g, b = hsv_to_rgb(h, 1, 1)
					if play and int(self.beat) == y:
						play_effect(self.sounds[x])
					if beat_row:
						h = x / 8.0
						r, g, b = hsv_to_rgb(h, 1, 1)
						fill(r, g, b)
					else:
						r, g, b = hsv_to_rgb(h, 1, 0.5)
						fill(r, g, b)
				elif beat_row:
					fill(1, 1, 1)
				else:
					fill(0.50, 0.50, 0.50)
				rect(x*(self.bounds.w/4), y*(self.bounds.h/9), self.bounds.w/4, self.bounds.h/9)
コード例 #20
0
ファイル: micdmx.py プロジェクト: drewp/bigeye
def writeOut():
    global prevs, envPrevs, envLo, envHi
    now = time.time()

    envPrevs = (envPrevs + [currentLevel])[-50:]
    
    prevs = (prevs + [currentLevel])[-config['avgPrevs']:]
    avg = sum(prevs) / len(prevs)

    yEnv = max(0, avg - envLo) / (envHi - envLo)

    envLo = min(envPrevs)
    envHi = max(envPrevs)
    
    
    y = max(0, min(1, (yEnv + config['levelOffset']) /
                   config['levelMax']))
    y = math.pow(y, config['gamma'])
    if y > .8 and now > state['lastHueTime'] + .3:
        state['dominantHue'] = .5 - state['dominantHue']#random.random()
        state['lastHueTime'] = time.time()
        print "hue", state['dominantHue']

    chans = [0] * 90

    h = state['dominantHue'] + y / 5
    chans[73-1:76-1] = list(colorsys.hsv_to_rgb(h, 1, y))
    chans[80-1:83-1] = list(colorsys.hsv_to_rgb(h, 1, y))
    chans[88-1:91-1] = list(colorsys.hsv_to_rgb(h, .4, y)) # center
    chans[87-1] = .84

    dmxclient.outputlevels(chans, twisted=True)
コード例 #21
0
ファイル: funkyavatar.py プロジェクト: atizo/funkyavatar
    def __set_gradient_pattern(self, cr, tx, ty):
        # use gray if no color is given
        r1, g1, b1 = 0.2, 0.2, 0.2
        r2, g2, b2 = 0.8, 0.8, 0.8

        if self.color:
            r, g, b = self.color
            r, g, b = float(r)/255, float(g)/255, float(b)/255

            h, s, v = colorsys.rgb_to_hsv(r, g, b)
            r1, g1, b1 = colorsys.hsv_to_rgb(h, s, min(v+0.2, 1.0))

            h, s, v = colorsys.rgb_to_hsv(r, g, b)
            r2, g2, b2 = colorsys.hsv_to_rgb(h, s, max(v-0.2, 0))

        if self.gradient_direction == 1:
            pat = cairo.LinearGradient(0.0, 0.0, 0.0, 200.0-ty)
        elif self.gradient_direction == 2:
            pat = cairo.LinearGradient(0.0, 200.0-ty, 0.0, 0.0)
        elif self.gradient_direction == 3:
            pat = cairo.LinearGradient(0.0, 0.0, 200.0-tx, 0.0)
        else:
            pat = cairo.LinearGradient(200.0-tx, 0.0, 0.0, 0.0)

        pat.add_color_stop_rgba(0, r2, g2, b2, 0.8)
        pat.add_color_stop_rgba(1, r1, g1, b1, 0.8)
        cr.set_source(pat)
コード例 #22
0
ファイル: snake.py プロジェクト: ruanpienaar/python
def uni_show(prev_x, prev_y):
    a = np.random.rand(1)
    b = np.random.rand(1)
    c = np.random.rand(1)
    rgb_on  = colorsys.hsv_to_rgb(a, b, c)
    rgb_off = colorsys.hsv_to_rgb(0.5, 0.5, 0.1)

    r_on  = int(rgb_on[0]*255.0)
    g_on  = int(rgb_on[1]*255.0)
    b_on  = int(rgb_on[2]*255.0)

    r_off = int(rgb_off[0]*255.0)
    g_off = int(rgb_off[1]*255.0)
    b_off = int(rgb_off[2]*255.0)	

    a = np.random.rand(1)
    x = int(a[0] * 8)-1
    b = np.random.rand(1)	
    y = int(b[0] * 8)-1
    
    #print x, y
    
    if x < 0:
      x = 0
    if y < 0:
      y = 0

    unicorn.set_pixel(x, y, r_on, g_on, b_on)
    unicorn.set_pixel(prev_x, prev_y, r_off, g_off, b_off)

    unicorn.show()
    return x, y
コード例 #23
0
ファイル: surv_prob_plot.py プロジェクト: mkawalec/masters
def gen_surv_plot():
    with open('24-1.05-survival_probability') as f:
        points = map(lambda x: (float(x.split(' ')[0]),
                                float(x.split(' ')[1])),
                     f.readlines())

    fits = gen_fits(0.1, 0.1)
    a0, a1= fits[24][1.05]['avg']
    color1 = hsv_to_rgb(0, 0.7, 0.9)
    color2 = hsv_to_rgb(0.5, 0.7, 0.9)

    fig, ax = plt.subplots()
    ax.plot(map(lambda x: x[0], points), map(lambda x: x[1], points),
            label="Data", marker=',', color=color1)
    ax.plot(map(lambda x: x[0], points),
            map(lambda x: model_function(x, a0, a1),
                map(lambda x: x[0], points)),
            label="Fit", color=color2, alpha=0.7)

    #plt.title('Data and fit at R=1.06')
    ax.legend(loc=0)
    ax.set_ylabel('$S(t)$')
    ax.set_xlabel('$t$')
    ax.set_xlim([0, 7000])
    plt.hlines(0.1, 0, 7000, linestyles='dashed')
    plt.text(5000, 0.11, 'Fit threshold')
    plt.subplots_adjust(bottom=0.15)

    savefig('surv_prob.png', dpi=600)
コード例 #24
0
ファイル: fft_avg.py プロジェクト: mkawalec/masters
def plot_portrait():
    with open('/tmp/e-02/process0-output16') as f:
        lines = f.readlines()
        pos02 = map(lambda y: map(lambda x: float(x), y.split(' ')[:3]),
                                  filter(lambda z: len(z.split(' ')) > 2,
                                         lines))

    with open('/tmp/e-05/process0-output02') as f:
        lines = f.readlines()
        pos05 = map(lambda y: map(lambda x: float(x), y.split(' ')[:3]),
                                  filter(lambda z: len(z.split(' ')) > 2,
                                         lines))

    fig, ax = plt.subplots()
    color1 = hsv_to_rgb(0, 0.7, 0.9)
    color2 = hsv_to_rgb(0.5, 0.7, 0.9)

    ax.plot(map(lambda x: x[1], pos02), map(lambda x: x[2], pos02),
            label='$\lambda=10^{-2}$', color=color1)
    ax.plot(map(lambda x: x[1], pos05), map(lambda x: x[2], pos05),
            label='$\lambda=10^{-5}$', color=color2, alpha=0.8)
    ax.legend(loc=0)
    ax.set_xlabel('l2 norm of $u(t)$')
    ax.set_ylabel('l2 norm of $v(t)$')
    plt.subplots_adjust(bottom=0.15)
    savefig('phase.png', dpi=600)
コード例 #25
0
ファイル: fractaldots.py プロジェクト: sparks/algoshirt
	def circle(self, cr, matrix, number, angle, scale, distance, fill_hue, fill_hue_incr, stroke_hue, stroke_hue_incr, depth, max_depth):
		if depth >= max_depth:
			return

		cr.set_matrix(matrix)

		cr.arc(0, 0, 100, 0, 2*math.pi)

		stroke_color = colorsys.hsv_to_rgb(stroke_hue, 0.5, 0.2)

		cr.set_source_rgb(stroke_color[0], stroke_color[1], stroke_color[2])
		cr.set_line_width(40)
		cr.stroke_preserve()

		fill_color = colorsys.hsv_to_rgb(fill_hue, 1, 1)

		cr.set_source_rgb(fill_color[0], fill_color[1], fill_color[2])
		cr.fill()

		for i in range(number):
			cr.set_matrix(matrix)
			cr.rotate(angle*i)
			cr.translate(distance*100, 0)
			cr.scale(scale, scale)
			sub_matrix = cr.get_matrix()
			self.circle(cr, sub_matrix, number, angle, scale, distance, fill_hue+fill_hue_incr, fill_hue_incr, stroke_hue+stroke_hue_incr, stroke_hue_incr, depth+1, max_depth)
コード例 #26
0
ファイル: sometext.py プロジェクト: mlsteele/curtain
    def draw(self):
        # speed defined here
        h = math.fmod(self.time / 3, 2)
        if h >= 1:
            h = 2 - h

        x = int(round(self.n))
        offset = 1.0 / (len(self.text) + 1)

        self.canvas.clear(*hsv_to_rgb(h, 1, 0.03))

        h = math.fmod(h + offset, 1)

        length = -1
        for c in self.text:
            length += letters[c].width + 1

        x = (width - length + 1) / 2

        for c in self.text:
            r, g, b = hsv_to_rgb(h, 1, brightness)
            h = math.fmod(h + offset, 1)

            letter = letters[c]
            self.canvas.add_letter(letter, x, 0, r, g, b)
            x += letter.width + 1

        if self.n > 15 or self.n < -15:
            self.d = not self.d
コード例 #27
0
ファイル: spppdd_lissajous.py プロジェクト: polygon/spppdd
def draw_lissajous(a, b, h):
    t = np.arange(0, 16*np.pi, np.pi/1024)
    x = (159 * np.sin(a*t) + 159).astype(np.uint)
    y = (119 * np.cos(b*t) + 119).astype(np.uint)
    picture = np.zeros((320, 240, 3))
    picture[:, :, :] = colorsys.hsv_to_rgb(h, 1.0, 1.0)
    picture[x, y, :] = np.array(colorsys.hsv_to_rgb((h+0.5)%1.0, 1.0, 1.0))
    return picture
コード例 #28
0
ファイル: filenode.py プロジェクト: SalinderSidhu/Diskmap
 def __setRandomColours(self):
     '''Set the gradient and mouse hover colours using an aesthetically
     pleasing HSV colour palette. The same hue value is used for all colours
     with varying degrees of saturation to generate different shades.'''
     hue = randint(0, 360) / 360
     self.tColour = tuple(i * 255 for i in hsv_to_rgb(hue, 0.6, 0.95))
     self.bColour = tuple(i * 255 for i in hsv_to_rgb(hue, 1, 0.95))
     self.hColour = tuple(i * 255 for i in hsv_to_rgb(hue, 0.05, 0.95))
コード例 #29
0
ファイル: Control.py プロジェクト: saaperezru/Quantum
 def getColor(self,number):
   """Returns an HTML color with a certain level of black or red (depending on the sign of the numbre provided)"""
   if number >= 0:
     ret = cs.hsv_to_rgb(0,0,1-abs(number/self.maxp))
   else:
     ret = cs.hsv_to_rgb(0,abs(number/self.maxn),1)
   hexcolor = '#%02x%02x%02x' % (ret[0]*255,ret[1]*255,ret[2]*255)
   return hexcolor 
コード例 #30
0
ファイル: colorselector.py プロジェクト: guozanhua/nuipaint
 def on_value_change(value=self.slider.slider_color):
     value = rgb_to_hsv(self.slider.slider_color[0], self.slider.slider_color[1], self.slider.slider_color[2])
     h, s, v = value[0], value[1], value[2]
     if self.slider._value <= 1.0:
         s = self.slider._value
     else:
         v = 2 - self.slider._value
     Observer.get("canvas").set_brush_color(hsv_to_rgb(h, s, v))
     self.slider.slider_color = hsv_to_rgb(h, s, v)
コード例 #31
0
ファイル: imagegen.py プロジェクト: graemeblackwood/amulets
def get_fingerprint_colors(base):
    return (normalise_tuple(colorsys.hsv_to_rgb(base, 0.4, 1.0), 255),
            normalise_tuple(colorsys.hsv_to_rgb(base, 0.4, 0.75), 255))
コード例 #32
0
imgx, imgy = 512, 512  # IMAGE DIMENSIONS
tmax = 256  # MAXIMUM ITERATIONS
xa3, xb3 = -0.1475, -0.1425
ya3, yb3 = 0.255, 0.26

image = Image.new("RGB", (imgx, imgy))  # CREATES IMAGE ACCORDING TO DIMENSIONS

cx, cy = -.79, .15
for x in range(imgx):
    for y in range(imgy):
        # Z starts at X,Y instead of 0,0
        zx = (x * (xb3 - xa3) / (imgx - 1) + xa3)
        zi = (y * (yb3 - ya3) / (imgy - 1) + ya3)
        for t in range(tmax):
            # same equations as Mandelbrot
            absz = float(((zx**2) + (zi**2))**0.5)
            if absz >= 2.0:
                break
            zx, zi = float((zx * zx - zi * zi) +
                           cx), float((zi * zx + zx * zi) + cy)
        # cycles through HSV starting from yellow
        R, G, B = int(
            colorsys.hsv_to_rgb(
                (0.297222 - (t / tmax)) % 1, 1, 1.36)[0] * 255), int(
                    colorsys.hsv_to_rgb(
                        (0.297222 - (t / tmax)) % 1, 1, 1.36)[1] * 255), int(
                            colorsys.hsv_to_rgb(
                                (0.297222 - (t / tmax)) % 1, 1, 1.36)[2] * 255)
        image.putpixel((x, imgy - 1 - y), (R, G, B))

image.save("julia.png")
コード例 #33
0
	def _random_colors(self, N, bright=True):
		hsv = [(float(i / N), 1, 1.0) for i in range(N)]
		colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
		random.shuffle(colors)

		return colors
コード例 #34
0
# create a palette for mapping heat values onto colours
palette = [0] * 256
for i in range(0, 256):
    h = i / 5.0
    h /= 360.0
    s = (1.0 / (math.sqrt(i / 50.0) + 0.01))
    s = min(1.0, s)
    s = max(0.0, s)

    v = i / 200.0
    if i < 60:
        v = v / 2
    v = min(1.0, v)
    v = max(0.0, v)

    r, g, b = colorsys.hsv_to_rgb(h, s, v)
    palette[i] = (int(r * 255.0), int(g * 255.0), int(b * 255.0))


def set_pixel(b, x, y, v):
    b[y * 16 + x] = int(v)  # edited 16 to 8


def get_pixel(b, x, y):
    # out of range sample lookup
    if x < 0 or y < 0 or x >= 16 or y >= 16:  # edited 16 to 8
        return 0

    # subpixel sample lookup
    if isinstance(x, float) and x < 7:  # edited 15 to 7
        f = x - int(x)
コード例 #35
0
for i in range(28):
    # Write labels
    cell = sheet.cell(column=i + 2, row=1, value=sorted(char_map.keys())[i])
    cell.alignment = Alignment(text_rotation=90, horizontal='center')
    sheet.cell(column=1, row=i + 2, value=sorted(char_map.keys())[i])

    min_confusion = confusionmap[i][0:28].min()
    max_confusion = confusionmap[i][0:28].max()
    # write cell values
    for j in range(28):
        col = j + 2
        row = i + 2
        value = confusionmap[i][j]
        confusion = value / (max_confusion - min_confusion * 1.0)

        rgb = colorsys.hsv_to_rgb(hsv[0], confusion, hsv[2])
        color = str(format(int(rgb[0] * 255), '02X')) + str(
            format(int(rgb[1] * 255), '02X')) + str(
                format(int(rgb[2] * 255), '02X'))

        cell = sheet.cell(column=col, row=row, value=value)
        cell.fill = PatternFill(fgColor=color, fill_type="solid")

sheet.cell(column=1, row=1, value="real/predicted")

sheet.cell(column=1, row=30, value="Sample size:").font = Font(bold=True)
sheet.cell(column=3, row=30, value=str(len(imagePaths))).font = Font(bold=True)

sheet.cell(column=1, row=31, value="Total loss:").font = Font(bold=True)
sheet.cell(column=3, row=31, value=str(int(loss))).font = Font(bold=True)
コード例 #36
0
    if y > 1.9 and not direction == 1:
        direction = 1
        t.append(millis() - t_start)
        t_start = millis()
        t = t[-5:]

    if len(t) > 0:
        total_time = float(sum(t)) / len(t)

    offset = ((millis() - t_start) / total_time)

    # offset += direction * 10

    offset = min(1.0, offset)
    offset = max(0.0, offset)

    hue = offset

    if direction == -1:
        hue = 1.0 - offset

    r, g, b = [int(c * 255.0) for c in hsv_to_rgb(hue, 1.0, 1.0)]

    for x in range(8):
        blinkt.set_pixel(x, r, g, b)

    blinkt.show()

    time.sleep(0.0001)
コード例 #37
0
def draw_boxes(image,
               boxes,
               scores,
               labels,
               classes,
               detection_size,
               font='./files/font/FiraMono-Medium.otf',
               show=True):
    if boxes is None:
        return image, False

    draw = ImageDraw.Draw(image)
    # draw settings
    font = ImageFont.truetype(font=font,
                              size=np.floor(2e-2 *
                                            image.size[1]).astype('int32'))
    hsv_tuples = [(x / len(classes), 0.9, 1.0) for x in range(len(classes))]
    colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
    colors = list(
        map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
            colors))

    warning = False

    det_list = [2, 3, 7]

    for i in range(len(labels)):  # for each bounding box, do:
        if labels[i] in det_list:
            mid_x = (boxes[i][0] + boxes[i][2]) / detection_size[0] / 2
            mid_y = (boxes[i][1] + boxes[i][3]) / detection_size[1] / 2

            re_width = (boxes[i][2] - boxes[i][0]) / detection_size[0]
            re_height = (boxes[i][3] - boxes[i][1]) / detection_size[1]
            # relative = np.sqrt(re_height**2+re_width**2)
            relative = round(((1 - re_width)**4),
                             2)  # **4宽度变化反映在relative上的效果更加强烈

            bbox, score, label = boxes[i], scores[i], classes[labels[i]]
            bbox_text = "%s %.2f %.2f" % (label, score, relative)
            color = colors[labels[i]]

            if 0.3 < mid_x < 0.7 and relative < 0.3:
                bbox_text = "%s" % ("WARNING")
                warning = True
                color = (255, 0, 255)

            text_size = draw.textsize(bbox_text, font)
            detection_size, original_size = np.array(detection_size), np.array(
                image.size)
            ratio = original_size / detection_size
            bbox = list((bbox.reshape(2, 2) * ratio).reshape(-1))
            draw.rectangle(bbox, outline=color, width=3)
            text_origin = bbox[:2] - np.array([0, text_size[1]])
            draw.rectangle(
                [tuple(text_origin),
                 tuple(text_origin + text_size)],
                fill=color)
            # # draw bbox
            draw.text(tuple(text_origin), bbox_text, fill=(0, 0, 0), font=font)
    image.show() if show else None
    return image, warning
コード例 #38
0
ファイル: util.py プロジェクト: cnheider/client-1
def class_colors(class_count):
    # make class 0 black, and the rest equally spaced fully saturated hues
    return [[0, 0, 0]] + [
        colorsys.hsv_to_rgb(i / (class_count - 1.0), 1.0, 1.0)
        for i in range(class_count - 1)
    ]
コード例 #39
0
 def rgb(self):
     return colorsys.hsv_to_rgb(self.hue, self.saturation, self.value)
コード例 #40
0
def test_FOV(M=10):
    env = rave.Environment()
    env.Load('../envs/pr2-test.env.xml')
    env.SetViewer('qtcoin')
    env.GetViewer().SendCommand(
        'SetFiguresInCamera 1')  # also shows the figures in the image
    time.sleep(1)
    robot = env.GetRobots()[0]

    convexify_workspace(env, robot)

    cam = robot.GetAttachedSensor('head_cam').GetSensor()
    type = rave.Sensor.Type.Camera
    cam_geom = cam.GetSensorGeometry(type)

    height, width, _ = cam_geom.imagedata.shape
    F = .01  # real focal length in meters
    max_range = 5.

    fov = FOV(robot, cam_geom.KK, height, width, F, max_range)

    cam_pose = tfx.pose([0, 0, 0.05], frame='wide_stereo_optical_frame')

    start = time.time()
    beams = fov.get_beams(cam_pose)
    print('beams time: {0}'.format(time.time() - start))

    start = time.time()
    border = fov.get_border(beams)
    print('border time: {0}'.format(time.time() - start))

    IPython.embed()
    return

    table = env.GetKinBody('table')
    base = table.GetLink('base')
    extents = base.Geometry.GetBoxExtents(base.GetGeometries()[0])

    table_pos = tfx.pose(table.GetTransform()).position
    # assume table has orientation np.eye(3)
    x_min, x_max = table_pos.x - extents[0], table_pos.x + extents[0]
    y_min, y_max = table_pos.y - extents[1], table_pos.y + extents[1]
    z_min, z_max = table_pos.z + extents[2], table_pos.z + extents[2] + .2

    particles = list()
    for i in xrange(M):
        x = random_within(x_min, x_max)
        y = random_within(y_min, y_max)
        z = random_within(z_min, z_max)
        particles.append(np.array([x, y, z]))

    signed_distances = list()
    for i in xrange(M):
        print(i)
        signed_distances.append(
            fov.signed_distance(particles[i], beams, border))

    min_sd = min(signed_distances)
    sd_hue = np.array(signed_distances) + abs(min_sd)
    sd_hue = (1 / 3.0) * (sd_hue / max(sd_hue))
    for p, h in zip(particles, sd_hue):
        rgb = colorsys.hsv_to_rgb(h, 1, 1)
        handles.append(utils.plot_point(env, p, color=rgb))

    #fov.plot(beams)
    for tri in border:
        tri.plot(env)

    IPython.embed()
コード例 #41
0
def main():
    img = Image.open('/media/maxiaoyu/data/training_data/images/macaw2.jpg')
    img.load()
    #img.show()

    data = np.asarray(img)
    ds = data.shape

    print(data[1, 1, 1])

    #zoom in
    """
    zoom_scale = np.random.random((1,))[0]
    while zoom_scale > 0.3:
        zoom_scale = np.random.random((1,))[0]


    outimg_w = int(img.width * (1 + zoom_scale))
    outimg_h = int(img.height * (1 + zoom_scale))

    outimg = img.resize((outimg_w, outimg_h))

    outimg.show()
    """


    # hsv operation
    random_factor2 = random.uniform(0.7, 1.4)
    random_factor3 = random.uniform(-0.1, 1.0)
    random_factor4 = random.uniform(-0.1, 1.0)
    hsv = rgb_to_hsv(data)
    print(hsv.shape)
    """
    for w in range(0, hsv.shape[0]):
        for h in range(0, hsv.shape[1]):
            s = hsv[w, h, 1]
            s = s * random_factor2 + random_factor3
            hsv[w, h, 1] = s

            v = hsv[w, h, 2]
            v = v * random_factor2 + random_factor3
            hsv[w, h, 2] = v
    """
    #s
    hsv[:, :, 1] *= random_factor2
    hsv[:, :, 1] += random_factor3
    #v
    hsv[:, :, 2] *= random_factor2
    hsv[:, :, 2] += random_factor3
    #h
    hsv[:, :, 0] += random_factor4

    rgbimg = hsv_to_rgb(hsv)
    outimg = Image.fromarray(rgbimg, mode="RGB")
    outimg.show('one')

    data2 = np.zeros(ds)
    for wi in range(0, ds[0]):
        for hi in range(0, ds[1]):
            r = data[wi, hi, 0]
            g = data[wi, hi, 1]
            b = data[wi, hi, 2]
            h, s, v = colorsys.rgb_to_hsv(r, g, b)
            h += random_factor4

            s *= random_factor2
            s += random_factor3

            v *= random_factor2
            v += random_factor3
            rn, gn, bn = colorsys.hsv_to_rgb(h, s, v)
            #rn *= 255
            #gn *= 255
            #bn *= 255
            data2[wi, hi, 0] = rn
            data2[wi, hi, 1] = gn
            data2[wi, hi, 2] = bn

    outimg2 = Image.fromarray(data2, mode="RGB")
    outimg2.show()

    #ci = scipy.misc.toimage(data2, cmin=0.0, cmax=1.0)
    #ci.show()


    print('show end')

    print('epoch : {0}, , running time : {1:.2f}m , left estimate : {2:.2f}m'.format(1, 0.345,
                                                                                     0.456))
コード例 #42
0
    def __init__(self,
                 pos,
                 color=(0, 125, 255),
                 radius=15,
                 is_head=False,
                 is_self=False):
        pygame.sprite.Sprite.__init__(self)
        self.pos = tuple(pos)
        self.color = tuple(color)
        self.radius = radius
        self.is_head = is_head
        self.is_self = is_self
        global seg_images, head_images, base_head, base_seg, color_precision
        '''try:
            self.image = images[(self.color,radius)]
        except:
            self.image = pygame.Surface([self.radius*2,self.radius*2])
            pygame.draw.ellipse(self.image,self.color,self.image.get_rect())
            self.image.set_colorkey((0,0,0))
            #print(f"type(color): {type(color)} is_head: {is_head}")
            images[(self.color,radius)] = self.image'''
        if self.is_head or True:
            self.image = pygame.Surface((self.radius * 2, self.radius * 2))
            self.image.fill((255, 255, 0))
            #self.image = pygame.transform.rotate(pygame.transform.scale(head_img,(self.radius*2,self.radius*2)),-head_rot)
        self.rect = self.image.get_rect()
        self.angle = 0
        self.goal_angle = 0

        self.rect.x = self.pos[0] - self.rect.width / 2
        self.rect.y = self.pos[1] - self.rect.height / 2

        #self.head_img = base_head.copy()#pygame.image.load("/home/USER/bin/python_io/head.png")
        if is_head:
            head_img = base_head.copy()
            #print("YAY!")
            #time.sleep(1)
        self.seg_img = base_seg.copy(
        )  #pygame.image.load("/home/USER/bin/python_io/segment.png")
        #seg_color = (240,10,128)
        self.seg_hue = round(
            colorsys.rgb_to_hsv(*self.color)[0], color_precision)
        self.head_hue = self.seg_hue
        if parsed_args['render_simple']:
            self.seg_hue = 268 / 360
            self.head_hue = 268 / 360
            if not self.is_self:
                self.seg_hue = 5 / 360
                self.head_hue = 5 / 360
        if not self.is_head:
            try:
                #print("found matching segment!")
                self.seg_img = seg_images[(self.seg_hue, self.radius)]
            except:
                for x in range(self.seg_img.get_width()):
                    for y in range(self.seg_img.get_height()):
                        #mult = (seg_img.get_at((x,y))[0]/255)
                        #sc = seg_color
                        #col = (round(sc[0]*mult),round(sc[1]*mult),round(sc[2]*mult))
                        rgb = self.seg_img.get_at((x, y))[:3]
                        hsv = colorsys.rgb_to_hsv(*rgb)
                        col = colorsys.hsv_to_rgb(self.seg_hue, hsv[1], hsv[2])
                        col = (int(col[0]), int(col[1]), int(col[2]),
                               self.seg_img.get_at((x, y))[3])
                        self.seg_img.set_at((x, y), col)
                #seg_img.set_colorkey((0,0,0))
                seg_images[(self.seg_hue, self.radius)] = self.seg_img
        if is_head:
            #print("heads are cool!")
            try:
                #self.head_hue = 0.5
                self.head_img = head_images[(self.head_hue,
                                             self.radius)].copy()
                #self.image = self.head_img
            except:
                #print("original head!")
                #self.head_hue = 0.5
                #print("1")
                #self.head_img = base_head.copy()
                temp_img = head_img.copy(
                )  #pygame.Surface((head_img.get_width(),head_img.get_height()))
                for x in range(head_img.get_width()):
                    for y in range(head_img.get_height()):
                        #mult = (seg_img.get_at((x,y))[0]/255)
                        #sc = seg_color
                        #col = (round(sc[0]*mult),round(sc[1]*mult),round(sc[2]*mult))
                        rgb = head_img.get_at((x, y))[:3]
                        hsv = colorsys.rgb_to_hsv(*rgb)
                        #print(f"head_hue:{self.head_hue}")
                        col = colorsys.hsv_to_rgb(self.head_hue, hsv[1],
                                                  hsv[2])
                        col = (int(col[0]), int(col[1]), int(col[2]),
                               head_img.get_at((x, y))[3])
                        #self.head_img.set_at((x,y),col)
                        temp_img.set_at((x, y), col)
                        if rgb != (0, 0, 0) or col[:3] != (0, 0, 0):
                            pass  #print(f"Color was {rgb}, Color is: {col[:3]}, Pos ({x},{y})")
                #print("ONE!")
                head_images[(
                    self.head_hue,
                    self.radius)] = temp_img.copy()  #self.head_img.copy()
                self.head_img = temp_img.copy()
                #self.image = temp_img.copy()
                #print("TWO!")
        if self.is_head:
            self.image = pygame.transform.rotate(
                pygame.transform.scale(self.head_img,
                                       (self.radius * 2, self.radius * 2)),
                -head_rot)
        else:
            self.image = pygame.transform.rotate(
                pygame.transform.scale(self.seg_img,
                                       (self.radius * 2, self.radius * 2)),
                -math.degrees(self.angle))
コード例 #43
0
 def setHue(self, hue):
     r, g, b = colorsys.hsv_to_rgb(hue, 1, 1)
     self.setRGB(r * 255, g * 255, b * 255)
コード例 #44
0
                Asm.WFI(0b10),

                # Palette magic, rainbow for rbrenderer
                *chain(*[[
                    Asm.MOV_R0(0x3000_0104),
                    Asm.WRITE_IMM(i * 0x08040201),
                    Asm.MOV_R0(0x3000_0108),
                    Asm.WRITE_IMM(1 << (i % 32)),
                    Asm.MOV_R0(0x3000_010c),
                    Asm.WRITE_IMM(1 << (i % 32)),
                    Asm.MOV_R0(0x3000_0110),
                    Asm.WRITE_IMM(0b01010101_01010101_01010101_01010101 << (i % 2)),
                    Asm.MOV_R0(0x3000_0114),
                    Asm.WRITE_IMM(0b01010101_01010101_01010101_01010101 << (i % 2)),
                    Asm.MOV_R0(0x3000_0008),
                    Asm.WRITE_IMM(rgb_to_uint32(hsv_to_rgb(i / 255, 1.0, 0.5))),
                    Asm.MOV_R0(0x3000_000C),
                    Asm.WRITE_IMM(rgb_to_uint32(hsv_to_rgb(i / 255, 1.0, 1.0))),
                    Asm.WFI(0b01),
                ] for i in range(255)]),

                # Patterns
                *chain(*[[
                    Asm.MOV_R0(0x3000_0100 + 4 * i), Asm.WRITE_IMM((1 << (i+1)) - 1),
                ] for i in range(10)]),

                Asm.JMP(0),
            ]

class GFXDemoApplet(Applet, applet_name="gfxdemo"):
    help = "Graphics demo"
コード例 #45
0
ファイル: predictor.py プロジェクト: tarzan9inc/f3pixel
    def ret_frame(cls, image):
        # Generate colors for drawing bounding boxes.
        hsv_tuples = [(x / 10, 1., 1.) for x in range(10)]
        colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
        colors = list(
            map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
                colors))
        np.random.seed(10101)  # Fixed seed for consistent colors across runs.
        np.random.shuffle(
            colors)  # Shuffle colors to decorrelate adjacent classes.
        np.random.seed(None)  # Reset seed to default.

        start = timer()

        model_image_size = (608, 608)
        class_names = cls._get_class()

        new_image_size = (image.width - (image.width % 32),
                          image.height - (image.height % 32))
        boxed_image = letterbox_image(image, new_image_size)
        image_data = np.array(boxed_image, dtype='float32')

        image_data /= 255.
        image_data = np.expand_dims(image_data, 0)  # Add batch dimension.

        image_shape = [image.size[1], image.size[0]]

        out_boxes, out_scores, out_classes = cls.compute_output(
            image_data, image_shape)

        Car_result_ALL = []
        Pedestrian_result_ALL = []
        all_result = []

        font = ImageFont.truetype(font='../box_font/FiraMono-Medium.otf',
                                  size=np.floor(3e-2 * image.size[1] +
                                                0.5).astype('int32'))

        thickness = (image.size[0] + image.size[1]) // 300

        for i, c in reversed(list(enumerate(out_classes))):
            predicted_class = class_names[c]
            box = out_boxes[i]
            score = out_scores[i]

            label = '{}_{:.2f}_{}'.format(
                predicted_class, score,
                str(cls.IDvalue))  #put the ID for each obj
            draw = ImageDraw.Draw(image)
            label_size = draw.textsize(label, font)

            top, left, bottom, right = box
            top = max(0, np.floor(top + 0.5).astype('int32'))
            left = max(0, np.floor(left + 0.5).astype('int32'))
            bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))
            right = min(image.size[0], np.floor(right + 0.5).astype('int32'))

            #JSON 形式の時はint32()未対応のため -> int()に変換する
            top = int(top)
            left = int(left)
            bottom = int(bottom)
            right = int(right)

            if top - label_size[1] >= 0:
                text_origin = np.array([left, top - label_size[1]])
            else:
                text_origin = np.array([left, top + 1])

            #1 予測結果より次のFrameの物体位置を予測
            #nxt_result_txt = ' {},{},{},{},{}'.format(left, top, right, bottom, c)

            #2 検出したbox_sizeを計算する 設定した閾値1024pix**2
            sq_bdbox = (bottom - top) * (right - left)

            if sq_bdbox >= 1024:  #矩形サイズの閾値
                if predicted_class == 'Car' or predicted_class == 'Pedestrian':  # Car or Pedes
                    # My kingdom for a good redistributable image drawing library.
                    for i in range(thickness):
                        draw.rectangle(
                            [left + i, top + i, right - i, bottom - i],
                            outline=colors[c])
                    draw.rectangle(
                        [tuple(text_origin),
                         tuple(text_origin + label_size)],
                        fill=colors[c])
                    draw.text(text_origin, label, fill=(0, 0, 0), font=font)
                    del draw

        end = timer()
        print("1フレームの処理時間 = ", end - start)
        return image
コード例 #46
0
ファイル: rainbox.py プロジェクト: FuriKuri/blinkt-rainbow
#!/usr/bin/env python

import colorsys
import time
import blinkt

spacing = 360.0 / 16.0
hue = 0

blinkt.set_clear_on_exit()
blinkt.set_brightness(0.035)

while True:
  hue = int(time.time() * 100) % 360
  for x in range(blinkt.NUM_PIXELS):
      offset = x * spacing
      h = ((hue + offset) % 360) / 360.0
      r, g, b = [int(c*255) for c in colorsys.hsv_to_rgb(h, 1.0, 1.0)]
      blinkt.set_pixel(x, r, g, b)

  blinkt.show()
  time.sleep(0.001)
コード例 #47
0
 def _get_random_xy_color(self):
     random_color = colorsys.hsv_to_rgb(random.random(), 1, 1)
     random_color = tuple([255 * x for x in random_color])
     return self.converter.rgbToCIE1931(*random_color)
コード例 #48
0
ファイル: detection_main.py プロジェクト: itamar8910/FlyEye
	anchors = [float(x) for x in anchors.split(',')]
	anchors = np.array(anchors).reshape(-1, 2)

yolo_model_keras = load_model(model_path)

# Verify model, anchors, and classes are compatible
num_of_classes = len(class_tags)
num_of_anchors = len(anchors)
model_output_channels = yolo_model_keras.layers[-1].output_shape[-1]

model_image_size = yolo_model_keras.layers[0].input_shape[1:3]
is_fixed_size = model_image_size != (None, None)

# Generate colors for drawing bounding boxes.
hsv_tuples = [(x / len(class_tags), 1., 1.) for x in range(len(class_tags))]
colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
colors = list(
	map(
		lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
		colors))
random.seed(10101)  # Fixed seed for consistent colors across runs.
random.shuffle(colors)  # Shuffle colors to decorrelate adjacent classes.
random.seed(None)  # Reset seed to default.

# Generate output tensor targets for filtered bounding boxes.
yolo_outputs = yolo_head(yolo_model_keras.output, anchors, len(class_tags))
input_image_shape = K.placeholder(shape=(2, ))
boxes, scores, classes = yolo_eval(
	yolo_outputs,
	input_image_shape,
	score_threshold=score_threshold,
コード例 #49
0
 def addObject(self, color=None):
     label = self.labelmgr.request()
     if color is None:
         color = colorsys.hsv_to_rgb(numpy.random.random(), 1.0, 1.0)
     self.setColor(label, color)
     return label
コード例 #50
0
 def set_pixel_hsv(self, x, y, h, s=1.0, v=1.0):
     r, g, b = [int(n * 255) for n in colorsys.hsv_to_rgb(h, s, v)]
     self.set_pixel(x, y, r, g, b)
コード例 #51
0
ファイル: Elements.py プロジェクト: rocketprogrammer/pydk
 def _set_hue(self, hue):
     self.hueValue = min(0.999, hue)
     self.hueHandle.top = (1.0-hue) * 128.0 - self.hueHandle.height / 2
     self.fieldBG.color = colorsys.hsv_to_rgb(self.hueValue, 1, 1)
コード例 #52
0
def visualize_pts_line(pts_array,
                       line_index_list,
                       method=2,
                       seed=0,
                       alpha=0.5,
                       vis_threshold=0.3,
                       pts_size=20,
                       line_size=10,
                       line_color_index=0,
                       fig=None,
                       ax=None,
                       save_path=None,
                       vis=False,
                       warning=True,
                       debug=True,
                       closefig=True):
    '''
    given a list of index, and a point array, to plot a set of points with line on it

    inputs:
        pts_array:          2(3) x num_pts
        line_index_list:    a list of index
        method:             1: all points are connected, if some points are missing in the middle, just ignore that point and connect the two nearby points
                            2: if some points are missing in the middle of a line, the line is decomposed to sub-lines
        vis_threshold:      confidence to draw the points

    '''
    if debug:
        assert is2dptsarray(pts_array) or is2dptsarray_occlusion(
            pts_array) or is2dptsarray_confidence(
                pts_array), 'input points are not correct'
        assert islist(line_index_list), 'the list of index is not correct'
        assert method in [1, 2], 'the plot method is not correct'

    num_pts = pts_array.shape[1]
    # expand the pts_array to 3 rows if the confidence row is not provided
    if pts_array.shape[0] == 2:
        pts_array = np.vstack((pts_array, np.ones((1, num_pts))))
    fig, ax = get_fig_ax_helper(fig=fig, ax=ax)
    np.random.seed(seed)
    color_option = 'hsv'

    if color_option == 'rgb': color_set_random = np.random.rand(3, num_pts)
    elif color_option == 'hsv':
        h_random = np.random.rand(num_pts, )
        color_set_random = np.zeros((3, num_pts), dtype='float32')
        for pts_index in range(num_pts):
            color_set_random[:, pts_index] = colorsys.hsv_to_rgb(
                h_random[pts_index], 1, 1)

    line_color = color_set[line_color_index]
    pts_line = pts_array[:, line_index_list]

    if method == 1:
        valid_pts_list = np.where(pts_line[2, :] > vis_threshold)[0].tolist()
        pts_line_tmp = pts_line[:, valid_pts_list]
        ax.plot(pts_line_tmp[0, :],
                pts_line_tmp[1, :],
                lw=line_size,
                color=line_color,
                alpha=alpha)  # plot all lines

        # plot all points
        for pts_index in valid_pts_list:
            pts_index_original = line_index_list[pts_index]
            # ax.plot(pts_array[0, pts_index_original], pts_array[1, pts_index_original], 'o', color=color_set_big[pts_index_original % len(color_set_big)], alpha=alpha)
            ax.plot(pts_array[0, pts_index_original],
                    pts_array[1, pts_index_original],
                    marker='o',
                    ms=pts_size,
                    lw=line_size,
                    color=color_set_random[:, pts_index],
                    alpha=alpha)
    else:
        not_valid_pts_list = np.where(
            pts_line[2, :] < vis_threshold)[0].tolist()
        if len(not_valid_pts_list) == 0:  # all valid
            ax.plot(pts_line[0, :],
                    pts_line[1, :],
                    lw=line_size,
                    color=line_color,
                    alpha=alpha)

            # plot points
            for pts_index in line_index_list:
                # ax.plot(pts_array[0, pts_index], pts_array[1, pts_index], 'o', color=color_set_big[pts_index % len(color_set_big)], alpha=alpha)
                ax.plot(pts_array[0, pts_index],
                        pts_array[1, pts_index],
                        marker='o',
                        ms=pts_size,
                        lw=line_size,
                        color=color_set_random[:, pts_index],
                        alpha=alpha)
        else:
            prev_index = 0
            for not_valid_index in not_valid_pts_list:
                plot_list = range(prev_index, not_valid_index)
                pts_line_tmp = pts_line[:, plot_list]
                ax.plot(pts_line_tmp[0, :],
                        pts_line_tmp[1, :],
                        lw=line_size,
                        color=line_color,
                        alpha=alpha)

                # plot points
                for pts_index in plot_list:
                    pts_index_original = line_index_list[pts_index]
                    ax.plot(pts_array[0, pts_index_original],
                            pts_array[1, pts_index_original],
                            marker='o',
                            ms=pts_size,
                            lw=line_size,
                            color=color_set_random[:, pts_index_original],
                            alpha=alpha)
                    # ax.plot(pts_array[0, pts_index_original], pts_array[1, pts_index_original], 'o', color=color_set_big[pts_index_original % len(color_set_big)], alpha=alpha)

                prev_index = not_valid_index + 1

            pts_line_tmp = pts_line[:, prev_index:]
            ax.plot(pts_line_tmp[0, :],
                    pts_line_tmp[1, :],
                    lw=line_size,
                    color=line_color,
                    alpha=alpha)  # plot last line

            # plot last points
            for pts_index in range(prev_index, pts_line.shape[1]):
                pts_index_original = line_index_list[pts_index]
                # ax.plot(pts_array[0, pts_index_original], pts_array[1, pts_index_original], 'o', color=color_set_big[pts_index_original % len(color_set_big)], alpha=alpha)
                ax.plot(pts_array[0, pts_index_original],
                        pts_array[1, pts_index_original],
                        marker='o',
                        ms=pts_size,
                        lw=line_size,
                        color=color_set_random[:, pts_index_original],
                        alpha=alpha)

    return save_vis_close_helper(fig=fig,
                                 ax=ax,
                                 vis=vis,
                                 save_path=save_path,
                                 warning=warning,
                                 debug=debug,
                                 closefig=closefig)
コード例 #53
0
    0.73,
    0.80,
    0.87,
    0.45,
    0.52,
    0.60,
    0.67,
    0.74,
    0.81,
    0.88,
    0.95,
]

hat = SenseHat()


def scale(v):
    return int(v * 255)


while True:
    # Rotate the hues
    hues = [(h + 0.01) % 1.0 for h in hues]
    # Convert the hues to RGB values
    pixels = [hsv_to_rgb(h, 1.0, 1.0) for h in hues]
    # hsv_to_rgb returns 0..1 floats; convert to ints in the range 0..255
    pixels = [(scale(r), scale(g), scale(b)) for r, g, b in pixels]
    # Update the display
    hat.set_pixels(pixels)
    sleep(0.04)
コード例 #54
0
def _hsv_to_rgb(tup):
    return tuple(int(i * 255) for i in colorsys.hsv_to_rgb(*tup))
コード例 #55
0
 def set_hsv_coord(self, *, h=None, s=None, v=None,
                   min_h=0, max_h=1, min_s=0, max_s=1, min_v=0, max_v=1) -> Color:
     h2, s2, v2 = self.hsv
     return self.c(*colorsys.hsv_to_rgb(max(min_h, min(max_h, h or h2)),
                                        max(min_s, min(max_s, s or s2)),
                                        max(min_v, min(max_v, v or v2))))
コード例 #56
0
from PIL import Image
import random
from vis import Vis, Word
import vis
import pandas as pd
from string import ascii_letters
import colorsys


def main():
    pass


if __name__ == '__main__':
    special_color = tuple(
        [int(item * 255) for item in colorsys.hsv_to_rgb(0.05, 0.7, 0.85)])

    # background_color = (247, 237, 226)
    # background_color_bgr = (226, 237, 247)
    background_color_bgr = background_color = (20, 20, 20)
    font_color = (240, 240, 240)
    # special_color = (88, 130, 135)

    v = Vis(special_color=special_color)
    w = Word()
    c = Canvas('framework_3')

    c.set_bg_color(background_color_bgr)
    c.set_font_color(font_color)
    c.set_special_color(special_color)
    c.add_layer(Layer(img=v.get(vis.dist_vis), alpha=1, title='成绩变化'))
コード例 #57
0
 def toRGB(self):
     return colorsys.hsv_to_rgb(self.h, self.s, self.b)
コード例 #58
0
 def hue_rotate(self, angle) -> Color:
     h, s, v = self.hsv
     return self.c(*colorsys.hsv_to_rgb((h + angle) % 1, s, v))
コード例 #59
0
    def LoadModel(self, detection_speed="normal"):

        if (self.__modelType == "yolov3"):
            if (detection_speed == "normal"):
                self.__yolo_model_image_size = (416, 416)
            elif (detection_speed == "fast"):
                self.__yolo_model_image_size = (320, 320)
            elif (detection_speed == "faster"):
                self.__yolo_model_image_size = (208, 208)
            elif (detection_speed == "fastest"):
                self.__yolo_model_image_size = (128, 128)
            elif (detection_speed == "flash"):
                self.__yolo_model_image_size = (96, 96)

        elif (self.__modelType == "tinyyolov3"):
            if (detection_speed == "normal"):
                self.__yolo_model_image_size = (832, 832)
            elif (detection_speed == "fast"):
                self.__yolo_model_image_size = (576, 576)
            elif (detection_speed == "faster"):
                self.__yolo_model_image_size = (416, 416)
            elif (detection_speed == "fastest"):
                self.__yolo_model_image_size = (320, 320)
            elif (detection_speed == "flash"):
                self.__yolo_model_image_size = (272, 272)

        if (self.__modelLoaded == False):
            if (self.__modelType == ""):
                raise ValueError(
                    "You must set a valid model type before loading the model."
                )
            elif (self.__modelType == "yolov3"):
                model = yolo_main(Input(shape=(None, None, 3)),
                                  len(self.__yolo_anchors) // 3,
                                  len(self.numbers_to_names))
                model.load_weights(self.modelPath)

                hsv_tuples = [(x / len(self.numbers_to_names), 1., 1.)
                              for x in range(len(self.numbers_to_names))]
                self.colors = list(
                    map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
                self.colors = list(
                    map(
                        lambda x:
                        (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
                        self.colors))
                np.random.seed(10101)
                np.random.shuffle(self.colors)
                np.random.seed(None)

                self.__yolo_input_image_shape = K.placeholder(shape=(2, ))
                self.__yolo_boxes, self.__yolo_scores, self.__yolo_classes = yolo_eval(
                    model.output,
                    self.__yolo_anchors,
                    len(self.numbers_to_names),
                    self.__yolo_input_image_shape,
                    score_threshold=self.__yolo_score,
                    iou_threshold=self.__yolo_iou)

                self.__model_collection.append(model)
                self.__modelLoaded = True

            elif (self.__modelType == "tinyyolov3"):
                model = tiny_yolo_main(Input(shape=(None, None, 3)),
                                       len(self.__tiny_yolo_anchors) // 2,
                                       len(self.numbers_to_names))
                model.load_weights(self.modelPath)

                hsv_tuples = [(x / len(self.numbers_to_names), 1., 1.)
                              for x in range(len(self.numbers_to_names))]
                self.colors = list(
                    map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
                self.colors = list(
                    map(
                        lambda x:
                        (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
                        self.colors))
                np.random.seed(10101)
                np.random.shuffle(self.colors)
                np.random.seed(None)

                self.__yolo_input_image_shape = K.placeholder(shape=(2, ))
                self.__yolo_boxes, self.__yolo_scores, self.__yolo_classes = yolo_eval(
                    model.output,
                    self.__tiny_yolo_anchors,
                    len(self.numbers_to_names),
                    self.__yolo_input_image_shape,
                    score_threshold=self.__yolo_score,
                    iou_threshold=self.__yolo_iou)

                self.__model_collection.append(model)
                self.__modelLoaded = True
コード例 #60
0
def highlight_rgb(r, g, b, amount=0.1):
    h, s, v = colorsys.rgb_to_hsv(r, g, b)
    return colorsys.hsv_to_rgb(h, s, (v + amount) % 1)