def bin_dataframe(self, radius):
    """
    This function looks at the Set's dataframe and checks whether there are
    columns that are closer together than _radius_ in colorspace. Such columns
    are then merged. 
    
    The algorithm is similar to the DCB algorithm itself, which is heavily commented
    in the ColorList class.
    """
    cols = list(self.dataframe)
    
    # Perform checking
    for col in cols:
      colbgr = literal_eval(col)
      color = sRGBColor(colbgr[0], colbgr[1], colbgr[2], is_upscaled=True)
      color_lab = convert_color(color, LabColor)
      
      for compcol in cols[cols.index(col)+1:]:
        compcolbgr = literal_eval(compcol)
        compcolor = sRGBColor(compcolbgr[0], compcolbgr[1], compcolbgr[2], is_upscaled=True)
        compcolor_lab = convert_color(compcolor, LabColor)
        delta = delta_e_cie2000(color_lab, compcolor_lab)
        if ( delta < radius ):
          self.dataframe[col].fillna(self.dataframe[compcol], inplace=True)
          del self.dataframe[compcol]
          cols.remove(compcol)

    # Clean up dataframe (sorting columns, setting NaN to 0)
    #self.dataframe.sort_index(inplace=True)
    self.dataframe.fillna(0, inplace=True)
    self.dataframe = self.dataframe.reindex_axis(sorted(self.dataframe.columns, key=lambda x: self.dataframe[x].sum(), reverse=True), axis=1)
Example #2
0
def colorCloseEnough(color1, color2):
    rgb1 = sRGBColor(color1[0], color1[1], color1[2])
    rgb2 = sRGBColor(color2[0], color2[1], color2[2])
    lab1 = convert_color(rgb1, LabColor)
    lab2 = convert_color(rgb2, LabColor)

    return delta_e_cie1976(lab1, lab2) < 5000
Example #3
0
def get_colors(infile, outfile, numcolors=256, swatchsize=10, resize=150):
 
    image = Image.open(infile)
    image = image.resize((resize, resize))
    result = image.convert('P', palette=Image.ADAPTIVE, colors=numcolors)
    result.putalpha(0)
    colors = result.getcolors(resize*resize)

    hslcolors = map(lambda x: convert_color(sRGBColor(x[1][0], x[1][1], x[1][2], is_upscaled=True), HSLColor), colors)
    hslcolors = sorted(hslcolors, key=lambda c: c.hsl_s)
    hslcolors = sorted(hslcolors, key=lambda c: c.hsl_h)
    hslcolors = map(lambda c: HSLColor(c.hsl_h, 0.5 + 0.5 * c.hsl_s, 0.55 + 0.15 * c.hsl_l), hslcolors)
    hslcolors = map(lambda x: convert_color(x, sRGBColor).get_upscaled_value_tuple(), hslcolors)
 
    # Save colors to file
 
    pal = Image.new('RGB', (swatchsize*numcolors, swatchsize * 20))
    draw = ImageDraw.Draw(pal)
 
    posx = 0
    for col in hslcolors:
        draw.rectangle([posx, 0, posx+swatchsize, swatchsize * 20], fill=col)
        posx = posx + swatchsize
 
    del draw
    pal.save(outfile, "PNG")

    print "palettes.append(%s)" % str(hslcolors)
Example #4
0
def distance(c1, c2):
    """
    Calculate the visual distance between the two colors.
    """
    return delta_e_cmc(
        convert_color(sRGBColor(*c1, is_upscaled=True), LabColor),
        convert_color(sRGBColor(*c2, is_upscaled=True), LabColor)
    )
def color_diff(color_1, color_2):
    # Red Color 6
    color1_rgb = sRGBColor(color_1[0], color_1[1], color_1[2])
    #  Blue Color 9
    color2_rgb = sRGBColor(color_2[0], color_2[1], color_2[2])
    # Convert from RGB to Lab Color Space 12
    color1_lab = convert_color(color1_rgb, LabColor)
    # Convert from RGB to Lab Color Space 15
    color2_lab = convert_color(color2_rgb, LabColor)
    # Find the color difference 18
    delta_e = delta_e_cie2000(color1_lab, color2_lab)
    return delta_e
Example #6
0
def difference(a, b): # HLS
	print(a, b)
	#c1 = HSLColor(hsl_h = a[0], hsl_s = a[2]/100.0, hsl_l = a[1]/100.0)
	#c2 = HSLColor(hsl_h = b[0], hsl_s = a[2]/100.0, hsl_l = a[1]/100.0)
	c1RGB = sRGBColor(a[0], a[1], a[2])
	c2RGB = sRGBColor(b[0], b[1], b[2])
	c1Lab = convert_color(c1RGB, LabColor)
	c2Lab = convert_color(c2RGB, LabColor)
	#c1.convert_to('lab')
	#c2.convert_to('lab')
	print(delta_e_cie2000(c1Lab, c2Lab))
	return delta_e_cie2000(c1Lab, c2Lab)
Example #7
0
def colordiff_lab(pixel1,pixel2):

	#convert rgb values to L*ab values
	rgb_pixel_1=sRGBColor(pixel1[0],pixel1[1],pixel1[2],True)
	lab_1= convert_color(rgb_pixel_1, LabColor)

	rgb_pixel_2=sRGBColor(pixel2[0],pixel2[1],pixel2[2],True)
	lab_2= convert_color(rgb_pixel_2, LabColor)

	#calculate delta e
	delta_e = delta_e_cie1976(lab_1, lab_2)
	return delta_e
 def dynamic_binning(self, radius):
   """
   This function applies the dynamic color binning algorithm to the
   ColorList. This algorithm sorts the colors by pixel count. Selecting
   the most prominent color, it searches the rest of the list for similar
   (i.e. within a distance <radius> in Lab color space) colors and adds
   the pixel counts of those colors to that of the prominent color, thus
   binning together similar colors. In this way it goes down the list
   until all colors present have been binned.
   The function returns a new ColorList object, as well as a dictionary
   that tells the user which colors have been binned together. This
   dictionary is of the form {major_color: [list, of, minor, colors]}.
   """
   colorlist = self.colorlist
   clustered_colorlist = []
   synonymous_colors = {}
   
   for color in colorlist:
     color_copy = color
     synonymous_colors[tuple(color[0:2])] = []
     
     # Store color as Lab-color
     color_rgb = sRGBColor(color[0], color[1], color[2], is_upscaled=True)
     color_lab = convert_color(color_rgb, LabColor)
     
     # Loop through all the colors that are less prominent than the current color
     for color_compare in colorlist[colorlist.index(color)+1:]:
       
       # Store color as Lab-color
       color_compare_rgb = sRGBColor(color_compare[0], color_compare[1], color_compare[2], is_upscaled=True)
       color_compare_lab = convert_color(color_compare_rgb, LabColor)
       
       # Calculate the distance in color space
       delta = delta_e_cie2000(color_lab, color_compare_lab)
       
       # If distance is smaller than threshold, label as similar
       if ( delta < radius ):
         
         # Add up pixel counts
         color_copy[3] += color_compare[3]
         
         # Remove color from the list we are looping over
         colorlist.remove(color_compare)
         
         synonymous_colors[tuple(color[0:2])].append(color_compare[0:2])
     
     # Add color with updated pixel count to new list
     clustered_colorlist.append(color_copy)
   
   clustered_colorlist.sort(key=lambda tup: tup[3], reverse=True)
   
   BinnedColorList = ColorList.from_list(clustered_colorlist)
   return BinnedColorList, synonymous_colors
Example #9
0
def colordiff_lab(pixel1,pixel2):

	#convert rgb values to L*ab values
	rgb_pixel_source=sRGBColor(pixel1[0],pixel1[1],pixel1[2],True)
	lab_source= convert_color(rgb_pixel_source, LabColor)

	rgb_pixel_palette=sRGBColor(pixel2[0],pixel2[1],pixel2[2],True)
	lab_palette= convert_color(rgb_pixel_palette, LabColor)

	#calculate delta e
	delta_e = delta_e_cie1976(lab_source, lab_palette)
	return delta_e
Example #10
0
def colordiff_lab(source_pixel,palette_pixel):

	#convert rgb values to L*ab values
	rgb_pixel_source=sRGBColor(source_pixel[0],source_pixel[1],source_pixel[2],True)
	lab_source= convert_color(rgb_pixel_source, LabColor)

	rgb_pixel_palette=sRGBColor(palette_pixels[0],palette_pixels[1],palette_pixels[2],True)
	lab_palette= convert_color(rgb_pixel_palette, LabColor)

	#calculate delta e
	delta_e = delta_e_cie1976(lab_source, lab_palette)
	return delta_e
    def test_conversion_through_rgb(self):
        """
        Make sure our convenience RGB tracking feature is working. For example,
        going from XYZ->HSL via Adobe RGB, then taking that HSL object and
        converting back to XYZ should also use Adobe RGB (instead of the
        default of sRGB).
        """

        xyz = convert_color(self.color, XYZColor)
        hsl = convert_color(xyz, HSLColor, through_rgb_type=AdobeRGBColor)
        # Notice how we don't have to pass through_rgb_type explicitly.
        xyz2 = convert_color(hsl, XYZColor)
        self.assertColorMatch(xyz, xyz2)
