def labelnode(var, fit):
    # high = float(2) #Default
    high = float(1)
    low = float(0)
    mid = float(high - low) / 2 + low

    """
  #USE BLUE MONOTONE GRADIENT
  if fit > high: return colorsys.rgb_to_hsv(0, 0, 1)
  elif fit > low: return colorsys.rgb_to_hsv(1-(fit-low)/(high-low),1-(fit-low)/(high-low),1)
  else: return colorsys.rgb_to_hsv(1,1,1)
  print 'Leaking'; sys.exit()
  """

    # HIG MIDE LOW IS USED, WHITE -> YELLOW -> RED
    if fit > high:
        return colorsys.rgb_to_hsv(1, 0, 0)
    elif fit > mid:
        return colorsys.rgb_to_hsv(1, (high - fit) / (high - mid), 0)
    elif fit > low:
        return colorsys.rgb_to_hsv(1, 1, (mid - fit) / (mid - low))
    elif fit <= low:
        return colorsys.rgb_to_hsv(1, 1, 1)
    else:
        print "Something is wrong with the coloring function"
        print fit
        sys.exit()
	def get_init_histogram(self, cv_image):
		# window size
		self.wh = 80
		self.ww = 200

		# get the sidewalk frame
		self.mid = self.w / 2
		self.sidewalk_frame = cv_image[(self.h - self.wh) : self.h, (self.mid - self.ww / 2) : (self.mid + self.ww / 2)]

		# sidewalk histogram
		self.sidewalk_his.append(np.zeros((10, 10, 1)))
		for i in range(0, self.wh):
			for j in range(0, self.ww):
				(r, g, b) = (self.sidewalk_frame[i, j, 0]/255.0, self.sidewalk_frame[i, j, 1]/255.0, self.sidewalk_frame[i, j, 2]/255.0)
				(h, s, v) = colorsys.rgb_to_hsv(r, g, b)
				x, y = self.normalize(h, s)
				self.sidewalk_his[0][x, y, 0] += 1

		# background histogram
		self.background_his = np.zeros((10, 10, 1))

		# background total pixel counts
		self.bp = 0

		for i in range(0, self.h):
			for j in range(0, self.w):
				if self.h - self.wh < i < self.h and (self.mid - self.ww / 2) < j < (self.mid + self.ww / 2):
					continue
				(r, g, b) = (cv_image[i, j, 0]/255.0, cv_image[i, j, 1]/255.0, cv_image[i, j, 2]/255.0)
				(h, s, v) = colorsys.rgb_to_hsv(r, g, b)
				x, y = self.normalize(h, s)
				self.bp += 1
				self.background_his[x, y, 0] += 1
Example #3
0
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')
Example #4
0
  def set_colour(self, colour1=None, colour2=None):
    ''' Colour each character with a gradient from colour1 to colour2
    Interpolate hsv instead of rgb since it is a more natural change.
    '''
    if colour1 is not None:
      self.colour1 = colour1
    if colour2 is not None:
      self.colour2 = colour2
      
    if self.textBlock is None:
      return
      
    colour1 = self.colour1
    colour2 = self.colour2

    textBlock = self.textBlock    
    manager = textBlock._text_manager
      
    hsv1 = colorsys.rgb_to_hsv(colour1[0], colour1[1], colour1[2])
    hsv2 = colorsys.rgb_to_hsv(colour2[0], colour2[1], colour2[2])
      
    normal = np.zeros((3), dtype=np.float)
    normal[0] = textBlock.rot + textBlock.char_rot
        
    for index in range(0,textBlock._string_length):
      h = np.interp(index, [0,textBlock._string_length], [hsv1[0], hsv2[0]])
      s = np.interp(index, [0,textBlock._string_length], [hsv1[1], hsv2[1]])
      v = np.interp(index, [0,textBlock._string_length], [hsv1[2], hsv2[2]])
      a = np.interp(index, [0,textBlock._string_length], [colour1[3], colour2[3]])
      rgb = colorsys.hsv_to_rgb(h, s, v)
      normal[1] = (rgb[1] * 0.999) + math.floor((rgb[0] * 999))
      normal[2] = (a * 0.999) + math.floor((rgb[2] * 999))
      
      #Only set colour alpha for string length. Zero for non displayed characters
      manager.normals[textBlock._buffer_index + index, :] = normal
Example #5
0
    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)
Example #6
0
        def hsv(a, surface, rcolors, weight=(2, 3, 1)):
            #hue saturation value/brightness


            hcolors = {}
            for color in rcolors:
                nc = colorsys.rgb_to_hsv(color[0] / 255.0, color[1] / 255.0, color[2] / 255.0)
                hcolors[nc] = rcolors[color]
            w10 = w // 20
            total = z = w
            #print hcolors
            for x in range(w):
                for y in range(h):
                    color = surface.get_at((x, y))
                    color = colorsys.rgb_to_hsv(color[0] / 255.0, color[1] / 255.0, color[2] / 255.0)
                    #print color
                    cdif = 100
                    for c in hcolors:
                        p1 = min(weight[0] * (c[0] - color[0]) * (c[0] - color[0]),
                                 weight[0] * (c[0] + 1 - color[0]) * (c[0] + 1 - color[0]),
                                 weight[0] * (c[0] - 1 - color[0]) * (c[0] - 1 - color[0]))

                        dif = p1 + weight[1] * (c[1] - color[1]) * (c[1] - color[1]) + weight[2] * (c[2] - color[2]) * (
                        c[2] - color[2])
                        #print dif, cdif
                        if dif < cdif:
                            cdif = dif
                            hit = hcolors[c]
                    set_tile(a, (hit, None, 0, None))
                    #print hit, dif
                if z % w10 == 1:  #give lifesigns
                    n = ((total - z) * 100.0) / w
                    print("%6.2f%% done writing tiles" % n)
                z -= 1
Example #7
0
    def colour(self):
        if self._colour != None: return self._colour

        # Count colour occurences, ignoring white. Return most common.
        d={}
        size = self.img.size
        for x in range(size[0]):
            for y in range(size[1]):
                p = self.img.getpixel((x,y))
                (hue,sat,val) = rgb_to_hsv(*pxtofloat(p))
                if sat > 0.5:  # Ignore greyscale colors
                    if p in d:
                        d[p] += 1
                    else:
                        d[p] = 1

        col = sorted(d.iteritems(), key=lambda a:a[1], reverse=True)[0][0] 
        (hue,sat,val) = rgb_to_hsv(*pxtofloat(col))

        log.debug("Pos %s rgb = %s, hsv = %s"%(self.pos, col, hue))
        if hue < 0.1:
            self._colour = Colour.RED
        elif hue > 0.3 and hue < 0.35:
            self._colour = Colour.GREEN
        elif hue > 0.77 and hue < 0.81:
            self._colour = Colour.PURPLE
        else:
            # NFI
            raise RuntimeError("Couldn't work out the color for %s: %s - %s"%(self.pos, col, hsv))
        
        return self._colour
Example #8
0
def compare(real, test):
	size = real.get_size()

	if size[0] > size[1]:
		real = pygame.transform.scale(real, (LONG, int(size[1] / size[0] * LONG)))
		test = pygame.transform.scale(test, (LONG, int(size[1] / size[0] * LONG)))

	else:
		real = pygame.transform.scale(real, (int(size[0] / size[1] * LONG), LONG))
		test = pygame.transform.scale(test, (int(size[0] / size[1] * LONG), LONG))

	size = real.get_size()
	score = 0

	for x in range(size[0]):
		for y in range(size[1]):
			preal = real.get_at((x, y))
			ptest = test.get_at((x, y))

			hsvreal = colorsys.rgb_to_hsv(preal[0], preal[1], preal[2])
			hsvtest = colorsys.rgb_to_hsv(ptest[0], ptest[1], ptest[2])

			if math.fabs(hsvtest[0] - hsvreal[0]) > H_THRESHOLD or math.fabs(hsvtest[1] - hsvreal[1]) > S_THRESHOLD or math.fabs(hsvtest[2] - hsvreal[2]) > V_THRESHOLD:
				score += math.hypot(math.hypot(math.fabs(preal[0] - ptest[0]), math.fabs(preal[1] - ptest[1])), math.fabs(preal[2] - ptest[2]))

	maximum = (size[0] * size[1] * 442)

	return (((maximum - score) / maximum * 100) - THRESHOLD) * 100 / (100 - THRESHOLD)
Example #9
0
    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)
Example #10
0
    def twinkle_random_limits(self, idx):
        """
        Randomly change a bulb from its baseline value within limits
        """
        (base_r, base_g, base_b) = self.options['init_pattern'][idx]
        (base_h, base_s, base_v) = colorsys.rgb_to_hsv(base_r/255.0,
                                                       base_g/255.0,
                                                       base_b/255.0)
        
        # % chance of updating a given globe
        if random.random() < self.options['change_chance']:

            r, g, b = self.hol.getglobe(idx)
            (h, s, v) = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
            #log.debug("start h s v: %f %f %f", h, s, v)

            # Adjust color components by a random amount
            h = self.rand_change_colcomp(h, self.options['huestep_max'], base_h, self.options['huediff_max'])
            s = self.rand_change_colcomp(s, self.options['satstep_max'], base_s, self.options['satdiff_max'])
            v = self.rand_change_colcomp(v, self.options['valstep_max'], base_v, self.options['valdiff_max'])

            (r, g, b) = colorsys.hsv_to_rgb(h, s, v)
            #log.debug("r g b: %f %f %f", r, g, b)
            self.hol.setglobe(idx, int(255*r), int(255*g), int(255*b))
            pass
        pass
	def update_sidewalk_his(self, cv_image):
		self.sidewalk_frame = cv_image[(self.h - self.wh) : self.h, (self.mid - self.ww / 2) : (self.mid + self.ww / 2)]
		if len(self.sidewalk_his) < 4:
			self.sidewalk_his.append(np.zeros((10, 10, 1)))
			for i in range(0, self.wh):
				for j in range(0, self.ww):
					(r, g, b) = (self.sidewalk_frame[i, j, 0]/255.0, self.sidewalk_frame[i, j, 1]/255.0, self.sidewalk_frame[i, j, 2]/255.0)
					(h, s, v) = colorsys.rgb_to_hsv(r, g, b)
					x, y = self.normalize(h, s)
					self.sidewalk_his[-1][x, y, 0] += 1
		else:
			new_his = np.zeros((10, 10, 1))
			for i in range(0, self.wh):
				for j in range(0, self.ww):
					(r, g, b) = (self.sidewalk_frame[i, j, 0]/255.0, self.sidewalk_frame[i, j, 1]/255.0, self.sidewalk_frame[i, j, 2]/255.0)
					(h, s, v) = colorsys.rgb_to_hsv(r, g, b)
					x, y = self.normalize(h, s)
					new_his[x, y, 0] += 1
			dis = []
			for i in range(0, len(self.sidewalk_his)):
				dis.append(self.normdis(new_his, self.sidewalk_his[i]))
			minimum = dis.index(min(dis))
			print 'minimum', minimum
			del(self.sidewalk_his[0])
			self.sidewalk_his.append(new_his)
Example #12
0
def from_rgb_to_paletton_hue(r, g, b, color_wheel):
    from colorsys import rgb_to_hsv

    h, s, v = rgb_to_hsv(r, g, b)
    wheel_hues = tuple(
        rgb_to_hsv(*color_wheel[k][:3])[0] for k in sorted(color_wheel.keys())
    )
    if h in wheel_hues:
        paletton_hue = wheel_hues.index(h) * 15
    else:
        i = sorted(wheel_hues + (h,)).index(h)
        wheel_start = (i - 1) * 15
        wheel_end = i * 15 if i < len(wheel_hues) else 360
        h1 = wheel_hues[i-1]
        h2 = wheel_hues[i] if i < len(wheel_hues) else 1.
        k = (h - h1) / (h2 - h1)
        log.debug(
            "k=%s, h=%s, h1=%s, h2=%s, i1=%s, i2=%s",
            k, h, h1, h2, wheel_start, wheel_end
        )
        paletton_hue = round(
            wheel_start + k * (wheel_end - wheel_start)
        )
        paletton_hue %= 360
    return paletton_hue
Example #13
0
 def gradient(self, d, spec=GRADIENT_SPEC):
     N = len(spec)
     idx = int(d * (N - 1))
     t = math.fmod(d * (N - 1), 1.0)
     col1 = colorsys.rgb_to_hsv(*spec[min(N - 1, idx)])
     col2 = colorsys.rgb_to_hsv(*spec[min(N - 1, idx + 1)])
     hsv = tuple(a * (1 - t) + b * t for a, b in zip(col1, col2))
     r, g, b = colorsys.hsv_to_rgb(*hsv)
     return "#%02X%02X%02X" % (r * 255, g * 255, b * 255)
Example #14
0
    def color(self, x):
        """ Get the color for the point x in the range [0..1).
            The color is returned as an rgb triple, with all values in the range
            [0..1).
        """
        # Find the segment.
        for seg in self.segs:
            if seg.l <= x <= seg.r:
                break
        else:
            # No segment applies! Return black I guess.
            return (0,0,0)

        # Normalize the segment geometry.
        mid = (seg.m - seg.l)/(seg.r - seg.l)
        pos = (x - seg.l)/(seg.r - seg.l)
        
        # Assume linear (most common, and needed by most others).
        if pos <= mid:
            f = pos/mid/2
        else:
            f = (pos - mid)/(1 - mid)/2 + 0.5

        # Find the correct interpolation factor.
        if seg.fn == 1:   # Curved
            f = math.pow(pos, math.log(0.5) / math.log(mid));
        elif seg.fn == 2:   # Sinusoidal
            f = (math.sin((-math.pi/2) + math.pi*f) + 1)/2
        elif seg.fn == 3:   # Spherical increasing
            f -= 1
            f = math.sqrt(1 - f*f)
        elif seg.fn == 4:   # Spherical decreasing
            f = 1 - math.sqrt(1 - f*f);

        # Interpolate the colors
        if seg.space == 0:
            c = (
                seg.rl + (seg.rr-seg.rl) * f,
                seg.gl + (seg.gr-seg.gl) * f,
                seg.bl + (seg.br-seg.bl) * f
                )
        elif seg.space in (1,2):
            hl, sl, vl = colorsys.rgb_to_hsv(seg.rl, seg.gl, seg.bl)
            hr, sr, vr = colorsys.rgb_to_hsv(seg.rr, seg.gr, seg.br)

            if seg.space == 1 and hr < hl:
                hr += 1
            elif seg.space == 2 and hr > hl:
                hr -= 1

            c = colorsys.hsv_to_rgb(
                (hl + (hr-hl) * f) % 1.0,
                sl + (sr-sl) * f,
                vl + (vr-vl) * f
                )
        return c
Example #15
0
def get_color(fraction, min_wins):
    assert 0 <= fraction <= 1, fraction
    if min_wins:
        fraction = 1 - fraction

    # Calculate hues.
    start = colorsys.rgb_to_hsv(0, 0, 0.8)[0]
    end = colorsys.rgb_to_hsv(0, 0.8, 0)[0]

    return colorsys.hsv_to_rgb(start + fraction * (end - start), 1, 0.7)
Example #16
0
def colormap(sat=None):
    pal = sns.color_palette("husl", n_colors=256)
    pal = pal[32:180][::-1]
    if sat is None:
        hsv = map(lambda x: [x[0], x[1] * 1, 1], [rgb_to_hsv(x[0], x[1], x[2]) for x in pal])
    else:
        hsv = map(lambda x: [x[0], x[1] * 0.6, 0.9], [rgb_to_hsv(x[0], x[1], x[2]) for x in pal])
    rgb = [hsv_to_rgb(x[0], x[1], x[2]) for x in hsv]
    pal = ListedColormap(rgb, name="husl")
    return pal
    def setRgbThreshold(self, rgbLower, rgbUpper):
        '''Set the threshold range for a color image'''

        # So far I haven't determined if it's easier to specify color range in RGB
        # or straight HSV.  If RGB is your thing then this will convert your range
        # to HSV colorspace
        
        self.processColor = True        
        self.threshHsvLower = colorsys.rgb_to_hsv(rgbLower)
        self.threshHsvUpper = colorsys.rgb_to_hsv(rgbUpper)
Example #18
0
def getcol(i, imin, imax, cmin, cmax):
    """ Calculate the hex color string for value v """
    hmin, smin, vmin = colorsys.rgb_to_hsv(*[floatrgb(v) for v in cmin])
    hmax, smax, vmax = colorsys.rgb_to_hsv(*[floatrgb(v) for v in cmax])
    hval = scale(i, imin, imax, hmin, hmax)
    sval = scale(i, imin, imax, smin, smax)
    vval = scale(i, imin, imax, vmin, vmax)
    rval, gval, bval = colorsys.hsv_to_rgb(hval, sval, vval)
    rhex = cconv(int(rval * 255))
    ghex = cconv(int(gval * 255))
    bhex = cconv(int(bval * 255))
    return '#%s%s%s' % (rhex, ghex, bhex)
def genColourRange(ncols, rgbfrom = (1.0, 0.9, 0.9), rgbto = (0.9, 0.9, 1.0)):
    import colorsys
    hsvfrom = colorsys.rgb_to_hsv(*rgbfrom)
    hsvto = colorsys.rgb_to_hsv(*rgbto)
    colsteps = ((hsvto[0] - hsvfrom[0])/(ncols - 1), (hsvto[1] - hsvfrom[1])/(ncols - 1), (hsvto[2] - hsvfrom[2])/(ncols - 1))
    colrange = [ ]
    for i in range(ncols):
        hsv = (hsvfrom[0] + i * colsteps[0], hsvfrom[1] + i * colsteps[1], hsvfrom[2] + i * colsteps[2])
        rgb = colorsys.hsv_to_rgb(*hsv)
        strrgb = '%.2x%.2x%.2x' % (int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255))
        colrange.append(strrgb)
    return colrange       
Example #20
0
def generate_gradient(f_color, l_color, number_of_shades):
  h_f, s_f, v_f = colorsys.rgb_to_hsv(f_color[0]/255., f_color[1]/255., f_color[2]/255.)
  h_l, s_l, v_l = colorsys.rgb_to_hsv(l_color[0]/255., l_color[1]/255., l_color[2]/255.)
  h_new_interval = numpy.linspace(h_f, h_l, number_of_shades)
  s_new_interval = numpy.linspace(s_f, s_l, number_of_shades)
  v_new_interval = numpy.linspace(v_f, v_l, number_of_shades)
  response = []
  for x in range(number_of_shades):
    r, g, b = colorsys.hsv_to_rgb(h_new_interval[x], s_new_interval[x], v_new_interval[x])
    r, g, b = int(r*255), int(g*255), int(b*255)
    response.extend([r, g, b])
  return response
def labelnode(var,fit):
  high = float(2)
  low  = float(0)
  mid  = float(high-low)/2+low
  if fit > high:  return colorsys.rgb_to_hsv(1, 0, 0)
  elif fit > mid: return colorsys.rgb_to_hsv(1,(high-fit)/(high-mid),0)
  elif fit > low: return colorsys.rgb_to_hsv(1,1,(mid-fit)/(mid-low))
  elif fit <= low: return colorsys.rgb_to_hsv(1,1,1)
  else: 
    print ("Something is wrong with the coloring function")
    print (var, fit)
    sys.exit()
Example #22
0
	def applyColours(self):
		
		# Set the vert colours for each face
		for f in self.me.faces:

			f_col = self.me.vertex_colors.active.data[f.index]
			for i, v in enumerate(f.vertices):
			
				# Get the actual angle (we might have added multiple up)
				if (not self.normalize) and self.totAngles[v] > 1:
					angle = self.angles[v] / self.totAngles[v]
				else:
					angle = self.angles[v]
					
				# The value is relative to pi (180 degrees)
				val =1.0 - ((angle-self.minimum)/self.range)
				
				# So lets make the val between -1 and + 1
				if self.contrast:
					
					val = val ** self.contrast
				
					val = 1.0 - val
				
					val = val ** self.contrast
				
					val = 1.0 - val
				
				if not i:
					ori = f_col.color1
					v_col = colorsys.rgb_to_hsv(ori[0],ori[1],ori[2])
					if val > v_col[2]: val = v_col[2]
					v_col = colorsys.hsv_to_rgb(v_col[0],v_col[1],val)
					f_col.color1 = v_col
				elif i == 1:
					ori = f_col.color2
					v_col = colorsys.rgb_to_hsv(ori[0],ori[1],ori[2])
					if val > v_col[2]: val = v_col[2]
					v_col = colorsys.hsv_to_rgb(v_col[0],v_col[1],val)
					f_col.color2 = v_col
				elif i == 2:
					ori = f_col.color3
					v_col = colorsys.rgb_to_hsv(ori[0],ori[1],ori[2])
					if val > v_col[2]: val = v_col[2]
					v_col = colorsys.hsv_to_rgb(v_col[0],v_col[1],val)
					f_col.color3 = v_col
				elif i == 3:
					ori = f_col.color4
					v_col = colorsys.rgb_to_hsv(ori[0],ori[1],ori[2])
					if val > v_col[2]: val = v_col[2]
					v_col = colorsys.hsv_to_rgb(v_col[0],v_col[1],val)
					f_col.color4 = v_col
Example #23
0
		def _missing(*args, **kwargs):
			self.type = name
			if name == 'frame':
				assert len(args) == 4
				self.start_value = self.view.frame
				self.end_value = pygame.Rect(args)
				self.perform_animation = self.tick_frame
			elif name == 'bounds':
				pass
			elif name == 'background_color':
				self.start_value = colorsys.rgb_to_hsv(self.view.background_color.r, self.view.background_color.g, self.view.background_color.b)
				self.end_value = colorsys.rgb_to_hsv(*args)
				self.perform_animation = self.tick_background_color
    def __init__(self,color):
        self.originalColor = color
        self.color = color
        self.HSV = colorsys.rgb_to_hsv(*[i/255 for i in self.color])
        self.originalHSV = colorsys.rgb_to_hsv(*[i/255 for i in self.color])

        self.fade = None
        self.brightFade = BrightFade()
        self.dimFade = DimFade()
        self.setBrightFade()
        self.isFading = False
        self.shouldFade = True
        self.peakBrightness = False