Example #12
0
def combinecolors(c1, c2, firstweight):
    firstweight = random.uniform(0.25, 0.75)
    # extra chance to make it lopsided
    if random.random() < 0.5:
        firstweight = firstweight / random.uniform(2, 4)
        
    secondweight = 1-firstweight

    c = sRGBColor(c1[0], c1[1], c1[2], is_upscaled = True)
    c2 = sRGBColor(c2[0], c2[1], c2[2], is_upscaled = True)
    
    hsl1 = color_conversions.convert_color(c, HSLColor)
    hsl2 = color_conversions.convert_color(c2, HSLColor)
    hue1 = hsl1.hsl_h
    hue2 = hsl2.hsl_h

    # jank recombination of hue
    # make hue2 the greater one
    if hue2 > hue1:
        temp = hue1
        hue1 = hue2
        hue2 = temp

    # shrink green region to make recombination work- green is from 75 to 150
        
    recombinecount = 0
    if hue1 > 75:
        subtract = min((hue1-75), 25)
        hue1 = hue1 - subtract
        recombinecount += 1
    if hue2 > 75:
        subtract = min((hue2-75), 25)
        hue2 = hue2 - subtract
        recombinecount += 1
        
    new_hue = circle_ave(hue1, hue2, circlerange = 360-25)
    # add both if it was found on the greater side of the circle
    if new_hue > hue2 and recombinecount > 0:
        recombinecount = 2
    
    # convert back with green
    if new_hue > 75:
        new_hue = new_hue + (min(new_hue-75, 25)/2) * recombinecount
    
    new_hsl = HSLColor(new_hue,
                       hsl1.hsl_s*firstweight+hsl2.hsl_s*(1-firstweight),
                       hsl1.hsl_l*firstweight+hsl2.hsl_l*(1-firstweight))
    rgb = color_conversions.convert_color(new_hsl, sRGBColor)
    pygame_rgb = (int(rgb.rgb_r * 255), int(rgb.rgb_g * 255), int(rgb.rgb_b * 255))
    
    return pygame_rgb
Example #13
0
    def recolor(self):
        from_lab = convert_color(sRGBColor(*self.from_color), LabColor)
        from_hsv = convert_color(sRGBColor(*self.from_color), HSVColor)
        self._to_lab = convert_color(sRGBColor(*self.to_color), LabColor)
        range_ = self.range
        from_r, from_g, from_b = self.from_color
        to_r, to_g, to_b = self.to_color

        width, height = self.image.width, self.image.height
        pixel_count = width * height
        source_pixels = numpy.asarray(self.image)

        result_image = PIL.Image.new('RGB', (width, height), "black")
        target_pixels = result_image.load()

        pixels_done = 0
        for i in range(width):
            for j in range(height):
                r, g, b = source_pixels[j, i]
                hsv_pixel = convert_color(sRGBColor(r, g, b), HSVColor)
                distance = barkovsky_distance_3000(hsv_pixel, from_hsv)

                #distance = delta_e_cie2000(lab_pixel, from_lab)

                # distance = math.sqrt(
                #     (r - from_r) ** 2 +
                #     (g - from_g) ** 2 +
                #     (b - from_b) ** 2
                # )

                pixels_done += 1
                if pixels_done % 10000 == 0:
                    print('%d%%' % (pixels_done / pixel_count * 100))

                if distance > range_:
                    target_pixels[i, j] = (r, g, b)
                    continue

                r_diff = r - from_r
                g_diff = g - from_g
                b_diff = b - from_b

                r_new = cap_number(to_r + r_diff, 0, 255)
                g_new = cap_number(to_g + g_diff, 0, 255)
                b_new = cap_number(to_b + b_diff, 0, 255)
                target_pixels[i, j] = (
                    int(r_new), int(g_new), int(b_new)
                )

        self.set_result_image(result_image)
Example #14
0
def distinguishable_colors(n_colors):
	import numpy as np
	from colormath.color_objects import sRGBColor, LabColor
	from colormath.color_conversions import convert_color
	from matplotlib.colors import rgb2hex
	
	bg = [1,1,1]	#Assumes background is white


	#Generate 30^3 RGB triples to choose from.

	n_grid = 30	
	x = np.linspace(0,1,n_grid)
	R = np.array([x]*900).flatten()
	G = np.array([[i]*30 for i in x]*30).flatten()
	B = np.array([[i]*900 for i in x]).flatten()

	rgb = np.array([R,G,B]).T			#27000 by 3 matrix 

	if n_colors > len(rgb)/3:	#>27000
		print "You can't distinguish that many colors, dingus"
		return None

	#Convert to Lab colorspace
	lab = np.array([list(convert_color(sRGBColor(i[0], i[1], i[2]), LabColor).get_value_tuple()) for i in rgb])
	bglab = list(convert_color(sRGBColor(bg[0], bg[1], bg[2]), LabColor).get_value_tuple())

	#Compute the distance from background to candicate colors
	arr_length = len(rgb)
	mindist2 = np.empty(arr_length)
	mindist2.fill(float('Inf'))
	dX = lab - bglab
	dist2 = np.sum(np.square(dX), axis=1)
	mindist2 = np.minimum(dist2, mindist2)	

	#Pick the colors
	colors = np.zeros((n_colors, 3))
	lastlab = bglab
	
	for i in range(n_colors):
		dX = lab - lastlab	#subtract last from all colors in the list
		dist2 = np.sum(np.square(dX), axis=1)
		mindist2 = np.minimum(dist2, mindist2)
		index = np.argmax(mindist2)
		colors[i] = rgb[index]
		lastlab = lab[index]

	hex_colors =  [rgb2hex(item) for item in colors]

	return hex_colors
Example #15
0
def rgb2is(red, green, blue, colorsdb, nbest):
    colors = json.loads(open(colorsdb, 'r').read())
    color1_rgb = sRGBColor(red, green, blue, is_upscaled=True);
    color1_lab = convert_color(color1_rgb, LabColor);
    result = []

    for name, value in colors.items():
        color2_rgb = sRGBColor(*value, is_upscaled=True);
        color2_lab = convert_color(color2_rgb, LabColor);
        delta_e = delta_e_cie2000(color1_lab, color2_lab);
        result.append((delta_e, name))

    for res in sorted(result)[:nbest]:
        print('{1}, delta = {0}'.format(*res))
Example #16
0
def color_contrast(img):
  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  img = img.reshape((img.shape[0] * img.shape[1], 3))
  clt = KMeans(n_clusters = 3)
  clt.fit(img)
  color_centroids = [sRGBColor(r, g, b) for (r, g, b) in clt.cluster_centers_]
  color_diff = 0.0

  for (color_a, color_b) in combinations(color_centroids, 2):
    color_a_lab = convert_color(color_a, LabColor);
    color_b_lab = convert_color(color_b, LabColor);
    delta_e = delta_e_cie2000(color_a_lab, color_b_lab)
    color_diff += delta_e

  return float(color_diff/3)
Example #17
0
def avg_delta_e_2000(main1, tail1, main2, tail2):
    rgb_main1 = sRGBColor(main1[0], main1[1], main1[2])
    rgb_main2 = sRGBColor(main2[0], main2[1], main2[2])
    rgb_tail1 = sRGBColor(tail1[0], tail1[1], tail1[2])
    rgb_tail2 = sRGBColor(tail2[0], tail2[1], tail2[2])

    lab_main1 = convert_color(rgb_main1, LabColor)
    lab_main2 = convert_color(rgb_main2, LabColor)
    lab_tail1 = convert_color(rgb_tail1, LabColor)
    lab_tail2 = convert_color(rgb_tail2, LabColor)

    main_deltae = delta_e_cie2000(lab_main1, lab_main2)
    tail_deltae = delta_e_cie2000(lab_tail1, lab_tail2)
    pair_deltae = numpy.array([main_deltae,  tail_deltae])
    return numpy.average(pair_deltae, weights=[main_weight, tail_weight])