Example #25
0
        def hsv(a, surface, rcolors, weight=(2, 3, 1)):
            #hue saturation value/brightness


            hcolors = {}
            for color in rcolors:
                nc = colorsys.rgb_to_hsv(color[0] / 255.0, color[1] / 255.0, color[2] / 255.0)
                hcolors[nc] = rcolors[color]
            w10 = w // 20
            total = z = w
            cache = {}
            tiledata = io.BytesIO()
            set_tile(tiledata, (None, None, 0, None))
            air = tiledata.getvalue()

            for x in range(w):
                for y in range(h):
                    color = surface.get_at((x, y))
                    if color[3] == 0:
                        a.write(air)
                        continue
                    cachecolor = color[:3]
                    if cachecolor in cache:
                        a.write(cache[cachecolor])
                    else:
                        tiledata = io.BytesIO()
                        color = colorsys.rgb_to_hsv(color[0] / 255.0, color[1] / 255.0, color[2] / 255.0)
                        #print color
                        cdif = 100
                        for c in hcolors:
                            p1 = min(weight[0] * (c[0] - color[0]) * (c[0] - color[0]),
                                     weight[0] * (c[0] + 1 - color[0]) * (c[0] + 1 - color[0]),
                                     weight[0] * (c[0] - 1 - color[0]) * (c[0] - 1 - color[0]))

                            dif = p1 + weight[1] * (c[1] - color[1]) * (c[1] - color[1]) + weight[2] * (c[2] - color[2]) * (
                            c[2] - color[2])
                            #print dif, cdif
                            if dif < cdif:
                                cdif = dif
                                hit = hcolors[c]

                        set_tile(tiledata, (hit, None, 0, None))
                        value = tiledata.getvalue()
                        a.write(value)
                        cache[cachecolor] = value

                    #print hit, dif
                if z % w10 == 1:  #give lifesigns
                    n = ((total - z) * 100.0) / w
                    print("%6.2f%% done writing tiles" % n)
                z -= 1
Example #26
0
def getHSVFromImage(fileName):
    src=Image.open(fileName)
    h=numpy.zeros((src.size[0],src.size[1]))
    s=numpy.zeros((src.size[0],src.size[1]))
    v=numpy.zeros((src.size[0],src.size[1]))

    r,g,b=src.convert("RGB").split()
    
    for x in xrange(src.size[0]):
        for y in xrange(src.size[1]):
            h[x][y]=colorsys.rgb_to_hsv(r.getpixel((x,y)),g.getpixel((x,y)),b.getpixel((x,y)))[0]*255
            s[x][y]=colorsys.rgb_to_hsv(r.getpixel((x,y)),g.getpixel((x,y)),b.getpixel((x,y)))[0]
            v[x][y]=colorsys.rgb_to_hsv(r.getpixel((x,y)),g.getpixel((x,y)),b.getpixel((x,y)))[0]
    return h,s,v
Example #27
0
 def rgb2xterm(self):
   '''selects the nearest xterm color for a rgb value ('color' class)'''
   # TODO 更好的计算法
   best_match= 0
   smallest_distance = 10000000
   for c in range(16,255):
     # d = (int(termcolor[c][1:3], 16) - self.r) ** 2 + (int(termcolor[c][3:5], 16) - self.g) ** 2 + (int(termcolor[c][5:], 16) - self.b) ** 2
     a = colorsys.rgb_to_hsv(float(int(termcolor[c][1:3], 16)), float(int(termcolor[c][3:5], 16)), float(int(termcolor[c][5:], 16)))
     b = colorsys.rgb_to_hsv(float(self.r), float(self.g), float(self.b))
     d = (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + ((a[2] - b[2]) / 255.0) ** 2
     if d < smallest_distance:
       smallest_distance = d
       best_match = c
   return best_match
Example #28
0
def color_range(n,start='red',end='blue'):
    from itertools2 import ilinear
    if start in color: start=color[start]
    start=hex_to_rgb(start,1./255)
    start=colorsys.rgb_to_hsv(*start)
    if end in color: end=color[end]
    end=hex_to_rgb(end,1./255)
    end=colorsys.rgb_to_hsv(*end)
    res=[]
    for hsv in ilinear(start,end,n):
        rgb=colorsys.hsv_to_rgb(*hsv)
        hex=rgb_to_hex(tuple(int(255*x) for x in rgb))
        res.append(hex)
    return res
Example #29
0
	def np_gradient(self, id, dataIn):
		#We expect dataIn to have:
		# 'start', the first pixel to use on the strand id
		# 'end', the last pixel to use on the strand id
		# 'startColor', the first color to use, as an RGB list []
		# 'endColor', the last color to use, as an RGB list []

		if "start" not in dataIn:
			self.log("UARTNeopixel.np_gradient(), no start in dataIn.")
			return None

		if "end" not in dataIn:
			self.log("UARTNeopixel.np_gradient(), no end in dataIn.")
			return None

		if "startColor" not in dataIn or len(dataIn["startColor"]) != 3:
			self.log("UARTNeopixel.np_gradient(), no startColor in dataIn.")
			return None

		if "endColor" not in dataIn or len(dataIn["endColor"]) != 3:
			self.log("UARTNeopixel.np_gradient(), no endColor in dataIn.")
			return None

		#Convert startColor and endColor to HSV values
		startColorHSV = colorsys.rgb_to_hsv(int(dataIn['startColor'][0]),int(dataIn['startColor'][1]),int(dataIn['startColor'][2]))
		endColorHSV = colorsys.rgb_to_hsv(int(dataIn['endColor'][0]),int(dataIn['endColor'][1]),int(dataIn['endColor'][2]))
		mapSize = int(dataIn["end"]) - int(dataIn["start"])

		#Prepare the data structure
		data = {
			"id":id,
			"command":"ctrl",
			"type":"neopixel",
			"data":{
				"leds":{} #pixel:[r,g,b] sets.
			}
		}

		for nrp in range(0, mapSize):
			lH = (endColorHSV[0] - startColorHSV[0]) * nrp / mapSize + startColorHSV[0]
			lV = (endColorHSV[2] - startColorHSV[2]) * nrp / mapSize + startColorHSV[2]
			lS = (endColorHSV[1] - startColorHSV[1]) * nrp / mapSize + startColorHSV[1]

			lRGB = colorsys.hsv_to_rgb(lH, lS, lV)

			data["data"]["leds"][nrp+int(dataIn["start"])] = [ int(lRGB[0]) % 256, int(lRGB[1]) % 256, int(lRGB[2]) % 256 ]

		if self.sendMessage(self.createMessage(data)):
			self.log("UARTNeopixel.np_gradient(), sendMessage call failure.")
  def termcolor(self): # {{{3
    '''selects the nearest xterm color for a rgb value ('color' class)'''
    best_match = 0
    smallest_distance = 10000000

    for c in range(16, 256):
      a = colorsys.rgb_to_hsv(*color_norm(termcolor[c]))
      b = colorsys.rgb_to_hsv(*self.value)
      d = ((a[0] - b[0])) ** 2 + ((a[1] - b[1]) * 2) ** 2 + ((a[2] - b[2]) * 4) ** 2

      if d < smallest_distance:
        smallest_distance = d
        best_match = c

    return best_match
Example #31
0
def readGlyphs(Font, Dict):
    Glyphs = Dict["glyphs"]
    GlyphsCount = len(Glyphs)
    FontMasters = Dict["fontMaster"]
    MasterCount = len(FontMasters)
    GlyphIndexes = {}
    for i in range(GlyphsCount):

        GlyphDict = Glyphs[i]
        glyph = Glyph(MasterCount)
        glyph.name = str(GlyphDict["glyphname"])
        if "unicode" in GlyphDict.keys():
            glyph.unicode = int(GlyphDict["unicode"], 16)
        if "export" in GlyphDict.keys() and str(GlyphDict["export"]) == "0":
            glyph.customdata = "Not Exported"
            glyph.mark = 2
        isNonSpacingMark = _isNonSpacingMark(glyph.name)

        if "color" in GlyphDict.keys():
            try:
                Color = GlyphDict["color"]
                if type(Color) == type(
                    []) or Color.__class__.__name__ == "__NSArrayM":
                    r = float(Color[0])
                    g = float(Color[1])
                    b = float(Color[2])
                    h, s, v = colorsys.rgb_to_hsv(r, g, b)
                    glyph.mark = int(round(h * 255))
                else:
                    ColorIndex = int(Color)
                    Mark = Color2Mark[ColorIndex]
                    if Mark == 0:
                        print "The gray mark colors are not supported by FontLab and are ignored."
                    glyph.mark = Mark
            except:
                pass

        for masterIndex in range(MasterCount):
            FontMaster = FontMasters[masterIndex]
            Layer = None
            try:
                for Layer in GlyphDict["layers"]:
                    if Layer["layerId"] == FontMaster["id"]:
                        break
            except:
                continue
            ShiftNodes = 0
            if isNonSpacingMark:
                ShiftNodes = round(float(Layer["width"]))
                glyph.SetMetrics(Point(0, 0), masterIndex)
            else:
                glyph.SetMetrics(Point(round(float(Layer["width"])), 0),
                                 masterIndex)

            if "paths" not in Layer.keys():
                continue
            nodeIndex = 0
            lastMoveNodeIndex = 0
            for PathIndex in range(len(Layer["paths"])):
                Path = Layer["paths"][PathIndex]
                Nodes = Path["nodes"]
                Nodes = fixNodes(Nodes)
                NodeString = Nodes[-1]
                NodeList = NodeString.split(" ")
                Position = Point(
                    round(float(NodeList[0])) - ShiftNodes,
                    round(float(NodeList[1])))
                if masterIndex == 0:
                    node = Node(nMOVE, Position)
                    glyph.Insert(node, len(glyph))
                else:
                    Index = nodeIndex
                    if Index > len(glyph):
                        Index = Index - len(glyph)
                    try:
                        glyph.nodes[Index].Layer(masterIndex)[0].x = Position.x
                        glyph.nodes[Index].Layer(masterIndex)[0].y = Position.y
                    except:
                        continue  # if the master has more paths then the first master
                firstPoint = Position
                firstNodeIndex = nodeIndex
                nodeIndex = nodeIndex + 1
                OffcurveNodes = []
                for NodeString in Nodes:
                    NodeList = NodeString.split(" ")
                    Position = Point(
                        round(float(NodeList[0])) - ShiftNodes,
                        round(float(NodeList[1])))
                    node = None
                    if NodeList[2] == "LINE":
                        if masterIndex == 0:
                            node = Node(nLINE, Position)
                            try:
                                if NodeList[3] == "SMOOTH":
                                    node.alignment = nSMOOTH
                            except:
                                pass
                            glyph.Insert(node, len(glyph))
                        else:
                            Index = nodeIndex
                            if Index >= len(glyph):
                                Index = Index - len(glyph)

                            glyph.nodes[Index].Layer(
                                masterIndex)[0].x = Position.x
                            glyph.nodes[Index].Layer(
                                masterIndex)[0].y = Position.y
                        nodeIndex = nodeIndex + 1
                    elif NodeList[2] == "CURVE":
                        if len(OffcurveNodes) == 2:
                            if masterIndex == 0:
                                node = Node(nCURVE, Position)
                                try:
                                    if NodeList[3] == "SMOOTH":
                                        node.alignment = nSMOOTH
                                except:
                                    pass
                                node.points[1].x = OffcurveNodes[0].x
                                node.points[1].y = OffcurveNodes[0].y
                                node.points[2].x = OffcurveNodes[1].x
                                node.points[2].y = OffcurveNodes[1].y
                                glyph.Insert(node, len(glyph))
                            else:
                                Index = nodeIndex
                                if Index >= len(glyph):
                                    Index = Index - len(glyph) + 1

                                Points = glyph.nodes[Index].Layer(masterIndex)
                                if len(Points) == 3:
                                    Points[0].x = Position.x
                                    Points[0].y = Position.y
                                    Points[1].x = OffcurveNodes[0].x
                                    Points[1].y = OffcurveNodes[0].y
                                    Points[2].x = OffcurveNodes[1].x
                                    Points[2].y = OffcurveNodes[1].y
                            nodeIndex = nodeIndex + 1
                        OffcurveNodes = []

                    elif NodeList[2] == "OFFCURVE":
                        OffcurveNodes.append(
                            Point(
                                round(float(NodeList[0])) - ShiftNodes,
                                round(float(NodeList[1]))))

                if "closed" in Path and masterIndex == MasterCount - 1:
                    # we may have output a node too much
                    node = glyph[nodeIndex - 1]
                    firstNode = glyph[firstNodeIndex]
                    if node is not None and firstNodeIndex is not None:
                        if node.x == firstNode.x and node.y == firstNode.y:
                            if node.type == nLINE:
                                glyph.DeleteNode(nodeIndex - 1)
                                nodeIndex = nodeIndex - 1
                            elif node.type == nCURVE and glyph[
                                    firstNodeIndex + 1].type != nCURVE:
                                glyph.DeleteNode(firstNodeIndex)
                                nodeIndex = nodeIndex - 1
                    else:
                        print "There was a problem with the outline in the glyph: \"%s\". Probably because the outlines are not compatible." % glyph.name
                        glyph.mark = 34

            if "hints" in Layer.keys():
                vHintIndex = 0
                hHintIndex = 0
                for HintIndex in range(len(Layer["hints"])):
                    HintDict = Layer["hints"][HintIndex]
                    Horizontal = "horizontal" in HintDict
                    if "target" in HintDict and "origin" in HintDict:  # add Links
                        if masterIndex > 0:
                            continue
                        FlNodeIndex1 = None
                        FlNodeIndex2 = None
                        PathIndex, NodeIndex = HintDict["origin"][1:-1].split(
                            ", ")
                        PathIndex = int(PathIndex)
                        NodeIndex = int(NodeIndex)
                        PathCounter = -1
                        NodeCounter = 0
                        for i in range(len(glyph)):
                            node = glyph[i]

                            if node.type == nMOVE:
                                PathCounter = PathCounter + 1
                            if PathCounter >= PathIndex:
                                NodeCounter = NodeCounter + node.count
                            if NodeCounter > NodeIndex:
                                FlNodeIndex1 = i
                                break
                        if HintDict["target"][0] == "{":
                            PathIndex, NodeIndex = HintDict["target"][
                                1:-1].split(", ")
                            PathIndex = int(PathIndex)
                            NodeIndex = int(NodeIndex)
                            PathCounter = -1
                            NodeCounter = 0
                            for i in range(len(glyph)):
                                node = glyph[i]
                                if node.type == nMOVE:
                                    PathCounter = PathCounter + 1
                                if PathCounter >= PathIndex:
                                    NodeCounter = NodeCounter + node.count
                                if NodeCounter > NodeIndex:
                                    FlNodeIndex2 = i
                                    break
                        elif HintDict["target"] == "down":
                            FlNodeIndex2 = -2
                        elif HintDict["target"] == "up":
                            FlNodeIndex2 = -1
                        if FlNodeIndex1 != None and FlNodeIndex2 != None:
                            link = Link(FlNodeIndex1, FlNodeIndex2)
                            if Horizontal:
                                glyph.hlinks.append(link)
                            else:
                                glyph.vlinks.append(link)
                    elif "place" in HintDict:
                        Origin, Size = HintDict["place"][1:-1].split(", ")
                        Origin = int(round(float(Origin)))
                        Size = int(round(float(Size)))
                        if abs(Origin) > 20000 or abs(
                                Size) > 20000 or "type" in HintDict:
                            continue
                        if masterIndex == 0:

                            if Horizontal:
                                hint = Hint(Origin, Size)
                                glyph.hhints.append(hint)
                            else:
                                Origin = Origin - ShiftNodes
                                hint = Hint(Origin, Size)
                                glyph.vhints.append(hint)
                        else:
                            if Horizontal:
                                hint = glyph.hhints[hHintIndex]
                                hint.positions[masterIndex] = Origin
                                hint.widths[masterIndex] = Size
                                hHintIndex = hHintIndex + 1
                            else:
                                hint = glyph.vhints[vHintIndex]
                                hint.positions[masterIndex] = Origin
                                hint.widths[masterIndex] = Size
                                vHintIndex = vHintIndex + 1
            if "anchors" in Layer.keys():
                for AnchorIndex in range(len(Layer["anchors"])):
                    # print "__nodeIndex:", nodeIndex
                    AnchorDict = Layer["anchors"][AnchorIndex]
                    Name = str(AnchorDict["name"])
                    X, Y = AnchorDict["position"][1:-1].split(", ")
                    X = round(float(X)) - ShiftNodes
                    Y = round(float(Y))
                    if masterIndex == 0:
                        anchor = Anchor(Name, X, Y)
                        # print "Move __node", node
                        glyph.anchors.append(anchor)
                    else:
                        Index = nodeIndex
                        #print "_set move point", Index, Position, glyph.nodes #, glyph.nodes[Index].Layer(masterIndex)
                        try:
                            glyph.anchors[AnchorIndex].Layer(masterIndex).x = X
                            glyph.anchors[AnchorIndex].Layer(masterIndex).y = Y
                        except:
                            continue

        Font.glyphs.append(glyph)
        GlyphIndexes[glyph.name] = len(Font.glyphs) - 1

    # Read the components.
    for i in range(GlyphsCount):
        glyph = Font.glyphs[i]
        GlyphDict = Glyphs[i]
        for masterIndex in range(MasterCount):
            FontMaster = FontMasters[masterIndex]
            try:
                for Layer in GlyphDict["layers"]:
                    if Layer["layerId"] == FontMaster["id"]:
                        break
            except:
                continue
            try:
                if "components" in Layer.keys():
                    for componentIndex in range(len(Layer["components"])):
                        try:
                            componentDict = Layer["components"][componentIndex]
                        except:
                            continue
                        ShiftNodes = 0

                        # reconstruct the correct positioning of Nonspacing marks. They where set to zero width on outline import.
                        try:
                            isNonSpacingMarkComponent = _isNonSpacingMark(
                                componentDict['name'])
                            if isNonSpacingMarkComponent:
                                ComponentIndex = GlyphIndexes[
                                    componentDict['name']]
                                ComponentGlyphDict = Glyphs[ComponentIndex]
                                ShiftNodes = float(
                                    str(ComponentGlyphDict['layers']
                                        [masterIndex]["width"]))
                        except:
                            pass

                        # if the glyph itself is a nonspacing mark, move the component
                        try:
                            isNonSpacingMark = _isNonSpacingMark(glyph.name)
                            if isNonSpacingMark:
                                ShiftNodes -= float(str(Layer["width"]))
                        except Exception, e:
                            print e

                        try:
                            componentTransformString = componentDict[
                                "transform"][1:-1]
                        except:
                            componentTransformString = u"1, 0, 0, 1, 0, 0"

                        componentTransformList = componentTransformString.split(
                            ", ")

                        if masterIndex == 0:
                            ComponentIndex = GlyphIndexes[
                                componentDict['name']]
                            Delta = Point(
                                round(float(str(componentTransformList[4]))) +
                                ShiftNodes,
                                round(float(str(componentTransformList[5]))))
                            Scale = Point(
                                float(str(componentTransformList[0])),
                                float(str(componentTransformList[3])))
                            component = Component(ComponentIndex, Delta, Scale)
                            glyph.components.append(component)
                        else:
                            component = glyph.components[componentIndex]
                            component.scales[masterIndex].x = float(
                                str(componentTransformList[0]))
                            component.scales[masterIndex].y = float(
                                str(componentTransformList[3]))
                            component.deltas[masterIndex].x = round(
                                float(str(componentTransformList[4])) +
                                ShiftNodes)
                            component.deltas[masterIndex].y = round(
                                float(str(componentTransformList[5])))

                        if abs(float(str(
                                componentTransformList[1]))) > 0.01 or abs(
                                    float(str(
                                        componentTransformList[2]))) > 0.01:
                            print "There are unsupported transformed components in letter:", glyph.name
            except:
                print "There was a problem reading the components for glyph:", glyph.name

    # Resolve nested components.
    GlyphsWithNestedComponemts = set()
    for glyph in Font.glyphs:
        if checkForNestedComponentsAndDecompose(Font, glyph, MasterCount):
            GlyphsWithNestedComponemts.add(glyph.name)
            checkForNestedComponentsAndDecompose(
                Font, glyph, MasterCount)  # run it again to get double nests.

    if len(GlyphsWithNestedComponemts) > 0:
        print "The font has nested components. They are not supported in FontLab and were decomposed.\n(%s)" % ", ".join(
            sorted(GlyphsWithNestedComponemts))
    fl.UpdateFont()
Example #32
0
 def hsv_conv(self, re, gr, bl):
     """Used to convert rgb to hsv."""
     import colorsys
     hsv = colorsys.rgb_to_hsv(re/255, gr/255, bl/255)
     return hsv
Example #33
0
 def set_hexcol(self, hexcol):
     self._hexcol = hexcol
     self._h, self._s, self._v = colorsys.rgb_to_hsv(*MColor.hex_to_rgb(hexcol))
Example #34
0
 def getBrightnessString(self, light):
     color = light.node().getColor()
     h, s, b = colorsys.rgb_to_hsv(color[0], color[1], color[2])
     return "%.2f" % b
Example #35
0
def meets_min_saturation(c, threshold):
    return colorsys.rgb_to_hsv(*norm_color(c.value))[1] > threshold
Example #36
0
def main():
	parser = argparse.ArgumentParser(description="F**k up an image")
	parser.add_argument('filename', type=str, help="File to f**k")
	parser.add_argument('colorsize', type=int, help="Minimum: ceil(cbrt(width*height)) - color resolution")
	parser.add_argument('--order', type=int, nargs=3, default=[0,1,2], help="Order to check cells in, default 0 1 2")
	parser.add_argument('--hsv', action='store_true', default=False, help="Use HSV instead of RGB. Be warned, this breaks the whole uniqueness thing since (255, 0, 0) is the same color as (33, 0, 0)")
	parser.add_argument('--sort', type=int, default=None, help="Sort a thing. Include a number between 0 and however many I end up adding to change modes. I like 0")
	parser.add_argument('--sort_again', type=int, default=None, help="Sort a thing in a different place. 3 is cool")
	parser.add_argument('--be_slow', action='store_true', default=False, help="Do a BFS for end points. This is slow. Don't do this. Literally I'm leaving this code in here in case I accidentally break shit. Note: I'm pretty sure this is broken if you use --order")
	parser.add_argument('--output_dir', type=str, default=os.getcwd(), help="Where to put the f****d file")
	parser.add_argument('--output_file', type=str, help="Where to put the f****d file, but also the name")
	args = parser.parse_args()

	global filename
	filename = args.filename
	print "File: {}\n\n".format(filename)

	# Filename shit
	global output_filename
	if args.output_file is None:
		if args.output_dir is None:
			output_filename = os.path.join(filename, '_output00')
		else:
			output_filename = os.path.join(args.output_dir, os.path.basename(filename) + '_output00')
		# Default to not overwriting files
		filename_version = 0
		while os.path.exists(output_filename + '.bmp'):
			output_filename = output_filename[:-2] + str(filename_version).zfill(2)
			filename_version += 1
		output_filename = output_filename + '.bmp'
	else:
		output_filename = args.output_file

	global color_size
	color_size = args.colorsize

	if args.hsv:
		get_adj = get_adj_HSB
		convert_color = lambda a, b, c : colorsys.rgb_to_hsv(a, b, c)
		unconvert_color = lambda a, b, c : colorsys.hsv_to_rgb(a, b, c)
	else:
		get_adj = get_adj_RGB
		convert_color = lambda a, b, c : (a, b, c)
		unconvert_color = lambda a, b, c : (a, b, c)

	input_image = Image.open(filename).convert()
	width, height = input_image.size

	# Init input pixel list, and modify it to only use appropriate colors
	input_pixels = input_image.load()
	transform_pixels = {}
	for x in range(width):
		for y in range(height):
			a = input_pixels[x, y][0] / 255.0
			b = input_pixels[x, y][1] / 255.0
			c = input_pixels[x, y][2] / 255.0

			a, b, c = convert_color(a, b, c)

			a = a * (color_size - 1)
			b = b * (color_size - 1)
			c = c * (color_size - 1)

			transform_pixels[x, y] = (int(a), int(b), int(c))

	del input_image

	# Init 3d 'color' space, where we will do the smoothing
	# each point in this space is a list of (x,y) coordinates
	transform_colorspace = {}
	for a in range(color_size):
		for b in range(color_size):
			for c in range(color_size):
				transform_colorspace[(a, b, c)] = deque()

	for x in range(width):
		for y in range(height):
			key = transform_pixels[x, y]

			# Reorder shit
			key = get_ordered_args(args.order, *key)

			transform_colorspace[key].append((x, y))

	del transform_pixels

	# Now do the actual color smoothing
	start_keys = [x for x in sorted(transform_colorspace, key=lambda x: len(transform_colorspace[x])) if len(transform_colorspace[x]) > 1] # MY MAX LINE LENGTH IS INFINITY	
	_test_keys = [x for x in transform_colorspace if len(transform_colorspace[x]) == 0]
	_prev = 0
	queue = deque()
	for key_number, start_key in enumerate(start_keys):
		if args.sort == 0:
			transform_colorspace[start_key]= deque(sorted(transform_colorspace[start_key], key=lambda x: x[0] - x[1]))
		elif args.sort == 1:
			transform_colorspace[start_key]= deque(sorted(transform_colorspace[start_key], key=lambda x: get_dist(x[0], x[1], width, height))) # lol this line is actually longer
		else:
			transform_colorspace[start_key]= deque(transform_colorspace[start_key])

		if len(transform_colorspace[start_key]) != _prev:
			prev = len(transform_colorspace[start_key])
			sys.stdout.write('\r' + "{0:.2f}%".format(key_number / len(start_keys) * 100))
			sys.stdout.flush()

		# Maybe BFS if the user hates life
		if args.be_slow:
			## BEGIN REALLY SHITTY INEFFICIENT SEARCH:
			# Declare shit
			end_keys = []
			searched = {} # Use a dict for searched keys because hash maps are fastish
			prev = {}
			queue.clear()

			# Init shit
			start_key_size = len(transform_colorspace[start_key])
			queue.append(start_key)
			searched[start_key] = None # We only care if the key exists, not it's value
			prev[start_key] = None

			# Breadth first search for a viable spot to flatten to
			while queue:
				current_key = queue.popleft()
				# If the size of the point here is zero (ie there are no points 
				# that are this color), it's an end point
				if len(transform_colorspace[current_key]) == 0:
					end_keys.append(current_key)
					# We need to find start_key_size - 1 open spots
					if(len(end_keys) >= start_key_size - 1):
						break

				# Search the nodes that are adjacent to this one
				for adj in get_adj(current_key, searched, args.order, color_size):
					searched[adj] = None
					prev[adj] = current_key
					queue.append(adj)

			# For each end point we found, slide along the path and move the 
			# tail of one point to the head of the next.
			for end_key in end_keys:
				assert prev[end_key] is not None # This would be really bad

				current_key = end_key
				while prev[current_key] is  not None:
					transform_colorspace[current_key].append(transform_colorspace[prev[current_key]].popleft())
					current_key = prev[current_key]
			## END REALLY SHITTY SLOW STUFF
		else:
			# Oh good we're not masochists

			# Find nearby empty spots
			## Dumb way to do it:
			# end_keys = [x for x in transform_colorspace if len(transform_colorspace[x]) == 0]
			# Less dumb way to do it:
			# Use expanding cubic shells of pixels to pick a decent approximation of nearest color

			end_key_count = len(transform_colorspace[start_key]) - 1 # How many empty spaces we need
			end_keys = get_target_keys(end_key_count, start_key, transform_colorspace, color_size)
			assert end_key_count == len(end_keys)

			# Possibly sort the end keys according to xy distance from the start point
			if args.sort_again == 0:
				end_keys = sorted(end_keys, key=lambda x: x[0])
			elif args.sort_again == 1:
				end_keys = sorted(end_keys, key=lambda x: x[1])
			elif args.sort_again == 2:
				end_keys = sorted(end_keys, key=lambda x: x[2])
			elif args.sort_again == 3:
				end_keys = sorted(end_keys, key=lambda x:(x[0]<<1 + x[1]<<1 + x[2]<<1))

			# Slide keys along the path to each end point from this point
			for end_key in end_keys:
				path = get_path_RGB(start_key, end_key)

				prev_key = path[0]
				for curr_key in path[1:]:
					transform_colorspace[curr_key].append(transform_colorspace[prev_key].popleft())
					prev_key = curr_key

		assert len(transform_colorspace[start_key]) == 1

	for key in transform_colorspace:
		if len(transform_colorspace[key]) > 1:
			print len(transform_colorspace[key])
			print key in _test_keys

	# Transform back to 256 colors
	print "\nConverting image..."
	output_image = Image.new("RGB", (width, height))
	for key, point in transform_colorspace.iteritems():
		ordered_key = get_unordered_args(args.order, *key)

		a = float(ordered_key[0]) / (color_size - 1)
		b = float(ordered_key[1]) / (color_size - 1)
		c = float(ordered_key[2]) / (color_size - 1)

		a, b, c = unconvert_color(a, b, c)

		a = int(float(a) * 255)
		b = int(float(b) * 255)
		c = int(float(c) * 255)

		for pos in point:
			x, y = pos
			output_image.putpixel((x, y), (a, b, c))

	try:
		output_image.save(output_filename)
		print "Saved image to {}".format(output_filename)
	except:
		"Couldn't save file {}".format(output_filename)

	output_image.show()
Example #37
0
 def testGetHsv(self):
     hsv = colorsys.rgb_to_hsv(20.0 / 255, 40.0 / 255, 60.0 / 255)
     hsva = int(hsv[0] * 360.0), int(hsv[1] * 255), int(
         hsv[2] * 256), self.color.alpha()
     self.assertEqual(self.color.getHsv(), hsva)
Example #38
0
def hex_to_hsv(hex_color):
    rgb_color = hex_to_rgb(hex_color)
    return colorsys.rgb_to_hsv(*(val / 255 for val in rgb_color))
 def hsv(self):
     if self.data is not None:
         return colorsys.rgb_to_hsv(*self.rgb)
     else:
         return None
def read_color():
    for idx, pin_states in enumerate(pin_reading_seq):
        # Select colour filter
        GPIO.output(S2, pin_states[0])
        GPIO.output(S3, pin_states[1])
        ##############################
        time.sleep(0.01)

        start = time.time()  # start timing measurement to time pulse length

        # Wait until the NUM_cycles pulses have been counted
        for impulse_count in range(NUM_CYCLES):
            GPIO.wait_for_edge(Out, GPIO.FALLING)
        ####################################################

        duration = time.time() - start  # calculate duration of pulses
        RGBW[idx] = (
            (NUM_CYCLES / duration) / 10000
        ) * 255  # compute Red, Green and White colour components and scale to 0-255

    # Scale Red, Green & Blue components with respect to the White/Brightness reading
    RGBW[0] = (RGBW[0] / RGBW[3])
    RGBW[1] = (RGBW[1] / RGBW[3])
    RGBW[2] = (RGBW[2] / RGBW[3])
    #################################################################################

    HSV_val = colorsys.rgb_to_hsv(
        RGBW[0], RGBW[1],
        RGBW[2])  # Convert RGB colour readings into HSV colour space

    color_str = ""

    # Convert Red, Green & Blue values to rounded percentages
    R_perc = round(RGBW[0] * 100)
    G_perc = round(RGBW[1] * 100)
    B_perc = round(RGBW[2] * 100)
    #########################################################

    hue_deg = round(HSV_val[0] * 360)  # Convert Hue to rounded degrees

    # Convert value and saturation to rounded percentages
    val_perc = round(HSV_val[1] * 100)
    sat_perc = round(HSV_val[2] * 100)
    #####################################################

    if OLED_SCREEN_INSTALLED:
        # draw "black" rectangle to clear screen space for updated numbers
        draw.rectangle((34, 0, 63, 30), fill=0)
        draw.rectangle((100, 0, 127, 30), fill=0)
        ###################################################################

        # Put updated Red, Green and Blue percentages on screen
        draw.text((30, 0),
                  "{:3d} %".format(R_perc),
                  font=font,
                  fill=255,
                  align="right")
        draw.text((30, 10),
                  "{:3d} %".format(G_perc),
                  font=font,
                  fill=255,
                  align="right")
        draw.text((30, 20),
                  "{:3d} %".format(B_perc),
                  font=font,
                  fill=255,
                  align="right")
        #################################################################################

        # Put updated Hue, value and saturation numbers on screen
        draw.text((100, 0),
                  "{:3d} °".format(hue_deg),
                  font=font,
                  fill=255,
                  align="right")
        draw.text((100, 10),
                  "{:3d} %".format(val_perc),
                  font=font,
                  fill=255,
                  align="right")
        draw.text((100, 20),
                  "{:3d} %".format(sat_perc),
                  font=font,
                  fill=255,
                  align="right")
        ####################################################################################

    # Determine colour based on hue parameter
    if sat_perc < 35:
        color_str = "Black/Dark"
    elif hue_deg > 357 or hue_deg < 10:
        color_str = "ORANGE"
    elif hue_deg > 10 and hue_deg < 40:
        color_str = "YELLOW"
    elif hue_deg > 45 and hue_deg < 160:
        color_str = "GREEN"
    elif hue_deg > 210 and hue_deg < 270:
        color_str = "BLUE"
    elif hue_deg > 270 and hue_deg < 330:
        color_str = "PURPLE"
    elif hue_deg > 340 and hue_deg < 356:
        color_str = "RED"
    else:
        color_str = "No valid color detected"
    #########################################

    if OLED_SCREEN_INSTALLED:
        draw.rectangle(
            (0, 34, 128, 60),
            fill=0)  # clear bottom part of screen by drawing "black" rectangle

        # if a valid color is detected...
        if color_str != "No valid color detected" and color_str != "Black/Dark":
            draw.rectangle((0, 34, 128, 60),
                           fill=255)  # Draw a filled rectangle as background
            w, h = draw.textsize(
                color_str,
                font=font2)  # Calculate pixel width and height of color name
            draw.text(((128 - w) / 2, 33), color_str, font=font2,
                      fill=0)  # Put color name on screen with inversed text

        # Update OLED screen with new image
        oled.image(image)
        oled.show()
        ###################################

    return color_str, HSV_val
Example #41
0
def make_gradient(sel,gradient,nbins,sat,value):
	if gradient == 'bgr' or gradient == 'rainbow':
		col=[]
		coldesc=[]
		for j in range(nbins):
			# must append the str(sel[j]) to the color name so that it is unique 
			# for the selection
			coldesc.append('col' + str(sel[j]) + str(j))

			# create colors using hsv scale (fractional) starting at blue(.6666667) 
			# through red(0.00000) in intervals of .6666667/(nbins -1) (the "nbins-1" 
			# ensures that the last color is, in fact, red (0)
			# rewrote this to use the colorsys module to convert hsv to rgb
			hsv = (colorsys.TWO_THIRD - colorsys.TWO_THIRD * float(j) / (nbins-1), sat, value)
			#convert to rgb and append to color list
			rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

			col.append(rgb)
			cmd.set_color("col" + str(sel[j]) + str(j),col[j])

	elif gradient == 'rgb' or gradient == 'reverserainbow':
		col=[]
		coldesc=[]
		for j in range(nbins):
			# must append the str(sel[j]) to the color name so that it is unique 
			# for the selection
			coldesc.append('col' + str(sel[j]) + str(j))

			# create colors using hsv scale (fractional) starting at red(.00000) 
			# through blue(0.66667) in intervals of .6666667/(nbins -1) (the "nbins-1" 
			# ensures that the last color is, in fact, red (0)
			# rewrote this to use the colorsys module to convert hsv to rgb
			hsv = (colorsys.TWO_THIRD * float(j) / (nbins-1), sat, value)
			#convert to rgb and append to color list
			rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

			col.append(rgb)
			cmd.set_color("col" + str(sel[j]) + str(j),col[j])

	elif gradient == 'bmr':
		col=[]
		coldesc=[]
		for j in range(nbins):
			coldesc.append('col' + str(sel[j]) + str(j))
			# create colors in a gradient from blue through magenta to red
			rgb = [min(1.0, float(j)*2/(nbins-1)), 0.0, min(1.0, float(nbins-j-1)*2/(nbins-1))]

			# convert rgb to hsv,  modify saturation and value and convert back to rgb
			hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
			hsv[1] = hsv[1]*sat
			hsv[2] = hsv[2]*value
			rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

			col.append(rgb)
			cmd.set_color("col" + str(sel[j]) + str(j),col[j])

	elif gradient == 'rmb':
		col=[]
		coldesc=[]
		for j in range(nbins):
			coldesc.append('col' + str(sel[j]) + str(j))
			# create colors in a gradient from blue through magenta to red
			rgb = [min(1.0, float(nbins-j-1)*2/(nbins-1)), 0.0, min(1.0, float(j)*2/(nbins-1))]

			# convert rgb to hsv,  modify saturation and value and convert back to rgb
			hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
			hsv[1] = hsv[1]*sat
			hsv[2] = hsv[2]*value
			rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

			col.append(rgb)
			cmd.set_color("col" + str(sel[j]) + str(j),col[j])

	elif gradient == 'bwr':
		col=[]
		coldesc=[]
		for j in range(nbins/2):
			coldesc.append('col' + str(sel[j]) + str(j))
			# create colors in a gradient from blue to white 
			rgb = [min(1.0, float(j)*2/(nbins-1)), min(1.0,float(j)*2/(nbins-1)), min(1.0, float(nbins-j-1)*2/(nbins-1))]

			# convert rgb to hsv,  modify saturation and value and convert back to rgb
			hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
			hsv[1] = hsv[1]*sat
			hsv[2] = hsv[2]*value
			rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

			col.append(rgb)
			cmd.set_color("col" + str(sel[j]) + str(j),col[j])

		for j in range(nbins/2,nbins):
			coldesc.append('col' + str(sel[j]) + str(j))
			# create colors in a gradient from white to red
			rgb = [min(1.0, float(j)*2/(nbins-1)), min(1.0,float(nbins-j-1)*2/(nbins-1)), min(1.0, float(nbins-j-1)*2/(nbins-1))]

			# convert rgb to hsv,  modify saturation and value and convert back to rgb
			hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
			hsv[1] = hsv[1]*sat
			hsv[2] = hsv[2]*value
			rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

			col.append(rgb)
			cmd.set_color("col" + str(sel[j]) + str(j),col[j])

	elif gradient == 'bw':
		col=[]
		coldesc=[]
		for j in range(nbins):
			coldesc.append('col' + str(sel[j]) + str(j))
			# create colors in a gradient from blue to white 
			rgb = [min(1.0, float(j)/(nbins-1)), min(1.0,float(j)/(nbins-1)), min(1.0, float(nbins - j -1)/(nbins-1))]
			rgb = bluewhitegradient(j,nbins)
			print rgb
			# convert rgb to hsv,  modify saturation and value and convert back to rgb
			hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
			hsv[1] = hsv[1]*sat
			hsv[2] = hsv[2]*value
			rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

			col.append(rgb)
			cmd.set_color("col" + str(sel[j]) + str(j),col[j])

	elif gradient == 'wr':
		col=[]
		coldesc=[]
		for j in range(nbins):
			coldesc.append('col' + str(sel[j]+str(nbins)) + str(j))
			# create colors in a gradient from white to red
			#value = nbins/2 + float(j/2.0) #nbins/2 + float(j/2.0)
			#value = j
			#rgb = [min(1.0, float(value)*2/(nbins-1)), min(1.0, float(nbins -value-1)*2/(nbins-1)), min(1.0, float(nbins -value -1)*2/(nbins-1))]
			rgb = whiteredgradient(j,nbins) #[float(j)/(nbins-1), 1.0, 1.0] # float(nbins-j+1)/(nbins-1), 1.0]#float(nbins-j+1)/(nbins-1)]
			#rgb = [min(1.0, float(j)/(nbins-1)), min(1.0,float(nbins-j-1)/(nbins-1)), min(1.0, float(nbins-j-1)/(nbins-1))]

			# convert rgb to hsv,  modify saturation and value and convert back to rgb
			hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
			hsv[1] = hsv[1]*sat
			hsv[2] = hsv[2]*value
			rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

			col.append(rgb)
			cmd.set_color("col" + str(sel[j]+str(nbins)) + str(j),col[j])

	elif gradient == 'rwb':
		col=[]
		coldesc=[]
		for j in range(nbins/2):
			coldesc.append('col' + str(sel[j]) + str(j))
			# create colors in a gradient from red to white
			rgb = [min(1.0, float(nbins-j-1)*2/(nbins-1)), min(1.0,float(j)*2/(nbins-1)), min(1.0, float(j)*2/(nbins-1))]

			# convert rgb to hsv,  modify saturation and value and convert back to rgb
			hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
			hsv[1] = hsv[1]*sat
			hsv[2] = hsv[2]*value
			rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

			col.append(rgb)
			cmd.set_color("col" + str(sel[j]) + str(j),col[j])

		for j in range(nbins/2,nbins):
			coldesc.append('col' + str(sel[j]) + str(j))
			# create colors in a gradient from white to blue
			rgb = [min(1.0, float(nbins-j-1)*2/(nbins-1)), min(1.0,float(nbins-j-1)*2/(nbins-1)), min(1.0, float(j)*2/(nbins-1))]

			# convert rgb to hsv,  modify saturation and value and convert back to rgb
			hsv = list(colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]))
			hsv[1] = hsv[1]*sat
			hsv[2] = hsv[2]*value
			rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

			col.append(rgb)
			cmd.set_color("col" + str(sel[j]) + str(j),col[j])

	elif gradient == 'gray' or gradient == 'grey':
		col=[]
		coldesc=[]
		for j in range(nbins):
			coldesc.append('col' + str(sel[j]) + str(j))
			# create colors in a gradient of grays from "sat" to "value"

			hsv = [0, 0, sat + (value-sat)*float(j)/(nbins-1)]