Example #18
0
def _kmeans_once(X, k, maxiter=1000, random_seed=None, verbose=False):

    centroids = _init_centroids(X,k,random_seed)
    labels, WCSS = _assign_cluster(X, centroids)
    
    for iter in range(maxiter):
         
        print "Iteration ", iter    
        new_centroids = _update_clusters(X, labels, k)
        labels, WCSS = _assign_cluster(X, new_centroids)
        
        if (verbose): print new_centroids
        
        if (new_centroids[0].get_value_tuple() == centroids[0].get_value_tuple() and \
            new_centroids[1].get_value_tuple() == centroids[1].get_value_tuple() and \
            new_centroids[2].get_value_tuple() == centroids[2].get_value_tuple()):
            break
        
        centroids = new_centroids
    
    if (verbose): 
        print "Converged in ", iter, "iterations"
        print centroids
    
    # Return centroids converted back to RGB
    centroidsRGB = [convert_color(centroid, sRGBColor).get_value_tuple() for centroid in centroids]

    return labels, centroidsRGB, WCSS
    def test_srgb_conversion_to_xyz_d65(self):
        """
        sRGB's native illuminant is D65. This is a straightforward conversion.
        """

        xyz = convert_color(self.color, XYZColor)
        self.assertColorMatch(xyz, XYZColor(0.294, 0.457, 0.103))
def example_spectral_to_xyz():
    """
    Instantiate an Lab color object with the given values. Note that the
    spectral range can run from 340nm to 830nm. Any omitted values assume a
    value of 0.0, which is more or less ignored. For the distribution below,
    we are providing an example reading from an X-Rite i1 Pro, which only
    measures between 380nm and 730nm.
    """

    print("=== Example: Spectral->XYZ ===")
    spc = SpectralColor(
        observer='2', illuminant='d50',
        spec_380nm=0.0600, spec_390nm=0.0600, spec_400nm=0.0641,
        spec_410nm=0.0654, spec_420nm=0.0645, spec_430nm=0.0605,
        spec_440nm=0.0562, spec_450nm=0.0543, spec_460nm=0.0537,
        spec_470nm=0.0541, spec_480nm=0.0559, spec_490nm=0.0603,
        spec_500nm=0.0651, spec_510nm=0.0680, spec_520nm=0.0705,
        spec_530nm=0.0736, spec_540nm=0.0772, spec_550nm=0.0809,
        spec_560nm=0.0870, spec_570nm=0.0990, spec_580nm=0.1128,
        spec_590nm=0.1251, spec_600nm=0.1360, spec_610nm=0.1439,
        spec_620nm=0.1511, spec_630nm=0.1590, spec_640nm=0.1688,
        spec_650nm=0.1828, spec_660nm=0.1996, spec_670nm=0.2187,
        spec_680nm=0.2397, spec_690nm=0.2618, spec_700nm=0.2852,
        spec_710nm=0.2500, spec_720nm=0.2400, spec_730nm=0.2300)
    xyz = convert_color(spc, XYZColor)
    print(xyz)
    print("=== End Example ===\n")
Example #21
0
def print_color(color):
	if type(color) is int:
		colstr = '5;' + str(color)
	else:
		rgb = convert_color(color, sRGBColor)
		colstr = '2;' + ';'.join((str(i) for i in get_upscaled_values(rgb)))
	sys.stdout.write('\033[48;' + colstr + 'm ')
Example #22
0
def named_colorset(colorfile):
    """From a file, generate a set of named color objects"""
    colorset = json.load(open(colorfile))
    for color in colorset['colors']:
        cobj = convert_color(sRGBColor.new_from_rgb_hex(color['hex']), LabColor)
        color['obj'] = cobj
    return colorset['colors']
Example #23
0
def get_lab(name, rgb):
	rgb = sRGBColor(
		int(rgb[:2], 16), int(rgb[2:4], 16), int(rgb[4:6], 16),
		is_upscaled=True
	)
	lab = convert_color(rgb, LabColor)
	return name, lab
Example #24
0
 def to_Lab(color):
     from colormath.color_objects import LabColor, sRGBColor
     from colormath.color_conversions import convert_color
     return convert_color(
         sRGBColor(*color, is_upscaled=True),
         LabColor
     ).get_value_tuple()
Example #25
0
def _rgb_to_lab(rgb):
    orgb = sRGBColor(rgb[0], rgb[1], rgb[2])
    orgb.is_upscaled = False
    r = convert_color(orgb, LabColor).get_value_tuple()
    if not np.all(np.isfinite(r)):
        raise ValueError('Found non finite values in input rgb tuple {} '.format(rgb))
    return r
Example #26
0
def createcolors(min_colors, max_colors):
    """Creates some random colors and saves them to the DB."""

    from colorsearchtest.database import db
    from colorsearchtest.models import Color

    from colormath.color_conversions import convert_color
    from colormath.color_objects import sRGBColor, LabColor

    # Based on:
    # https://github.com/kevinwuhoo/randomcolor-py/blob/master/test_randomcolor.py

    import randomcolor
    import random

    rand_color = randomcolor.RandomColor()

    rand = random.Random()
    rand_int = lambda: rand.randint(min_colors, max_colors)

    i = rand_int()
    colors = rand_color.generate(count=i, format_='rgbArray')

    for x in colors:
        c_rgb = sRGBColor(rgb_r=x[0], rgb_g=x[1], rgb_b=x[2],
                          is_upscaled=True)
        c_lab = convert_color(c_rgb, LabColor)

        c = Color(rgb_r=x[0], rgb_g=x[1], rgb_b=x[2],
                  lab_l=c_lab.lab_l, lab_a=c_lab.lab_a, lab_b=c_lab.lab_b)
        db.session.add(c)

    db.session.commit()

    return i
Example #27
0
    def __init__(self, palette: str="palette.bin", distinguishing: float=5.0):
        """ Constructor.

        :param palette:
        :param distinguishing:
        """
        self.distinguish = distinguishing
        self.colorList = []
        self.labColorList = []
        self.lBound, self.uBound = 0.0, 0.0

        persistence = shelve.open(palette)
        _colorList = persistence['data']

        for colorTuple in _colorList:
            color = sRGBColor(colorTuple[0], colorTuple[1], colorTuple[2])
            self.colorList.append(color)
            self.labColorList.append(convert_color(color, LabColor))

        persistence.close()

        self.colorsCount = len(self.colorList)

        for i in range(self.colorsCount):
            for j in range(i, self.colorsCount):
                distance = delta_e_cmc(self.labColorList[i], self.labColorList[j])
                self.lBound = min(self.lBound, distance)
                self.uBound = max(self.uBound, distance)
Example #28
0
def find_color_code_by_color_distance(r, g, b, algorithm='delta_e_cie2000'):
    """

    :param r:
    :param g:
    :param b:
    :param algorithm:
    :return: tuple(sRGBColor, color_code)
    """
    color = sRGBColor(r, g, b)
    lab_color = convert_color(color, LabColor)
    distances = [algorithms[algorithm](lab_color, convert_color(x[0], LabColor)) for x in color_wheel]
    np_distances = np.array(distances)
    idx = np.argmin(np_distances)
    ans_color = color_wheel[idx][0]
    return convert_color(ans_color, sRGBColor).get_value_tuple(), (color_wheel[idx][1], color_wheel[idx][2])
Example #29
0
def worker(gridwork):
    ret = []

    predefinedcolors = False
    if len(gridwork.beadlist):
        predefinedcolors = True

    ravg, gavg, bavg = 0, 0, 0
    blockpixels = gridwork.xgrid*gridwork.ygrid
    offset=0
    for y in range(0,gridwork.ygrid):
        for x in range(0,gridwork.xgrid):
            travg, tgavg, tbavg = gridwork.region[offset]
            ravg+=travg
            gavg+=tgavg
            bavg+=tbavg
            offset+=1

    nr, ng, nb = (ravg/blockpixels), (gavg/blockpixels), (bavg/blockpixels)
    if predefinedcolors:
        index = gridwork.beadlist.keys()[0]
        if gridwork.fastcolor:
            closest = colordistance((nr, ng, nb), (gridwork.beadlist[index][0], gridwork.beadlist[index][1], gridwork.beadlist[index][2]))
        else:
            rgblab = convert_color(sRGBColor( nr, ng, nb), LabColor)
            closest = delta_e_cie2000(rgblab, convert_color(sRGBColor( gridwork.beadlist[index][0], gridwork.beadlist[index][1], gridwork.beadlist[index][2] ), LabColor))

        for key in gridwork.beadlist:
            hr = gridwork.beadlist[key][0]
            hg = gridwork.beadlist[key][1]
            hb = gridwork.beadlist[key][2]

            if fastcolor:
                delta = colordistance((nr, ng, nb), (hr, hg, hb))
            else:
                beadlab = convert_color(sRGBColor( hr, hg, hb ), LabColor)
                delta = delta_e_cie2000(rgblab, beadlab)

            if delta < closest:
                index = key
                closest = delta

        nr, ng, nb = gridwork.beadlist[index][0], gridwork.beadlist[index][1], gridwork.beadlist[index][2]

    gridwork.color = (nr, ng, nb)
    ret.append((gridwork.color,gridwork.box))
    return ret
    def test_srgb_conversion_to_xyz_d50(self):
        """
        sRGB's native illuminant is D65. Test the XYZ adaptations by setting
        a target illuminant to something other than D65.
        """

        xyz = convert_color(self.color, XYZColor, target_illuminant='D50')
        self.assertColorMatch(xyz, XYZColor(0.313, 0.460, 0.082))