#			hsv[1] = hsv[1]*sat
#			hsv[2] = hsv[2]*value
			rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

			col.append(rgb)
			cmd.set_color("col" + str(sel[j]) + str(j),col[j])

	elif gradient == 'reversegray' or gradient == 'reversegrey':
		col=[]
		coldesc=[]
		for j in range(nbins):
			coldesc.append('col' + str(sel[j]) + str(j))
			# create colors in a gradient of grays from "sat" to "value"

			hsv = [0, 0, value - (value-sat)*float(j)/(nbins-1)]
#			hsv[1] = hsv[1]*sat
#			hsv[2] = hsv[2]*value
			rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

			col.append(rgb)
			cmd.set_color("col" + str(sel[j]) + str(j),col[j])


# return the gradient as a color description that include the selection as 
# part of its name
	return coldesc
max_intensity = 100
hues = {}

# (3) Examine each pixel in the image file
for x in xrange(0, xs):
    for y in xrange(0, ys):
        # (4)  Get the RGB color of the pixel
        [r, g, b] = img[x, y]

        # (5)  Normalize pixel color values
        r /= 255.0
        g /= 255.0
        b /= 255.0

        # (6)  Convert RGB color to HSV
        [h, s, v] = colorsys.rgb_to_hsv(r, g, b)

        # (7)  Marginalize s; count how many pixels have matching (h, v)
        if h not in hues:
            hues[h] = {}
        if v not in hues[h]:
            hues[h][v] = 1
        else:
            if hues[h][v] < max_intensity:
                hues[h][v] += 1

# (8)   Decompose the hues object into a set of one dimensional arrays we can use with matplotlib
h_ = []
v_ = []
i = []
colours = []
Example #43
0
 def as_hsv(self):
     u"""
     Creates an hsv triplet from a ScreenColor.
     Each result component ranges from 0..1
     """
     return rgb_to_hsv(*self.normalise().as_tuple())
Example #44
0
from PIL import Image
import colorsys

img = Image.open("lenna.jpeg")  # must be in same folder
width, height = img.size
pixels = img.load()

for i in range(width):
    for j in range(height):
        r, g, b = pixels[i, j]
        # colorsys uses colors in the range [0, 1]
        h, s, v = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
        # s = .350/255
        # v = .50/255
        # h = .50/255

        s += .1
        v -= .25
        h += .5

        # do some math on h, s, v

        r, g, b = colorsys.hsv_to_rgb(h, s, v)

        # convert back to [0, 255]

        r = int(r * 255)
        g = int(g * 255)
        b = int(b * 255)

        pixels[i, j] = (r, g, b)
Example #45
0
    with open('foo.html', 'w') as fh:
        write_header(fh)
        #for algorithm in ('none', 'rgb', 'hsv', 'hls', 'luminosity', 'step', 'travelling-salesman'):
        #for algorithm in ('none', 'hsv', 'step', 'kmeans'):
        #for algorithm in ('none', 'hsv', 'kmeans'):
        for algorithm in ('kmeans', 'kmeans2'):

            if algorithm == 'none':
                tmp_colors = colors

            elif algorithm == 'rgb':
                tmp_colors = sorted(colors)

            elif algorithm == 'hsv':
                tmp_colors = deepcopy(colors)
                tmp_colors.sort(key=lambda rgb: colorsys.rgb_to_hsv(*rgb))

            elif algorithm == 'hls':
                tmp_colors = deepcopy(colors)
                tmp_colors.sort(key=lambda rgb: colorsys.rgb_to_hls(*rgb))

            elif algorithm == 'luminosity':
                tmp_colors = deepcopy(colors)
                tmp_colors.sort(key=lambda rgb: lum(*rgb))

            elif algorithm == 'step':
                tmp_colors = deepcopy(colors)
                tmp_colors.sort(key=lambda rgb: step(*rgb, 6))

            elif algorithm == 'travelling-salesman':
                tmp_colors = travelling_salesman(deepcopy(colors))