Example #31
0
def scaledRGBTupleToHSL(s):
    rgb = sRGBColor(s[0], s[1], s[2], True)
    return convert_color(rgb, HSLColor)
def matchValues(hash, R, B, G):
    log("Attempting API request on /match/%s/%d/%d/%d" % (hash, R, G, B), True)

    redisVidHashToImageHash = redis.Redis(host=redisHost,
                                          db=1,
                                          decode_responses=True)
    redisImgHashToTimestamp = redis.Redis(host=redisHost,
                                          db=2,
                                          decode_responses=True)
    redisImageHashToColorPalette = redis.Redis(host=redisHost,
                                               db=3,
                                               decode_responses=True)

    imageList = sorted(list(redisVidHashToImageHash.smembers(hash)),
                       key=lambda item: int(redisImgHashToTimestamp.get(item)))

    if len(imageList) == 0:
        response = {
            "message":
            "No color palettes matched for the specified color and hash. Either hash does not exist or server is not done processing"
        }
        response_pickled = jsonpickle.encode(response)
        log(
            'POST /match/%s/%d/%d/%d HTTP/1.1 200 - No Images' %
            (hash, R, G, B), True)

        return Response(response=response_pickled,
                        status=200,
                        mimetype="application/json")

    R /= 255.0
    G /= 255.0
    B /= 255.0
    color1_rgb = sRGBColor(R, G, B)
    # Convert from RGB to Lab Color Space
    color1_lab = convert_color(color1_rgb, LabColor)

    toPlot = [False] * len(imageList)

    buf = io.BytesIO()
    subplt = 0
    for imageHash in imageList:
        #Get color centers from redis db
        centers = [
            i.split(' ')
            for i in redisImageHashToColorPalette.get(imageHash).split(',')
        ]
        centers = np.array([np.array([float(n) for n in i]) for i in centers])

        for RGB in centers:
            color2_rgb = sRGBColor(RGB[0], RGB[1], RGB[2])
            # Convert from RGB to Lab Color Space
            color2_lab = convert_color(color2_rgb, LabColor)
            # Find the color difference
            delta_e = delta_e_cie2000(color1_lab, color2_lab)
            print(delta_e)
            if delta_e <= 10:
                toPlot[subplt] = True
        subplt += 1

    numToPlot = np.sum(toPlot)
    fig, axs = plt.subplots(numToPlot * 2,
                            figsize=(14,
                                     14 if numToPlot == 0 else numToPlot * 14))

    subplt = 0
    n = 0
    for imageHash in imageList:
        if toPlot[n]:
            centers = [
                i.split(' ')
                for i in redisImageHashToColorPalette.get(imageHash).split(',')
            ]
            centers = np.array(
                [np.array([float(n) for n in i]) for i in centers])

            img = downloadFromGCS(imageHash,
                                  'csci4253finalproject',
                                  '%s/%s' % (hash, imageHash),
                                  file_perms='w+b')

            #Plot the image
            axs[subplt].imshow(np.array(Image.open(img)))
            axs[subplt].grid()
            axs[subplt].set_title("Timestamp: %s ms" %
                                  (redisImgHashToTimestamp.get(imageHash)),
                                  fontsize=40)
            axs[subplt].axis('off')

            subplt += 1
            # Plot the palette
            axs[subplt].imshow(centers[np.concatenate(
                [[i] * 100 for i in range(len(centers))]).reshape((-1, 10)).T])
            axs[subplt].grid()
            axs[subplt].axis('off')
            subplt += 1

            img.close()
            os.remove(img.name)
        n += 1

    plt.savefig(buf, format='jpg')
    buf.seek(0)

    log('GET /match/%s/%d/%d/%d HTTP/1.1 200' % (hash, R, G, B), True)
    return send_file(buf,
                     mimetype='image/jpg',
                     as_attachment=False,
                     attachment_filename='results_%s.jpg' % hash)
Example #33
0
def staticGold():
  gold = sRGBColor(255, 200, 0)
  gold = convert_color(gold, LabColor)
  return gold
Example #34
0
print("Avg pixel intensity on right face : ", calcAvgPixel(right_face))

# Calculate the avg pixel of each half face

r1, g1, b1 = calcAvgPixel(left_face)

r2, g2, b2 = calcAvgPixel(right_face)

color1_rgb = sRGBColor(r1, g1, b1)

color2_rgb = sRGBColor(r2, g2, b2)

# Convert from RGB to Lab Color Space

color1_lab = convert_color(color1_rgb, LabColor)

color2_lab = convert_color(color2_rgb, LabColor)

# Find the color difference

delta_e = delta_e_cie2000(color1_lab, color2_lab)

print("The difference between the 2 color = ", delta_e)

# Impose a threshold either from user or hard-coded

# threshold = int(input("Enter a threshold: "))
threshold = 25
if delta_e > threshold:
    print("Asymmetry exists!")
Example #35
0
                    outputCl = outputBlockStart[1] + cl
                    if (outputRw < args.outputSize
                            and outputCl < args.outputSize):
                        nextVertOverlap[rw, cl] = output[outputRw, outputCl]

        #convert vertical rgb color space to lab color space
        if (cb > 0):
            for rw in range(blockWidth):
                for cl in range(args.overlap):
                    prevValues = prevVertOverlap[rw, cl]
                    nextValues = nextVertOverlap[rw, cl]
                    prevRGB = sRGBColor(prevValues[0], prevValues[1],
                                        prevValues[2])
                    nextRGB = sRGBColor(nextValues[0], nextValues[1],
                                        nextValues[2])
                    prevLab = convert_color(prevRGB, LabColor)
                    nextLab = convert_color(nextRGB, LabColor)
                    left = min(args.overlap - 1, cl + 1)
                    right = max(0, cl - 1)
                    if (rw == 0):
                        diffVertOverlap[rw, cl] = delta_e_cie1976(
                            prevLab, nextLab)
                    else:
                        diffVertOverlap[rw, cl] = delta_e_cie1976(
                            prevLab, nextLab) + min(
                                diffVertOverlap[rw - 1, right],
                                diffVertOverlap[rw - 1, cl],
                                diffVertOverlap[rw - 1, left])

        #calculate vertical minimum boundary cut
        if (cb > 0):
Example #36
0
def staticred():
  redbar = sRGBColor(148, 100, 116)
  redbar = convert_color(redbar, LabColor)
  return redbar
 def getColor(id):
     color = HSVColor(id * 60 % 360, 150, 200)
     return np.array(
         convert_color(color, sRGBColor).get_value_tuple()
     ) / 255.0  # FIXME: This is bgr color
Example #38
0
    def grab_vis_params(self, index, get_op_img=False):
        with open(self.inputs_dir + self.input_files[index]) as input_file:
            all_inputs = np.array([float(val.rstrip()) for val in input_file])

        # setup view params
        view_params = np.zeros(5)
        view_params[0] = 2.0 * (
            (all_inputs[0] - self.min_elevation) /
            (self.max_elevation - self.min_elevation)) - 1.0
        view_params[1] = np.cos(np.deg2rad(all_inputs[1]))
        view_params[2] = np.sin(np.deg2rad(all_inputs[1]))
        view_params[3] = all_inputs[2] / self.roll_range
        view_params[4] = 2.0 * ((all_inputs[3] - self.min_zoom) /
                                (self.max_zoom - self.min_zoom)) - 1.0

        # next, grab the opacity TF
        verbose_op_func = np.reshape(all_inputs[4:(4 + 2 * self.tf_res)],
                                     (self.tf_res, 2))
        op_tf = 2.0 * verbose_op_func[:, 1:] - 1.0
        op_tf = op_tf.T

        # grab the color TF
        verbose_color_func = np.reshape(all_inputs[(4 + 2 * self.tf_res):],
                                        (self.tf_res, 4))
        lab_color_tf = np.array([
            convert_color(sRGBColor(rgb[0], rgb[1], rgb[2]),
                          LabColor).get_value_tuple()
            for rgb in verbose_color_func[:, 1:]
        ])
        color_tf = np.zeros((3, self.tf_res))
        color_tf[0, :] = 2.0 * ((lab_color_tf[:, 0] - self.min_lab_l) /
                                (self.max_lab_l - self.min_lab_l)) - 1.0
        color_tf[1, :] = 2.0 * ((lab_color_tf[:, 1] - self.min_lab_a) /
                                (self.max_lab_a - self.min_lab_a)) - 1.0
        color_tf[2, :] = 2.0 * ((lab_color_tf[:, 2] - self.min_lab_b) /
                                (self.max_lab_b - self.min_lab_b)) - 1.0

        if get_op_img:
            # and the opacity image
            pil_rgba_img = Image.open(self.imgs_dir +
                                      self.img_files[index]).convert("RGBA")
            np_rgba_img = np.array(pil_rgba_img).astype(np.uint8)
            np_opacity_img = np.zeros(
                (np_rgba_img.shape[0], np_rgba_img.shape[1],
                 3)).astype(np.uint8)
            np_opacity_img[:, :, 0] = np_rgba_img[:, :, 3]
            np_opacity_img[:, :, 1] = np_rgba_img[:, :, 3]
            np_opacity_img[:, :, 2] = np_rgba_img[:, :, 3]
            if self.target_opacity_res != pil_rgba_img.width:
                pil_opacity_img = Image.fromarray(np_opacity_img).resize(
                    (self.target_opacity_res, self.target_opacity_res),
                    resample=PIL.Image.BICUBIC)
            else:
                pil_opacity_img = Image.fromarray(np_opacity_img)
            target_opacity_img = np.array(pil_opacity_img,
                                          dtype=np.float32) / 255.0
            target_opacity_img = np.swapaxes(target_opacity_img[:, :, 0:1].T,
                                             axis1=1,
                                             axis2=2)
            return view_params, op_tf, color_tf, target_opacity_img
        else:
            return view_params, op_tf, color_tf
Example #39
0
def lab2rgb(pt):
    return convert_color(LabColor(pt[0], pt[1], pt[2]),
                         sRGBColor).get_value_tuple()
 def rgb_error(self):
     return delta_e_cie2000(
         convert_color(self.m_lch, LabColor),
         convert_color(sRGBColor.new_from_rgb_hex(self.rgb()), LabColor))
Example #41
0
 def get_rgb_colors(self):
     """Return a dictionary of sRGB color objects (not just coordinates)."""
     return {
         name: Palette.clamp_rgb_color(convert_color(lab, sRGBColor))
         for name, lab in self.get_lab_colors().items()
     }
 def rgb(self):
     rgb = convert_color(self.m_lch, sRGBColor)
     if (rgb.rgb_r != rgb.clamped_rgb_r or rgb.rgb_g != rgb.clamped_rgb_g
             or rgb.rgb_b != rgb.clamped_rgb_b):
         raise Exception("Colour {} is outside sRGB".format(self.lch()))
     return rgb.get_rgb_hex()
Example #43
0
def get_mask_contours(image, monsters_in_image, debug=False):
    imgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(imgray, 5, 255, 0)
    contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    monster_contours = {}
    for i in range(len(contours)):
        # Create a mask image that contains the contour filled in
        cimg = np.zeros_like(imgray)
        cv2.drawContours(cimg, contours, i, color=255, thickness=-1)
        ret, thresh = cv2.threshold(cimg, 5, 255, 0)

        # Access the image pixels and create a 1D numpy array then add to list
        pts = np.where(cimg == 255)
        if len(pts[0]) < 500:
            continue

        counts = defaultdict(lambda: 0)
        for c in image[pts[0], pts[1]]:
            counts[tuple(c)] += 1

        unique_bgrs = [k for k in counts.keys() if counts[k] > 100]

        colors_per_monster = defaultdict(lambda: [])
        for bgr in unique_bgrs:
            closest_color = ()
            min_dist = 500000

            # Compute the closest color using the delta E metric
            # http://hanzratech.in/2015/01/16/color-difference-between-2-colors-using-python.html
            for color in monster_colors.keys():
                if monster_colors[color] not in monsters_in_image:
                    continue

                pixel_color = sRGBColor(bgr[2]/255, bgr[1]/255, bgr[0]/255)
                monster_color = sRGBColor(color[0]/100, color[1]/100, color[2]/100)

                # Convert from RGB to Lab Color Space
                pixel_color_lab = convert_color(pixel_color, LabColor)
                monster_color_lab = convert_color(monster_color, LabColor)

                delta_e = delta_e_cie2000(pixel_color_lab, monster_color_lab)

                if delta_e < min_dist:
                    min_dist = delta_e
                    closest_color = color

            # If the pixel is not black...
            if closest_color != (0, 0, 0):
                colors_per_monster[closest_color].append(bgr)

        for key, colors in colors_per_monster.items():
            colors = np.array(colors)
            min_color = np.min(colors, axis=0)
            max_color = np.max(colors, axis=0)

            mask = cv2.inRange(image, min_color, max_color)
            if cv2.countNonZero(mask) < 500:
                continue

            masked = cv2.bitwise_and(thresh, thresh, mask=mask)
            blurred = cv2.GaussianBlur(masked, (7, 7), 0)
            sub_contours, _ = cv2.findContours(blurred, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            monster_contours[key] = sorted(sub_contours, key=lambda x: -cv2.contourArea(x))[0]

            if debug:
                cv2.imshow(str(key), masked)

    if debug:
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    return monster_contours
Example #44
0
vector_list1 = []
vector_list2 = []

for t in test_pic:
    #line_vector存放一行的向量,vector_test存放一张图片的向量,vector_list1存放所有test图片的向量
    vector_test = []
    img1 = cv2.imread(pic_tests_dir + t, cv2.IMREAD_COLOR)
    #测试集图像不一定是400*400,所以要转换
    img1 = cv2.resize(img1, (50, 50), interpolation=cv2.INTER_CUBIC)
    print(t, 'is loading..........')
    for i in range(img1.shape[0]):
        line_vector = []
        for j in range(img1.shape[1]):
            #rgb转xyz转lab
            rgb1 = sRGBColor(img1[i][j][0], img1[i][j][1], img1[i][j][2])
            xyz1 = convert_color(rgb1, XYZColor)
            lab1 = convert_color(xyz1, LabColor, target_illuminant=str)
            line_vector.append(lab1)
        vector_test.append(line_vector)
    vector_list1.append(vector_test)

print('train_set loading complete!!!')

for c in colors:
    vector = []
    img2 = cv2.imread(pic_dir + c, cv2.IMREAD_COLOR)
    img2 = cv2.resize(img2, (50, 50), interpolation=cv2.INTER_CUBIC)
    print(c, 'is loading..........')
    for i in range(img2.shape[0]):
        line_vector_2 = []
        for j in range(img2.shape[1]):
 def _ipt_conversion():
     return convert_color(xyz, IPTColor)
 def test_conversion_to_xyz(self):
     xyz = convert_color(self.color, XYZColor)
     self.assertColorMatch(xyz, XYZColor(0.115, 0.099, 0.047))
 def test_consistency(self):
     xyz = convert_color(self.color, XYZColor)
     same_color = convert_color(xyz, IPTColor)
     self.assertColorMatch(self.color, same_color)
 def test_convert_to_self(self):
     same_color = convert_color(self.color, SpectralColor)
     self.assertEqual(self.color, same_color)
 def test_convert_to_XYZ(self):
     xyz = convert_color(self.color, XYZColor)
     self.assertColorMatch(
         xyz,
         XYZColor(0.4497, 0.2694, 0.0196, illuminant="d65", observer="2"))
Example #50
0
def isWhite(pix):
  color = sRGBColor(*(pix))
  color = convert_color(color, LabColor)
  similarity = delta_e_cie2000(color,statusWhite)
  return similarity
 def test_convert_so_self(self):
     same_color = convert_color(self.color, IPTColor)
     self.assertEqual(self.color, same_color)
Example #52
0
def isred(pix):
  color = sRGBColor(*(pix))
  color = convert_color(color, LabColor)
  similarity = delta_e_cie2000(color, minigame_red)
  return similarity
 def test_convert_to_self(self):
     same_color = convert_color(self.color, CMYKColor)
     self.assertEqual(self.color, same_color)
Example #54
0
def staticWhite():
  white = sRGBColor(255, 255, 255)
  white = convert_color(white, LabColor)
  return white
Example #55
0
def get_difference(rgb1, rgb2):
    lab1 = convert_color(rgb1, LabColor)
    lab2 = convert_color(rgb2, LabColor)
    delta = delta_e_cie2000(lab1, lab2)
    return delta
Example #56
0
def HSLToScaledRGBTuple(hsl):
    return convert_color(hsl, sRGBColor).get_upscaled_value_tuple()
Example #57
0
def distinguishable_colors(ncolors,
                           backgrounds=[[0, 0, 0], [1, 1, 1]],
                           save_csv=True,
                           plot_colormap=True,
                           verbose=True,
                           out_dir='.'):
    """
    Create a colormap of perceptually distinguishable colors.

    This program is a Python program based on Tim Holy's 2010-2011
    BSD-licensed Matlab program "distinguishable_colors.m"
    (https://www.mathworks.com/matlabcentral/fileexchange/
     29702-generate-maximally-perceptually-distinct-colors):

    "This function generates a set of colors which are distinguishable
    by reference to the "Lab" color space, which more closely matches
    human color perception than RGB. Given an initial large list of possible
    RGB colors, it iteratively chooses the entry in the list that is farthest
    (in Lab space) from all previously-chosen entries. While this "greedy"
    algorithm does not yield a global maximum, it is simple and efficient.
    Moreover, the sequence of colors is consistent no matter how many you
    request, which facilitates the users' ability to learn the color order
    and avoids major changes in the appearance of plots when adding or
    removing lines."

    Parameters
    ----------
    ncolors : integer
        number of colors for the colormap
    backgrounds : list of list(s) of 3 elements between 0 and 1
        rgb background colors to initialize and distinguish from
    save_csv : Boolean
        save colormap as csv file?
    plot_colormap : Boolean
        plot colormap as horizontal bar chart?
    verbose : Boolean
        print to stdout?

    Returns
    -------
    colors : numpy ndarray of ndarrays of 3 floats between 0 and 1
        rgb colormap

    Examples
    --------
    >>> from mindboggle.mio.colors import distinguishable_colors
    >>> ncolors = 31
    >>> backgrounds = [[0,0,0],[1,1,1]]
    >>> save_csv = False
    >>> plot_colormap = False
    >>> verbose = False
    >>> colors = distinguishable_colors(ncolors, backgrounds,
    ...     save_csv, plot_colormap, verbose)
    >>> colors[0]
    array([ 0.62068966,  0.06896552,  1.        ])
    >>> colors[1]
    array([ 0.       ,  0.5862069,  0.       ])
    >>> colors[2]
    array([ 0.75862069,  0.20689655,  0.        ])

    """
    import numpy as np
    import matplotlib.pyplot as plt
    from colormath.color_objects import LabColor, AdobeRGBColor
    from colormath.color_conversions import convert_color
    from colormath.color_diff import delta_e_cie2000

    filename = "colormap_of_{0}_distinguishable_colors".format(ncolors)
    filename = os.path.join(out_dir, filename)

    # ------------------------------------------------------------------------
    # Generate a sizable number of RGB triples. This represents our space of
    # possible choices. By starting in RGB space, we ensure that all of the
    # colors can be generated by the monitor:
    # ------------------------------------------------------------------------
    n_grid = 30  # number of grid divisions along each axis in RGB space
    x = np.linspace(0, 1, num=n_grid, endpoint=True)
    R, G, B = np.meshgrid(x, x, x)
    ncolors_total = np.size(R)
    RGB = np.vstack([np.ravel(R), np.ravel(G), np.ravel(B)])
    RGB = [[RGB[0][icolor], RGB[1][icolor], RGB[2][icolor]]
           for icolor in range(ncolors_total)]
    if ncolors > ncolors_total:
        raise IOError("You can't readily distinguish that many colors")

    # ------------------------------------------------------------------------
    # Convert to Lab color space which better represents human perception:
    # ------------------------------------------------------------------------
    # https://python-colormath.readthedocs.io/en/latest/illuminants.html
    lab_colors = []
    for rgb in RGB:
        lab = convert_color(AdobeRGBColor(rgb[0], rgb[1], rgb[2]), LabColor)
        lab_colors.append(lab)

    bg_lab_colors = []
    for bg_rgb in backgrounds:
        bg_lab = convert_color(AdobeRGBColor(bg_rgb[0], bg_rgb[1], bg_rgb[2]),
                               LabColor)
        bg_lab_colors.append(bg_lab)

    # ------------------------------------------------------------------------
    # If the user specified multiple background colors, compute differences
    # between the candidate colors and the background colors:
    # ------------------------------------------------------------------------
    min_dx = np.inf * np.ones(ncolors_total)
    if backgrounds:
        for bg_lab_color in bg_lab_colors:
            # Store difference from closest previously-chosen color:
            for icolor_total, lab_color in enumerate(lab_colors):
                dx = delta_e_cie2000(lab_color, bg_lab_color)
                min_dx[icolor_total] = min(dx, min_dx[icolor_total])

    # ------------------------------------------------------------------------
    # Iteratively pick the color that maximizes the difference
    # with the nearest already-picked color:
    # ------------------------------------------------------------------------
    # Initialize by making the "previous" color equal to the last background:
    last_lab_color = bg_lab_colors[-1]
    colors = np.zeros((ncolors, 3))
    for icolor in range(ncolors):

        # Find the difference of the last color from all colors on the list:
        for icolor_total, lab_color in enumerate(lab_colors):
            dx = delta_e_cie2000(lab_color, last_lab_color)
            min_dx[icolor_total] = min(dx, min_dx[icolor_total])

        # Find the entry farthest from all previously chosen colors:
        imax_dx = np.argmax(min_dx)

        # Store distant color:
        colors[icolor] = RGB[imax_dx]

        # Prepare for next iteration:
        last_lab_color = lab_colors[imax_dx]

    # ------------------------------------------------------------------------
    # Plot the colormap as a horizontal bar chart:
    # ------------------------------------------------------------------------
    if plot_colormap:
        if verbose:
            print("RGB values:")
        plt.figure(ncolors, figsize=(5, 10))
        for icolor in range(ncolors):
            ax = plt.subplot(ncolors, 1, icolor + 1)
            plt.axis("off")
            rgb = colors[icolor]
            #rgb = [[rgb.rgb_r, rgb.rgb_g, rgb.rgb_b]]
            if verbose:
                print(rgb)
            plt.barh(0, 50, 1, 0, color=rgb)
        plt.savefig(filename + ".png")
        if verbose:
            print("Colormap image saved to {0}".format(filename + ".png"))

    # ------------------------------------------------------------------------
    # Save the colormap as a csv file:
    # ------------------------------------------------------------------------
    if save_csv:
        np.savetxt(filename + ".csv",
                   colors,
                   fmt='%.18e',
                   delimiter=',',
                   newline='\n',
                   header='')
        if verbose:
            print("Colormap saved to {0}".format(filename + ".csv"))

    return colors
Example #58
0
def group_colors(colormap,
                 colormap_name,
                 description='',
                 adjacency_matrix=[],
                 IDs=[],
                 names=[],
                 groups=[],
                 save_text_files=True,
                 plot_colors=True,
                 plot_graphs=True,
                 out_dir='.',
                 verbose=True):
    """
    This greedy algoritm reorders a colormap so that labels assigned to
    the same group have more similar colors, but within a group (usually
    of adjacent labels), the colors are reordered so that adjacent labels
    have dissimilar colors:

    1. Convert colormap to Lab color space
       which better represents human perception.
    2. Load a binary (or weighted) adjacency matrix, where each row or column
       represents a label, and each value signifies whether (or the degree
       to which) a given pair of labels are adjacent.
       If a string (file) is provided instead of a numpy ndarray:
            column 0 = label "ID" number
            column 1 = label "name"
            column 2 = "group" number (each label is assigned to a group)
            columns 3... = label adjacency matrix
    3. Sort labels by decreasing number of adjacent labels (adjacency sum).
    4. Order label groups by decreasing maximum adjacency sum.
    5. Create a similarity matrix for pairs of colors.
    6. Sort colors by decreasing perceptual difference from all other colors.
    7. For each label group:
        7.1. Select unpicked colors for group that are similar to the first
             unpicked color (unpicked colors were sorted above by decreasing
             perceptual difference from all other colors).
        7.2. Reorder subgraph colors according to label adjacency sum
             (decreasing number of adjacent labels).
    8. Assign new colors.

    For plotting graphs and colormap:

    1. Convert the matrix to a graph, where each node represents a label
       and each edge represents the adjacency value between connected nodes.
    2. Break up the graph into subgraphs, where each subgraph contains labels
       assigned the same group number (which usually means they are adjacent).
    3. Plot the colormap and colored sub/graphs.

    NOTE: Requires pydotplus

    Parameters
    ----------
    colormap : string or numpy ndarray of ndarrays of 3 floats between 0 and 1
        csv file containing rgb colormap, or colormap array
    colormap_name : string
        name of colormap
    description : string
        description of colormap
    adjacency_matrix : string or NxN numpy ndarray (N = number of labels)
        csv file containing label adjacency matrix or matrix itself
    IDs : list of integers
        label ID numbers
    names : list of strings
        label names
    groups : list of integers
        label group numbers (one per label)
    save_text_files : Boolean
        save colormap as csv and json files?
    plot_colors : Boolean
        plot colormap as horizontal bar chart?
    plot_graphs : Boolean
        plot colormap as graphs?
    out_dir : string
        output directory path
    verbose : Boolean
        print to stdout?

    Returns
    -------
    colors : numpy ndarray of ndarrays of 3 floats between 0 and 1
        rgb colormap

    Examples
    --------
    >>> # Get colormap:
    >>> from mindboggle.mio.colors import distinguishable_colors
    >>> colormap = distinguishable_colors(ncolors=31,
    ...     backgrounds=[[0,0,0],[1,1,1]],
    ...     save_csv=False, plot_colormap=False, verbose=False)
    >>> # Get adjacency matrix:
    >>> from mindboggle.mio.colors import label_adjacency_matrix
    >>> from mindboggle.mio.fetch_data import prep_tests
    >>> urls, fetch_data = prep_tests()
    >>> label_file = fetch_data(urls['left_manual_labels'], '', '.vtk')
    >>> IDs, adjacency_matrix, output_table = label_adjacency_matrix(label_file,
    ...     ignore_values=[-1, 0], add_value=0, save_table=False,
    ...     output_format='', verbose=False)
    >>> adjacency_matrix = adjacency_matrix.values
    >>> adjacency_matrix = adjacency_matrix[:, 1::]
    >>> # Reorganize colormap:
    >>> from mindboggle.mio.colors import group_colors
    >>> from mindboggle.mio.labels import DKTprotocol
    >>> dkt = DKTprotocol()
    >>> colormap_name = "DKT31colormap"
    >>> description = "Colormap for DKT31 human brain cortical labels"
    >>> save_text_files = True
    >>> plot_colors = False
    >>> plot_graphs = False
    >>> out_dir = '.'
    >>> verbose = False
    >>> #IDs = dkt.DKT31_numbers
    >>> names = dkt.DKT31_names #dkt.left_cerebrum_cortex_DKT31_names
    >>> groups = dkt.DKT31_groups
    >>> colors = group_colors(colormap, colormap_name, description,
    ...     adjacency_matrix, IDs, names, groups,
    ...     save_text_files, plot_colors, plot_graphs, out_dir, verbose)
    >>> colors[0]
    [0.7586206896551724, 0.20689655172413793, 0.0]
    >>> colors[1]
    [0.48275862068965514, 0.4482758620689655, 0.48275862068965514]
    >>> colors[2]
    [0.3448275862068966, 0.3103448275862069, 0.034482758620689655]
    >>> colors[-1]
    [0.7931034482758621, 0.9655172413793103, 0.7931034482758621]

    No groups / subgraphs:

    >>> groups = []
    >>> colors = group_colors(colormap, colormap_name, description,
    ...     adjacency_matrix, IDs, names, groups,
    ...     save_text_files, plot_colors, plot_graphs, out_dir, verbose)
    >>> colors[0]
    [0.5172413793103449, 0.8275862068965517, 1.0]
    >>> colors[1]
    [0.13793103448275862, 0.0, 0.24137931034482757]
    >>> colors[2]
    [0.3793103448275862, 0.27586206896551724, 0.48275862068965514]
    >>> colors[-1]
    [0.6206896551724138, 0.48275862068965514, 0.3448275862068966]

    """
    import os
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import networkx as nx
    from colormath.color_diff import delta_e_cie2000
    from colormath.color_objects import LabColor, AdobeRGBColor
    from colormath.color_conversions import convert_color
    import itertools

    from mindboggle.mio.colors import write_json_colormap, write_xml_colormap

    # ------------------------------------------------------------------------
    # Set parameters for graph layout and output files:
    # ------------------------------------------------------------------------
    if plot_graphs:
        graph_node_size = 1000
        graph_edge_width = 2
        graph_font_size = 10
        subgraph_node_size = 3000
        subgraph_edge_width = 5
        subgraph_font_size = 18
        axis_buffer = 10
        graph_image_file = os.path.join(out_dir, "label_graph.png")
        subgraph_image_file_pre = os.path.join(out_dir, "label_subgraph")
        subgraph_image_file_post = ".png"

    if plot_colors:
        colormap_image_file = os.path.join(out_dir, 'label_colormap.png')

    if save_text_files:
        colormap_csv_file = os.path.join(out_dir, 'label_colormap.csv')
        colormap_json_file = os.path.join(out_dir, 'label_colormap.json')
        colormap_xml_file = os.path.join(out_dir, 'label_colormap.xml')

    run_permutations = False

    # ------------------------------------------------------------------------
    # Load colormap:
    # ------------------------------------------------------------------------
    if verbose:
        print("Load colormap and convert to CIELAB color space.")
    if isinstance(colormap, np.ndarray):
        colors = colormap
    elif isinstance(colormap, str):
        colors = pd.read_csv(colormap, sep=',', header=None)
        colors = colors.values
    else:
        raise IOError("Please use correct format for colormap.")
    nlabels = np.shape(colors)[0]
    new_colors = np.copy(colors)

    if len(IDs) == 0:
        IDs = range(nlabels)
    if len(names) == 0:
        names = [str(x) for x in range(nlabels)]
    if len(groups) == 0:
        groups = [1 for x in range(nlabels)]

    # ------------------------------------------------------------------------
    # Convert to Lab color space which better represents human perception:
    # ------------------------------------------------------------------------
    # https://python-colormath.readthedocs.io/en/latest/illuminants.html
    lab_colors = []
    for rgb in colors:
        lab_colors.append(
            convert_color(AdobeRGBColor(rgb[0], rgb[1], rgb[2]), LabColor))

    # ------------------------------------------------------------------------
    # Load label adjacency matrix:
    # ------------------------------------------------------------------------
    if np.size(adjacency_matrix):
        if verbose:
            print("Load label adjacency matrix.")
        if isinstance(adjacency_matrix, np.ndarray):
            adjacency_values = adjacency_matrix
        # If a string (file) is provided instead of a numpy ndarray:
        #    column 0 = label "ID" number
        #    column 1 = label "name"
        #    column 2 = "group" number (each label is assigned to a group)
        #    columns 3... = label adjacency matrix
        elif isinstance(adjacency_matrix, str):
            matrix = pd.read_csv(adjacency_matrix, sep=',', header=None)
            matrix = matrix.values
            IDs = matrix.ID
            names = matrix.name
            groups = matrix.group
            adjacency_values = matrix[[str(x) for x in IDs]].values
        else:
            raise IOError("Please use correct format for adjacency matrix.")
        if np.shape(adjacency_values)[0] != nlabels:
            raise IOError("The colormap and label adjacency matrix don't "
                          "have the same number of labels.")

        # Normalize adjacency values:
        adjacency_values = adjacency_values / np.max(adjacency_values)
    else:
        plot_graphs = False

    # ------------------------------------------------------------------------
    # Sort labels by decreasing number of adjacent labels (adjacency sum):
    # ------------------------------------------------------------------------
    if np.size(adjacency_matrix):
        adjacency_sums = np.sum(adjacency_values, axis=1)  # sum rows
        isort_labels = np.argsort(adjacency_sums)[::-1]
    else:
        isort_labels = range(nlabels)

    # ------------------------------------------------------------------------
    # Order label groups by decreasing maximum adjacency sum:
    # ------------------------------------------------------------------------
    label_groups = np.unique(groups)
    if np.size(adjacency_matrix):
        max_adjacency_sums = []
        for label_group in label_groups:
            igroup = [i for i, x in enumerate(groups) if x == label_group]
            max_adjacency_sums.append(max(adjacency_sums[igroup]))
        label_groups = label_groups[np.argsort(max_adjacency_sums)[::-1]]

    # ------------------------------------------------------------------------
    # Convert adjacency matrix to graph for plotting:
    # ------------------------------------------------------------------------
    if plot_graphs:
        adjacency_graph = nx.from_numpy_matrix(adjacency_values)
        for inode in range(nlabels):
            adjacency_graph.node[inode]['ID'] = IDs[inode]
            adjacency_graph.node[inode]['label'] = names[inode]
            adjacency_graph.node[inode]['group'] = groups[inode]

    # ------------------------------------------------------------------------
    # Create a similarity matrix for pairs of colors:
    # ------------------------------------------------------------------------
    if verbose:
        print("Create a similarity matrix for pairs of colors.")
    dx_matrix = np.zeros((nlabels, nlabels))
    for icolor1 in range(nlabels):
        for icolor2 in range(nlabels):
            dx_matrix[icolor1,
                      icolor2] = delta_e_cie2000(lab_colors[icolor1],
                                                 lab_colors[icolor2])
    # ------------------------------------------------------------------------
    # Sort colors by decreasing perceptual difference from all other colors:
    # ------------------------------------------------------------------------
    icolors_to_pick = list(np.argsort(np.sum(dx_matrix, axis=1))[::-1])

    # ------------------------------------------------------------------------
    # Loop through label groups:
    # ------------------------------------------------------------------------
    for label_group in label_groups:
        if verbose:
            print("Labels in group {0}...".format(label_group))
        igroup = [i for i, x in enumerate(groups) if x == label_group]
        N = len(igroup)

        # --------------------------------------------------------------------
        # Select unpicked colors for group that are similar to the first
        # unpicked color (unpicked colors were sorted above by decreasing
        # perceptual difference from all other colors):
        # --------------------------------------------------------------------
        isimilar = np.argsort(dx_matrix[icolors_to_pick[0],
                                        icolors_to_pick])[0:N]
        icolors_to_pick_copy = icolors_to_pick.copy()
        group_colors = [list(colors[icolors_to_pick[i]]) for i in isimilar]
        if run_permutations:
            group_lab_colors = [
                lab_colors[icolors_to_pick[i]] for i in isimilar
            ]
        for iremove in isimilar:
            icolors_to_pick.remove(icolors_to_pick_copy[iremove])

        # --------------------------------------------------------------------
        # Reorder group colors according to label adjacency sum
        # (decreasing number of adjacent labels):
        # --------------------------------------------------------------------
        isort_group_labels = np.argsort(isort_labels[igroup])
        group_colors = [group_colors[i] for i in isort_group_labels]

        # --------------------------------------------------------------------
        # Compute differences between every pair of colors within group:
        # --------------------------------------------------------------------
        weights = False
        if run_permutations:
            permutation_max = np.zeros(N)
            NxN_matrix = np.zeros((N, N))
            # ----------------------------------------------------------------
            # Extract group adjacency submatrix:
            # ----------------------------------------------------------------
            neighbor_matrix = adjacency_values[igroup, :][:, igroup]
            if not weights:
                neighbor_matrix = (neighbor_matrix > 0).astype(np.uint8)
            # ----------------------------------------------------------------
            # Permute colors and color pair differences:
            # ----------------------------------------------------------------
            DEmax = 0
            permutations = [
                np.array(s) for s in itertools.permutations(range(0, N), N)
            ]
            if verbose:
                print(" ".join([
                    str(N), 'labels,',
                    str(len(permutations)), 'permutations:'
                ]))
            for permutation in permutations:
                delta_matrix = NxN_matrix.copy()
                for i1 in range(N):
                    for i2 in range(N):
                        if (i2 > i1) and (neighbor_matrix[i1, i2] > 0):
                            delta_matrix[i1, i2] = delta_e_cie2000(
                                group_lab_colors[i1], group_lab_colors[i2])
                if weights:
                    DE = np.sum((delta_matrix * neighbor_matrix))
                else:
                    DE = np.sum(delta_matrix)
                # ------------------------------------------------------------
                # Store color permutation with maximum adjacency cost:
                # ------------------------------------------------------------
                if DE > DEmax:
                    DEmax = DE
                    permutation_max = permutation
                # ------------------------------------------------------------
                # Reorder group colors by the maximum adjacency cost:
                # ------------------------------------------------------------
                group_colors = [group_colors[x] for x in permutation_max]
                new_colors[isimilar] = group_colors

        # --------------------------------------------------------------------
        # Assign new colors:
        # --------------------------------------------------------------------
        else:
            new_colors[isimilar] = group_colors

        # --------------------------------------------------------------------
        # Draw a figure of the colored subgraph:
        # --------------------------------------------------------------------
        if plot_graphs:
            plt.figure(label_group)
            subgraph = adjacency_graph.subgraph(igroup)

            # Layout:
            pos = nx.nx_pydot.graphviz_layout(subgraph, prog="neato")
            nx.draw(subgraph,
                    pos,
                    node_size=subgraph_node_size,
                    width=subgraph_edge_width,
                    alpha=0.5,
                    with_labels=False)

            # Labels:
            labels = {}
            for iN in range(N):
                labels[subgraph.nodes()[iN]] = \
                    subgraph.node[subgraph.nodes()[iN]]['label']
            nx.draw_networkx_labels(subgraph,
                                    pos,
                                    labels,
                                    font_size=subgraph_font_size,
                                    font_color='black')
            # Nodes:
            nodelist = list(subgraph.node.keys())
            for iN in range(N):
                nx.draw_networkx_nodes(subgraph,
                                       pos,
                                       node_size=subgraph_node_size,
                                       nodelist=[nodelist[iN]],
                                       node_color=group_colors[iN])

            # Figure:
            ax = plt.gca().axis()
            plt.gca().axis([
                ax[0] - axis_buffer, ax[1] + axis_buffer, ax[2] - axis_buffer,
                ax[3] + axis_buffer
            ])
            plt.savefig(subgraph_image_file_pre + str(int(label_group)) +
                        subgraph_image_file_post)
            #plt.show()

    # ------------------------------------------------------------------------
    # Plot the entire graph (without colors):
    # ------------------------------------------------------------------------
    if plot_graphs:
        plt.figure(nlabels)

        # Graph:
        pos = nx.nx_pydot.graphviz_layout(adjacency_graph, prog="neato")
        nx.draw(adjacency_graph,
                pos,
                node_color='yellow',
                node_size=graph_node_size,
                width=graph_edge_width,
                with_labels=False)

        # Labels:
        labels = {}
        for ilabel in range(nlabels):
            labels[ilabel] = adjacency_graph.node[ilabel]['label']
        nx.draw_networkx_labels(adjacency_graph,
                                pos,
                                labels,
                                font_size=graph_font_size,
                                font_color='black')
        # # Nodes:
        # nodelist = list(adjacency_graph.node.keys())
        # for icolor, new_color in enumerate(new_colors):
        #     nx.draw_networkx_nodes(subgraph, pos,
        #                            node_size=graph_node_size,
        #                            nodelist=[nodelist[icolor]],
        #                            node_color=new_color)

        plt.savefig(graph_image_file)
        plt.show()

    # ------------------------------------------------------------------------
    # Plot the subgraphs (colors):
    # ------------------------------------------------------------------------
    if plot_graphs:
        for label_group in label_groups:
            plt.figure(label_group)
            plt.show()

    # ------------------------------------------------------------------------
    # Plot the colormap as a horizontal bar chart:
    # ------------------------------------------------------------------------
    if plot_colors:
        plt.figure(nlabels, figsize=(5, 10))
        for ilabel in range(nlabels):
            ax = plt.subplot(nlabels, 1, ilabel + 1)
            plt.axis("off")
            rgb = new_colors[ilabel]
            plt.barh(0, 50, 1, 0, color=rgb)
        plt.savefig(colormap_image_file)
        plt.show()

    # ------------------------------------------------------------------------
    # Save new colormap as text files:
    # ------------------------------------------------------------------------
    if save_text_files:

        # ------------------------------------------------------------------------
        # Save new colormap as a csv file:
        # ------------------------------------------------------------------------
        np.savetxt(colormap_csv_file,
                   new_colors,
                   fmt='%.18e',
                   delimiter=',',
                   newline='\n',
                   header='')

        # ------------------------------------------------------------------------
        # Save new colormap as a json file:
        # ------------------------------------------------------------------------
        write_json_colormap(colormap=new_colors,
                            label_numbers=IDs,
                            label_names=names,
                            colormap_file=colormap_json_file,
                            colormap_name=colormap_name,
                            description=description)

        # ------------------------------------------------------------------------
        # Save new colormap as an xml file:
        # ------------------------------------------------------------------------
        write_xml_colormap(colormap=new_colors,
                           label_numbers=IDs,
                           colormap_file=colormap_xml_file,
                           colormap_name=colormap_name)

    # ------------------------------------------------------------------------
    # Return new colors:
    # ------------------------------------------------------------------------
    colors = new_colors.tolist()

    return colors
Example #59
0
from colormath.color_objects import sRGBColor, XYZColor
from colormath.color_conversions import convert_color
from colormath.color_appearance_models import CIECAM02
from hyooze import xFF, DEPTH
from hyooze.mesh import EqualBrightnessMesh

REFERENCE_WHITE = convert_color(sRGBColor(1, 1, 1), XYZColor)


class Office:
    """Color perception models are environment dependent. This class encodes the
    assumptions about viewing conditions."""
    def __init__(self, ambient_lightness, background):
        self.ambient_lightness = ambient_lightness
        self.background = background
        background_xyz = convert_color(background, XYZColor)
        self.background_brightness = background_xyz.xyz_y

        self._mesh_cache = {}

    def rgb_to_cbh(self, r, g, b):
        target_xyz = convert_color(sRGBColor(r, g, b, is_upscaled=True),
                                   XYZColor)
        perception = CIECAM02(
            target_xyz.xyz_x,
            target_xyz.xyz_y,
            target_xyz.xyz_z,
            REFERENCE_WHITE.xyz_x,
            REFERENCE_WHITE.xyz_y,
            REFERENCE_WHITE.xyz_z,
            c=0.69,
Example #60
0
def rgb2lab(pt):
    return convert_color(sRGBColor(pt[0], pt[1], pt[2]),
                         LabColor).get_value_tuple()