Example #46
0
 def get_hsv(self):
     rgb = self.get_rgb()
     h, s, v = colorsys.rgb_to_hsv(*rgb)
     return self.h, s, v
Example #47
0
def rgb_to_hsv(T):
    if len(T) > 3:
        T = T[:3]
    return colorsys.rgb_to_hsv(*T)
Example #48
0
def MouseEvent(event, x, y, flags, param):
    global frame, last_rgb, sleep, console_h, group_colors
    if event == cv2.EVENT_FLAG_LBUTTON:
        rgb = frame[y, x, :][::-1].tolist()
        if not operator.eq(last_rgb, rgb):
            last_hsv = [
                round(i, 2)
                for i in colorsys.rgb_to_hsv(last_rgb[0] / 255.0, last_rgb[1] /
                                             255.0, last_rgb[2] / 255.0)
            ]
            hsv = [
                round(j, 2)
                for j in colorsys.rgb_to_hsv(rgb[0] / 255.0, rgb[1] /
                                             255.0, rgb[2] / 255.0)
            ]

            last_Lab = [round(i, 1) for i in RGB2Lab(last_rgb[::-1])]
            Lab = [round(j, 1) for j in RGB2Lab(rgb[::-1])]

            cv2.rectangle(frame, (0, h), (w, h + console_h), (0, 0, 0), -1)
            frame = cv2ImgAddText(frame,
                                  f"██",
                                  5,
                                  h + 3,
                                  textColor=tuple(last_rgb),
                                  textSize=16)
            frame = cv2ImgAddText(frame,
                                  f"██",
                                  5,
                                  h + int(console_h / 2) + 3,
                                  textColor=tuple(rgb),
                                  textSize=16)

            frame = cv2ImgAddText(
                frame,
                f"RGB {last_rgb}, HSV {last_hsv}, Lab {last_Lab}",
                console_h,
                h + 3,
                textColor=(255, 255, 255),
                textSize=16)
            frame = cv2ImgAddText(frame,
                                  f"RGB {rgb}, HSV {hsv}, Lab {Lab}",
                                  console_h,
                                  h + int(console_h / 2) + 3,
                                  textColor=(255, 255, 255),
                                  textSize=16)
            print(f"RGB {rgb}")
            last_rgb = rgb
    if event == cv2.EVENT_LBUTTONDBLCLK:
        start_x = 600
        index = x // n * cell_h + y // n
        print(index)
        if index in group_colors.keys():
            group_color = group_colors[index]
            for i, group in enumerate(group_color):
                color = group[0]
                pro = group[1]
                cv2.rectangle(
                    frame, (start_x + i * console_h, h),
                    (start_x + console_h + i * console_h, h + console_h),
                    color[::-1], -1)
                frame = cv2ImgAddText(frame,
                                      f"{int(pro+0.5)}",
                                      start_x + i * console_h + 5,
                                      h + 5,
                                      textColor=(255, 255, 255),
                                      textSize=16)

    if flags == cv2.EVENT_FLAG_RBUTTON:
        if sleep == 0:
            sleep = 2000
            print(f"继续")
            cv2.destroyWindow(window_name)
            cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
            cv2.setMouseCallback(window_name, MouseEvent)  # 窗口与回调函数绑定
        else:
            print(f"暂停")
            sleep = 0
Example #49
0
def hex_to_hsv(hex):
    """Convert a hex string to hsv."""
    rgb = hex_to_rgb(hex)
    return colorsys.rgb_to_hsv(rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0)
Example #50
0
def rgba_to_hsv(red, green, blue, alpha=0):
    return colorsys.rgb_to_hsv(red / 255, green / 255, blue / 255)
    blue = 255
    red = 0
    green = 0
    blue_totaal = 0

    for blue_ind in range(0,sample_size):
        lcdDisplay.setColor(red,green,blue)
        blue_sample = float(lum.read())
        blue_totaal += blue_sample
        time.sleep(0.1)

    blue_avg = blue_totaal/sample_size
#    print "red: "+str(red)+"blu: "+str(blue)+"grn: "+str(green)+"lum: "+str(blue_avg)


    print "red: "+str(red_avg-66)+"blu: "+str(blue_avg-56)+"grn: "+str(green_avg-58)

    print colorsys.rgb_to_hsv(red_avg,green_avg, blue_avg)

    notes = [0,0,0,0,0,0,10,10,30,40,70,100,130,180,220,270,300,310,290,220,130,560,210,500,500,500,500]

#print buzzer.name()

    for notes_ind in range (0,24):
        buzzer.playSound(notes[notes_ind], 100000)
#    time.sleep(0.01)

del buzzer

Example #52
0
    def color(
        c: Union[str, Union[Tuple[Union[int, float], Union[int, float],
                                  Union[int, float], ],
                            Tuple[Union[int, float], Union[int, float],
                                  Union[int, float], Union[int,
                                                           float], ], ], ],
        input_format: ColorModel,
        output_format: ColorModel,
        round_output: bool = True,
    ) -> Union[str, Tuple[int, int, int], Tuple[int, int, int, int], Tuple[
            float, float, float], Tuple[float, float, float, float], ]:
        """Converts a provided color from a color model to another.

        Parameters:
            c (str or tuple of int or tuple of float): A color in the format ``input_format``.
            input_format (ColorModel): The color format of ``c``.
            output_format (ColorModel): The color format for the output.
            round_output (bool): A boolean to determine whether the output should be rounded or not.

        Returns:
            A color in the format ``output_format``.

        Examples:
            ..  code-block:: python3

                print(Convert.color("&H0000FF&", ColorModel.ASS, ColorModel.RGB))

            >>> (255, 0, 0)
        """
        try:
            # Text for exception if input is out of ranges
            input_range_e = f"Provided input '{c}' has value(s) out of the range "

            # Parse input, obtaining its corresponding (r,g,b,a) values
            if input_format == ColorModel.ASS:
                match = re.fullmatch(
                    r"&H([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})&", c)
                (b, g, r), a = map(lambda x: int(x, 16), match.groups()), 255
            elif input_format == ColorModel.ASS_STYLE:
                match = re.fullmatch(
                    r"&H([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})",
                    c)
                a, b, g, r = map(lambda x: int(x, 16), match.groups())
            elif input_format == ColorModel.RGB:
                if not all(0 <= n <= 255 for n in c):
                    raise ValueError(input_range_e + "[0, 255].")
                (r, g, b), a = c, 255
            elif input_format == ColorModel.RGB_STR:
                match = re.fullmatch(
                    r"#([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})", c)
                (r, g, b), a = map(lambda x: int(x, 16), match.groups()), 255
            elif input_format == ColorModel.RGBA:
                if not all(0 <= n <= 255 for n in c):
                    raise ValueError(input_range_e + "[0, 255].")
                r, g, b, a = c
            elif input_format == ColorModel.RGBA_STR:
                match = re.fullmatch(
                    r"#([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})",
                    c)
                r, g, b, a = map(lambda x: int(x, 16), match.groups())
            elif input_format == ColorModel.HSV:
                if not (0 <= c[0] < 360 and 0 <= c[1] <= 100
                        and 0 <= c[2] <= 100):
                    raise ValueError(input_range_e +
                                     "( [0, 360), [0, 100], [0, 100] ).")
                h, s, v = c[0] / 360, c[1] / 100, c[2] / 100
                (r, g, b), a = map(lambda x: 255 * x,
                                   colorsys.hsv_to_rgb(h, s, v)), 255
        except (AttributeError, ValueError, TypeError) as e:
            # AttributeError -> re.fullmatch failed
            # ValueError     -> too many values to unpack
            # TypeError      -> in case the provided tuple is not a list of numbers
            raise ValueError(
                f"Provided input '{c}' is not in the format '{input_format}'."
            ) from e

        # Convert (r,g,b,a) to the desired output_format
        try:
            if output_format == ColorModel.ASS:
                return f"&H{round(b):02X}{round(g):02X}{round(r):02X}&"
            elif output_format == ColorModel.ASS_STYLE:
                return f"&H{round(a):02X}{round(b):02X}{round(g):02X}{round(r):02X}"
            elif output_format == ColorModel.RGB:
                method = round if round_output else float
                return tuple(map(method, (r, g, b)))
            elif output_format == ColorModel.RGB_STR:
                return f"#{round(r):02X}{round(g):02X}{round(b):02X}"
            elif output_format == ColorModel.RGBA:
                method = round if round_output else float
                return tuple(map(method, (r, g, b, a)))
            elif output_format == ColorModel.RGBA_STR:
                return f"#{round(r):02X}{round(g):02X}{round(b):02X}{round(a):02X}"
            elif output_format == ColorModel.HSV:
                method = round if round_output else float
                h, s, v = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
                return method(h * 360) % 360, method(s * 100), method(v * 100)
            else:
                raise ValueError(
                    f"Unsupported output_format ('{output_format}').")
        except NameError as e:
            raise ValueError(
                f"Unsupported input_format ('{input_format}').") from e
Example #53
0
def test_hsv(data, data2 = []):

    x, y, color, c, max_color = donnees(data)

    centre = couleurCentre(data)
    centre_hsv = []
    tab_hsv = []
    tab_rgb, data_rgb = [], []
    #conversion centre rgb to hsv
    for i in range(0, len(centre)):
        color = t255to01(centre[i],max_color)
        #print "  couleur des donnees :  " , data[1][4] , "      couleur en format 0-1 : ", color
        centre_hsv.append( colorsys.rgb_to_hsv(color[0], color[1], color[2]) )
    #test sur toutes les facets
    
    data_hsv ,color_center, tab_rgb = [], [], []
    for i in range(0, len(data)):
        data_hsv.append([])
        color_center.append([])
        tab_hsv.append([])
        tab_rgb.append([])

    """
    Fig = plt.figure()
    ax = plt.axes(projection='3d') 
    """  
    for s, side in enumerate(data):
        for f, (r,g,b) in enumerate(side):
            data_hsv[s].append( colorsys.rgb_to_hsv( float(r)/max_color, float(g)/max_color, float(b)/max_color) )
            min_distance = 100000
            indice = 0
            for i in range(0, len(centre_hsv)):
                dist = distance_hsv(data_hsv[s][f], centre_hsv[i])
                if dist < min_distance:
                    min_distance = dist
                    indice = i
	    color_center[indice].append( [r,g,b] )
            tab_hsv[indice].append( data_hsv[s][f] )

    """
            ax.scatter3D(data_hsv[s][f][0], data_hsv[s][f][1], data_hsv[s][f][2], c=t255to01(data[s][f],max_color), cmap=data)
    """
    if len(data2) > 0:
        taux_erreur(data2, color_center)
        
    fig = plt.figure()
    for i in range(0,len(color_center) ):

      for j in range (0 , len(color_center[i])):
            plt.scatter(i, 10 + j* 5, s=800, marker='o', c=  rgb255to01(color_center[i][j], max_color) )
            plt.scatter(i, 0, s=800, marker='o', c= t255to01(centre[i],max_color) )

            
            
    tab_repar = repartition_egal(tab_hsv, centre_hsv, 9, False)
    
    fig = plt.figure()
    for i in range(0,len(tab_repar) ):

      for j in range (0 , len(tab_repar[i])):
          color = colorsys.hsv_to_rgb( tab_repar[i][j][0], tab_repar[i][j][1], tab_repar[i][j][2])
          plt.scatter(i, 10 + j* 5, s=800, marker='o', c=  color)
          plt.scatter(i, 0, s=800, marker='o', c= t255to01(centre[i],max_color) )
      
    plt.show()    
Example #54
0
def adjust_hsv_of_rgb(rgb, hue_adjust=0.0, sat_adjust=0.0, val_adjust=0.0):
    """ works on a single rgb tuple

    Args:
        rgb (tuple):
        hue_adjust (float):
        sat_adjust (float):
        val_adjust (float):

    Returns:
        ?: new_rgb

    CommandLine:
        python -m wbia.plottool.color_funcs --test-adjust_hsv_of_rgb --show

    Example:
        >>> # DISABLE_DOCTEST
        >>> from wbia.plottool.color_funcs import *  # NOQA
        >>> import wbia.plottool as pt
        >>> # build test data
        >>> rgb_list = [pt.DEEP_PINK[0:3], pt.DARK_YELLOW[0:3], pt.DARK_GREEN[0:3]]
        >>> hue_adjust = -0.1
        >>> sat_adjust = +0.5
        >>> val_adjust = -0.1
        >>> # execute function
        >>> new_rgb_list = [adjust_hsv_of_rgb(rgb, hue_adjust, sat_adjust, val_adjust) for rgb in rgb_list]
        >>> import wbia.plottool as pt
        >>> if pt.show_was_requested():
        >>>     color_list = rgb_list + new_rgb_list
        >>>     testshow_colors(color_list)
        >>> # verify results
        >>> result = str(new_rgb)
        >>> print(result)

    Ignore:
        print(np.array([-.1, 0.0, .1, .5, .9, 1.0, 1.1]))
        print(np.array([-.1, 0.0, .1, .5, .9, 1.0, 1.1]) % 1.0)
        print(divmod(np.array([-.1, 0.0, .1, .5, .9, 1.0, 1.1]), 1.0))
        print(1 + np.array([-.1, 0.0, .1, .5, .9, 1.0, 1.1]) % 1.0)
    """
    assert_base01(rgb)
    # assert_base01([sat_adjust, val_adjust])
    numpy_input = isinstance(rgb, np.ndarray)
    # For some reason numpy input does not work well
    if numpy_input:
        dtype = rgb.dtype
        rgb = rgb.tolist()
    # print('rgb=%r' % (rgb,))
    alpha = None
    if len(rgb) == 4:
        (R, G, B, alpha) = rgb
    else:
        (R, G, B) = rgb
    hsv = colorsys.rgb_to_hsv(R, G, B)
    (H, S, V) = hsv
    H_new = H + hue_adjust
    if H_new > 0 or H_new < 1:
        # is there a way to more ellegantly get this?
        H_new %= 1.0
    S_new = max(min(S + sat_adjust, 1.0), 0.0)
    V_new = max(min(V + val_adjust, 1.0), 0.0)
    # print('hsv=%r' % (hsv,))
    hsv_new = (H_new, S_new, V_new)
    # print('hsv_new=%r' % (hsv_new,))
    new_rgb = colorsys.hsv_to_rgb(*hsv_new)
    if alpha is not None:
        new_rgb = list(new_rgb) + [alpha]
    # print('new_rgb=%r' % (new_rgb,))
    assert_base01(new_rgb)
    # Return numpy if given as numpy
    if numpy_input:
        new_rgb = np.array(new_rgb, dtype=dtype)
    return new_rgb
Example #55
0
 def rgb255_to_hsv(cls, rgb255):
     return colorsys.rgb_to_hsv(*cls.rgb255_to_rgb(rgb255))
Example #56
0
#!/usr/bin/python

import os
import colorsys
import sys
from PIL import Image

meanHSV = []

for (path, dirs, files) in os.walk(sys.argv[1]):
    for fname in files:
        if fname.endswith(('.jpg', '.png')):
            im = Image.open(fname)
            meanRGB = [(float(sum(list(im.getdata(channel)))) /
                        len(list(im.getdata(channel)))) / 255
                       for channel in range(3)]
            meanHSV.append([
                colorsys.rgb_to_hsv(meanRGB[0], meanRGB[1], meanRGB[2]), fname
            ])

meanHSV.sort()
print '\n'.join([q[1] for q in meanHSV])
Example #57
0
def color_exchange(image, base_color, replacement_color, mask_path=None, validate_mask_colors=True, ignore_bright=False):
  if mask_path:
    mask_image = Image.open(mask_path).convert("RGBA")
    if image.size != mask_image.size:
      raise Exception("Mask image is not the same size as the texture.")
  
  if PY_FAST_TEXTURE_UTILS_INSTALLED:
    image_bytes = image.tobytes()
    
    if mask_path:
      mask_bytes = mask_image.tobytes()
    else:
      mask_bytes = None
    
    try:
      new_image_bytes = pyfasttextureutils.color_exchange(
        image_bytes, base_color, replacement_color,
        mask_bytes, validate_mask_colors, ignore_bright
      )
    except Exception as e:
      if str(e) == "Invalid color color in mask, only red (FF0000) and white (FFFFFF) should be present":
        # The exception given by PyFastTextureUtils for invalid colors is too vague. We list out all invalid colors when this happens with Python code instead.
        invalid_colors = []
        mask_pixels = mask_image.load()
        for x in range(image.width):
          for y in range(image.height):
            if mask_pixels[x, y] == (255, 0, 0, 255):
              # Red
              continue
            elif mask_pixels[x, y] == (255, 255, 255, 255):
              # White
              continue
            elif mask_pixels[x, y][3] == 0:
              # Completely transparent
              continue
            else:
              if mask_pixels[x, y] not in invalid_colors:
                invalid_colors.append(mask_pixels[x, y])
        invalid_colors_str = ", ".join("%02X%02X%02X%02X" % color for color in invalid_colors)
        new_err_message = "Mask %s has invalid colors in it. Only pure red (FF0000FF) and pure white (FFFFFFFF) are allowed.\n\nAll invalid colors in the mask are: %s" % (mask_path, invalid_colors_str)
        e.args = (new_err_message,)
        raise
      else:
        raise
    
    new_image = Image.frombytes(image.mode, (image.width, image.height), new_image_bytes)
    return new_image
  
  # When recoloring via native Python code, explicitly make a copy of the image and modify that.
  # This is for consistency with the C function, which has to return a copy.
  image = image.copy()
  
  if mask_path:
    mask_pixels = mask_image.load()
  
  base_r, base_g, base_b = base_color
  base_h, base_s, base_v = colorsys.rgb_to_hsv(base_r/255, base_g/255, base_b/255)
  base_h = int(base_h*360)
  base_s = int(base_s*100)
  base_v = int(base_v*100)
  
  replacement_r, replacement_g, replacement_b = replacement_color
  replacement_h, replacement_s, replacement_v = colorsys.rgb_to_hsv(replacement_r/255, replacement_g/255, replacement_b/255)
  replacement_h = int(replacement_h*360)
  replacement_s = int(replacement_s*100)
  replacement_v = int(replacement_v*100)
  
  s_change = replacement_s - base_s
  v_change = replacement_v - base_v
  
  pixels = image.load()
  for x in range(image.width):
    for y in range(image.height):
      if mask_path:
        if validate_mask_colors:
          if mask_pixels[x, y] == (255, 0, 0, 255):
            # Red, masked
            pass
          elif mask_pixels[x, y] == (255, 255, 255, 255):
            # White, unmasked
            continue
          elif mask_pixels[x, y][3] == 0:
            # Completely transparent, unmasked
            continue
          else:
            # Not red or white and also not completely transparent, so this is an invalid color.
            r, g, b, a = mask_pixels[x, y]
            raise Exception("Invalid color %02X%02X%02X%02X in mask %s" % (r, g, b, a, mask_path))
        else:
          if mask_pixels[x, y] != (255, 0, 0, 255):
            continue
      
      r, g, b, a = pixels[x, y]
      
      if ignore_bright and r > 128 and g > 128 and b > 128 and a == 0xFF:
        continue
      
      h, s, v = colorsys.rgb_to_hsv(r/255, g/255, b/255)
      h = int(h*360)
      s = int(s*100)
      v = int(v*100)
      
      if s == 0:
        # Prevent issues when recoloring black/white/grey parts of a texture where the base color is not black/white/grey.
        s = base_s
      
      new_h = replacement_h
      new_s = s + s_change
      new_v = v + v_change
      new_h = new_h % 360
      new_s = max(0, min(100, new_s))
      new_v = max(0, min(100, new_v))
      r, g, b = colorsys.hsv_to_rgb(new_h/360, new_s/100, new_v/100)
      r = int(r*255)
      g = int(g*255)
      b = int(b*255)
      pixels[x, y] = (r, g, b, a)
  
  return image
Example #58
0
#6. Implemente o código abaixo:

    # Exemplo para uso do Pillow
    # Converte as cores de uma imagem, rotacionando o matiz

    from PIL import Image
    from colorsys import rgb_to_hsv, hsv_to_rgb
    im_obj=Image.open('q6.jpg')
    print ("width = "+str(im_obj.width))
    print ("height = "+str(im_obj.height))
    shimg=im_obj.copy()
    pix=shimg.load()
    for shift in range(1,6):
        for i in range(im_obj.width):
            for j in range(im_obj.height):
                rgb=pix[i,j]
                hsv=rgb_to_hsv(*rgb)
                hsv=((hsv[0]+1.0/6)%1.0,hsv[1],hsv[2])
                r,g,b=hsv_to_rgb(*hsv)
                rgb=(int(r),int(g),int(b))
                pix[i,j]=rgb
        shimg.save("q6%02d.jpg"%shift)
    shimg.close()
    im_obj.close()


    #E comente o resultado obtido relacionando-o com a utilização da biblioteca Pillow.

    #Resposta Q6: Geram novas cores para as imagens utilizando manipulação com conversão de HSV para novos valores e retornando para RGB.
Example #59
0
def _strong_color(r, g, b):
    h, s, v = rgb_to_hsv(r / 256, g / 256, b / 256)
    strong_color = tuple(int(round(i * 255)) for i in hsv_to_rgb(h, s, 1))
    return strong_color
Example #60
0
File: color.py Project: jessopb/p5
 def _recompute_hsb(self):
     """Recompute the HSB values from the RGB values."""
     h, s, b = colorsys.rgb_to_hsv(self._red, self._green, self._blue)
     self._hue = h
     self._saturation = s
     self._brightness = b