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)
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
def output_html(): f = open('delta-e-cie2000.html', 'w') f.write('<table>') # header line = '<thead><tr><th></th>' for c in colors: rgb = sRGBColor(c['rgb'][0], c['rgb'][1], c['rgb'][2], True) line += '<th style="background-color:' + rgb.get_rgb_hex() + ';">' + str(c['id']) + '</th>' f.write(line + '</tr></thead>') # boody f.write('<tbody>') for c1 in colors: rgb = sRGBColor(c1['rgb'][0], c1['rgb'][1], c1['rgb'][2], True) line = '<tr><th style="background-color:' + rgb.get_rgb_hex() + ';">' + str(c1['id']) + '</th>' lab1 = LabColor(c1['lab'][0], c1['lab'][1], c1['lab'][2]) for c2 in colors: if c1['id'] == c2['id']: line += '<td>--</td>' else: lab2 = LabColor(c2['lab'][0], c2['lab'][1], c2['lab'][2]) line += '<td>' + str(round(delta_e_cie2000(lab1, lab2), 2)) + '</td>' f.write(line + '</td>') f.write('</tbody>') f.write('</table>') f.close()
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 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 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 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
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
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)
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
def calculate_color_distance(color1, color2): color1_rgb = sRGBColor(color1[0], color1[1], color1[2]) color2_rgb = sRGBColor(color2[0], color2[1], color2[2]) # Convert from RGB to Lab Color Space color1_lab = convert_color(color1_rgb, LabColor) # 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) return delta_e
def color_match(rgb_dress,rgb_color): color1_rgb = sRGBColor(rgb_dress[0], rgb_dress[1], rgb_dress[2]); color2_rgb = sRGBColor(rgb_color[0], rgb_color[1], rgb_color[2]); color1_lab = convert_color(color1_rgb, LabColor); color2_lab = convert_color(color2_rgb, LabColor); delta_e = delta_e_cie2000(color1_lab, color2_lab); print ("The difference between the 2 color = ", delta_e) return delta_e
def ColorDistance(rgb1, rgb2): #print("ColorDistance of " + str(rgb1) + " and " + str(rgb2)) color1_rgb = sRGBColor(rgb1[0], rgb1[1], rgb1[2]) color1_lab = convert_color(color1_rgb, LabColor) # Convert from RGB to Lab Color Space color2_rgb = sRGBColor(rgb2[0], rgb2[1], rgb2[2]) color2_lab = convert_color(color2_rgb, LabColor) # Find the color difference delta_e = delta_e_cie2000(color1_lab, color2_lab) #print("ColorDistance of " + str(color1_rgb) + " and " + str(color2_lab) + " = " + str(delta_e)) return delta_e
def calculate_colour_distance(c1: Color, c2: Color) -> float: """Users Delta E Cie 2000 to calculate colour distance Args: c1 (Color): First Colour c2 (Color): Second Colour Returns: float: Float distance between the two colours, 0 being the same colour, 100 being the furthest away, rounded to 3 decimal places """ c1_lab = convert_color(sRGBColor(*c1.rgb), LabColor) c2_lab = convert_color(sRGBColor(*c2.rgb), LabColor) return round(delta_e_cie2000(c1_lab, c2_lab), 3)
def fmtHex(str): black = convert_color(sRGBColor(0, 0, 0), LabColor) white = convert_color(sRGBColor(1, 1, 1), LabColor) color = sRGBColor.new_from_rgb_hex(str) lcolor = convert_color(color, LabColor) if delta_e_cie2000(lcolor, white) > delta_e_cie2000(lcolor, black): return "\033[48;2;{};{};{};38;2;255;255;255m{}\033[0m".format( int(255 * color.rgb_r), int(255 * color.rgb_g), int(255 * color.rgb_b), color.get_rgb_hex()) else: return "\033[48;2;{};{};{};38;2;0;0;0m{}\033[0m".format( int(255 * color.rgb_r), int(255 * color.rgb_g), int(255 * color.rgb_b), color.get_rgb_hex())
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
def get_delta_e(rgba, rgbb): color1_rgb = sRGBColor(rgba[0], rgba[1], rgba[2]) color2_rgb = sRGBColor(rgbb[0], rgbb[1], rgbb[2]) # Convert from RGB to Lab Color Space color1_lab = convert_color(color1_rgb, LabColor) # 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) return delta_e
def get_cie2000_difference(color_arr): color1 = color_arr[0] color2 = color_arr[1] # Normalize RGB values color1_rgb = sRGBColor(color1[0], color1[1], color1[2], is_upscaled=True) color2_rgb = sRGBColor(color2[0], color2[1], color2[2], is_upscaled=True) # Convert from RGB to Lab Color Space color1_lab = convert_color(color1_rgb, LabColor) color2_lab = convert_color(color2_rgb, LabColor) #Find the difference diff = delta_e_cie2000(color1_lab, color2_lab) return diff
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
def too_revealing(image, gender="M"): image = Image.open(image) w, h = image.size # image = image.crop((w / 4, h / 5, w * 3 / 4, h * 4 / 5)) # w, h = image.size pixelSize = (w * h) / 10000 image = image.resize( (round(image.size[0] / pixelSize), round(image.size[1] / pixelSize)), Image.NEAREST) w, h = image.size image.save("output.png") all_colours = list(image.getdata()) # Convert from RGB to Lab Color Space white_skin = [ convert_color(sRGBColor(255, 224, 189), LabColor), convert_color(sRGBColor(255, 205, 148), LabColor), convert_color(sRGBColor(239, 175, 139), LabColor), convert_color(sRGBColor(142, 81, 62), LabColor), convert_color(sRGBColor(126, 76, 62), LabColor), convert_color(sRGBColor(174, 127, 109), LabColor), convert_color(sRGBColor(60, 27, 12), LabColor) ] total_skin = 0 for colour in all_colours: # Convert from RGB to Lab Color Space color2_lab = convert_color(sRGBColor(colour[0], colour[1], colour[2]), LabColor) min_dist = 200 # Find the color difference for tone in white_skin: min_dist = min(delta_e_cie2000(tone, color2_lab), min_dist) # print(min_dist) if min_dist < 30: total_skin += 1 total_skin = total_skin / (w * h) # debug print(total_skin) # male if total_skin > .12 and gender == "M": return True # female if total_skin > .20 and gender != "M": return True return False
def convertPostMsg(self, postmsg): msgToDevice = {} datacontainsRGB = False if 'color' in postmsg.keys(): datacontainsRGB = True for k, v in postmsg.items(): if k == 'status': if postmsg.get('status') == "ON": msgToDevice['on'] = True elif postmsg.get('status') == "OFF": msgToDevice['on'] = False elif k == 'brightness': msgToDevice['bri'] = int( round(float(postmsg.get('brightness')) * 255.0 / 100.0, 0)) elif k == 'color': print(type(postmsg['color'])) if type(postmsg['color']) == tuple: _red, _green, _blue = postmsg['color'] # colors rgb = sRGBColor(_red, _green, _blue, True) # True for Digital 8-bit per channel _xyY = convert_color(rgb, xyYColor, target_illuminant='d50') msgToDevice['xy'] = [_xyY.xyy_x, _xyY.xyy_y] msgToDevice['bri'] = int(_xyY.xyy_Y * 255) elif type(postmsg['color']) == list: _red = postmsg['color'][0] _green = postmsg['color'][1] _blue = postmsg['color'][2] rgb = sRGBColor(_red, _green, _blue, True) # True for Digital 8-bit per channel _xyY = convert_color(rgb, xyYColor, target_illuminant='d50') msgToDevice['xy'] = [_xyY.xyy_x, _xyY.xyy_y] msgToDevice['bri'] = int(round(_xyY.xyy_Y * 255, 0)) elif k == 'hue': if datacontainsRGB == False: msgToDevice['hue'] = postmsg.get('hue') # msgToDevice['hue'] = 50000 elif k == 'saturation': if datacontainsRGB == False: msgToDevice['sat'] = int( round( float(postmsg.get('saturation')) * 255.0 / 100.0, 0)) else: msgToDevice[k] = v return msgToDevice
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)
def color_distance(rgb1, rgb2): c = tuple(rgb1)+tuple(rgb2) if c in color_map: return color_map[c] else: color1_rgb = sRGBColor(rgb1[0], rgb1[1], rgb1[2]); color1_lab = convert_color(color1_rgb, LabColor); color2_rgb = sRGBColor(rgb2[0], rgb2[1], rgb2[2]); color2_lab = convert_color(color2_rgb, LabColor); d = delta_e_cie2000(color1_lab, color2_lab) color_map[c] = d return d
def distance_DELTAECIE2000(p1, p2): """Restituisce un valore indicante la differenza tra 2 pixel in formato RGB. La differenza viene calcolata con l'algoritmi DELTA E CIE2000.""" # converto i colori in formato LAB p1 = convert_color( sRGBColor(p1.item(0) / 255.0, p1.item(1) / 255.0, p1.item(2) / 255.0), LabColor) p2 = convert_color( sRGBColor(p2.item(0) / 255.0, p2.item(1) / 255.0, p2.item(2) / 255.0), LabColor) # e calcolo la differenza return delta_e_cie2000(p1, p2)
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))
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 compare_color(img1, img2): a = get_color(img1) b = get_color(img2) a1 = sRGBColor(a[0], a[1], a[2]) b1 = sRGBColor(b[0], b[1], b[2]) color1 = convert_color(a1, LabColor) color2 = convert_color(b1, LabColor) delta_e = delta_e_cie2000(color1, color2) print("delta_e:", delta_e) if delta_e < delta_e_param: return True else: return False
def chromakey(source, bg): for x in range(source.width): for y in range(source.height): cur_pixel = source.getpixel((x, y)) green = sRGBColor(0, 190, 60) cur_pixel_rgb = sRGBColor(cur_pixel[0], cur_pixel[1], cur_pixel[2]) cur_pixel_lab = convert_color(cur_pixel_rgb, LabColor) green_lab = convert_color(green, LabColor) if delta_e_cie2000(cur_pixel_lab, green_lab) < 10: source.putpixel((x, y), bg.getpixel((x, y))) source.save("chromakeyed.png")
def preview(hex, end='\n'): black = convert_color(sRGBColor(0, 0, 0), LabColor) white = convert_color(sRGBColor(1, 1, 1), LabColor) color = convert_color(hex, sRGBColor) lcolor = convert_color(color, LabColor) if delta_e_cie2000(lcolor, white) > delta_e_cie2000(lcolor, black): print("\033[48;2;{};{};{};38;2;255;255;255m{}\033[0m".format( int(255 * color.rgb_r), int(255 * color.rgb_g), int(255 * color.rgb_b), color.get_rgb_hex()), end=end) else: print("\033[48;2;{};{};{};38;2;0;0;0m{}\033[0m".format( int(255 * color.rgb_r), int(255 * color.rgb_g), int(255 * color.rgb_b), color.get_rgb_hex()), end=end)
def validate_lighting(predicted, current, threshold): c1_rgb = colorsys.hsv_to_rgb(current['h'] / 360, current['s'], current['b']) c1 = sRGBColor(c1_rgb[0], c1_rgb[1], c1_rgb[2]) c2 = sRGBColor(predicted['r'] / 255.0, predicted['g'] / 255.0, predicted['b'] / 255.0) print("c1 is " + str(c1) + " and c2 is " + str(c2)) de = delta_e_cie2000(convert_color(c1, LabColor), convert_color(c2, LabColor)) LOG.info("delta_e: {} is within valid range: {}".format( de, de < threshold)) return de < threshold
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])
def color_difference(coll1, coll2): # First color col1 = hex2color(coll1) color1_rgb = sRGBColor(col1[0], col1[1], col1[2]) # Second color col2 = hex2color(coll2) color2_rgb = sRGBColor(col2[0], col2[1], col2[2]) # Convert from RGB to Lab Color Space color1_lab = convert_color(color1_rgb, LabColor) # 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 "The difference between the 2 color = ", delta_e return delta_e
def find_closest_color(color, colors_to_check): # create Color object from site color and convert to lab color for comparison r, g, b = (x / 255.0 for x in color) site_color_lab = convert_color(sRGBColor(r, g, b), LabColor) last_delta_e = 999 match_color = None for c, val in colors_to_check.items(): r, g, b = (x / 255.0 for x in val) check_color_lab = convert_color(sRGBColor( r, g, b), LabColor) # convert to lab color for comparison delta_e = delta_e_cie2000(site_color_lab, check_color_lab) if delta_e < last_delta_e: # use this check to find the closest match match_color = c last_delta_e = delta_e return match_color, last_delta_e
def color_similarity(cl1, cl2): cl1 = np.array(cl1) cl2 = np.array(cl2) cl1 = cl1 / 255. cl2 = cl2 / 255. color1 = sRGBColor(cl1[0], cl1[1], cl1[2]) color2 = sRGBColor(cl2[0], cl2[1], cl2[2]) # Convert from RGB to Lab Color Space color1_lab = convert_color(color1, LabColor) # Convert from RGB to Lab Color Space color2_lab = convert_color(color2, LabColor) # Find the color difference return delta_e_cie2000(color1_lab, color2_lab)
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)
def color_func(x, y, main_colors): #convert colors the Lab Color, x rectangle, y color c1 = (convert_color(sRGBColor(x.r / 255.0, x.g / 255.0, x.b / 255.0), LabColor)) c2 = (convert_color(sRGBColor(y.r / 255.0, y.g / 255.0, y.b / 255.0), LabColor)) #find the main color category of the rectangle color_cat = y.category rect_cat = find_color_cat(x, main_colors) diff = (abs(delta_e_cie2000(c1, c2))) if(color_cat.name != rect_cat.name): #based on the different color categories, set different rules for each color # # increase difference if color categories are blue and purple or gold and limegreen if((color_cat.name == "purple" and rect_cat.name == "blue") or (color_cat.name == "blue" and rect_cat.name == "purple")): diff *= 100 if((color_cat.name == "gold" and rect_cat.name == "limegreen") or (color_cat.name == "limegreen" and rect_cat.name == "gold")): diff = 1000 #these colors should never be grouped together if((color_cat.name == "gold" and rect_cat.name == "blue") or (color_cat.name == "blue" and rect_cat.name == "gold")): diff = 1000 if((color_cat.name == "purple" and rect_cat.name == "brown") or (color_cat.name == "brown" and rect_cat.name == "purple")): diff = 1000 if((color_cat.name == "green" and rect_cat.name == "red") or (color_cat.name == "red" and rect_cat.name == "green")): diff = 1000 if((color_cat.name == "green" and rect_cat.name == "brown") or (color_cat.name == "brown" and rect_cat.name == "green")): diff *= 80 #decrease the difference if one category is hotpink and the other is purple if((color_cat.name == "purple" and rect_cat.name == "hotpink") or (color_cat.name == "hotpink" and rect_cat.name == "purple")): diff = diff/15 #decrease the difference if the two colors are in the same color category or share a border color if(y.border_col[0] == rect_cat.name or y.border_col[1] == rect_cat.name): if(color_cat.name == rect_cat.name): diff = diff/40 else: diff = (diff)/(40) return diff
def tint_key(self, key_img): #a image of the key, and a hex color code string alpha = key_img.split()[3] key_img = ImageCms.applyTransform(key_img, rgb2lab_transform) l, a, b = key_img.split() rgb_color = sRGBColor(*ImageColor.getrgb(self.color), is_upscaled=True) lab_color = convert_color(rgb_color, LabColor) l1, a1, b1 = lab_color.get_value_tuple() l1 = int(l1 * 256 / 100) a1 = int( a1 + 128 ) #a1 should be scaled by 128/100, but desaturation looks more natural b1 = int(b1 + 128) l = ImageMath.eval('l + l1 - l2', l=l, l2=self.base_color, l1=l1).convert('L') a = ImageMath.eval('a - a + a1', a=a, a1=a1).convert('L') b = ImageMath.eval('b - b + b1', b=b, b1=b1).convert('L') key_img = Image.merge('LAB', (l, a, b)) key_img = ImageCms.applyTransform(key_img, lab2rgb_transform) elements = key_img.split() temp = (elements[0], elements[1], elements[2], alpha) key_img = Image.merge('RGBA', temp) return key_img
def hex_colors(start, amount, saturation, luminosity): k = 360/amount ans = ((luminosity, saturation, start + i*k) for i in range(amount)) ans = (cspace_convert(color, cie_string, "sRGB1") for color in ans) ans = (color.tolist() for color in ans) ans = (sRGBColor(*color) for color in ans) return to_hex_rgb(ans)
def randomize(rgb, labDistance): rgbColor = sRGBColor(rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0) randomDistance = random.random() * (labDistance * 2) - labDistance labColor = convert_color(rgbColor, LabColor) labColor2 = copy.deepcopy(labColor) signum = (random.choice([-1.0, 1.0]), random.choice([-1.0, 1.0]), random.choice([-1.0, 1.0])) while (delta_e_cie2000(labColor, labColor2) < randomDistance): current = random.randint(0, 2) if current == 0: labColor2.lab_l = labColor2.lab_l + signum[ current] * labColor2.lab_l / 100.0 * 5.0 elif current == 2: labColor2.lab_a = labColor2.lab_a + signum[ current] * labColor2.lab_a / 100.0 * 5.0 elif current == 2: labColor2.lab_b = labColor2.lab_b + signum[ current] * labColor2.lab_b / 100.0 * 5.0 rgbModified = convert_color(labColor2, sRGBColor) return tuple( map(int, [ rgbModified.rgb_r * 255, rgbModified.rgb_g * 255, rgbModified.rgb_b * 255 ]))
def optimize_colormap(name): # optimize lightness to the desired value import matplotlib.cm as cm from matplotlib.colors import LinearSegmentedColormap from colormath.color_objects import LabColor, sRGBColor from colormath.color_conversions import convert_color cmap = cm.get_cmap(name) values = cmap(np.linspace(0, 1, 256))[:, :3] lab_colors = [] for rgb in values: lab_colors.append(convert_color(sRGBColor(*rgb), target_cs=LabColor)) target_lightness = np.ones(256) * np.mean([_i.lab_l for _i in lab_colors]) for color, lightness in zip(lab_colors, target_lightness): color.lab_l = lightness # Go back to rbg. rgb_colors = [convert_color(_i, target_cs=sRGBColor) for _i in lab_colors] # Clamp values as colorspace of LAB is larger then sRGB. rgb_colors = [(_i.clamped_rgb_r, _i.clamped_rgb_g, _i.clamped_rgb_b) for _i in rgb_colors] cmap = LinearSegmentedColormap.from_list(name=name + "_optimized", colors=rgb_colors) return cmap
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
def cluster_multiple_images(images, k_clusters=10): ''' Clusters an image into k cluster points. Then, converts each color point from RGB to LAB color format. Args: images: An array of open PIL image k_clusters: Number of clusters to produce. Defaulted to 10. Returns: cluster_list: A list containing elements in the following format: [(name), (array of colors)] Replaced vq with sklearn ''' fullarr = scipy.misc.fromimage(images[0]) shape = fullarr.shape fullarr = fullarr.reshape(scipy.product(shape[:2]), shape[2]) # print('fullarr', fullarr.shape) for im in images[1:]: arr = scipy.misc.fromimage(im) shape = arr.shape if len(shape) > 2: arr = arr.reshape(scipy.product(shape[:2]), shape[2]) # print(arr.shape) fullarr = numpy.concatenate((fullarr, arr), axis=0) # print('fullarr',fullarr.shape) else: print('Invalid image') rgblist = [sRGBColor(z[0] / 255, z[1] / 255, z[2] / 255) for z in fullarr] lablist = [convert_color(x, LabColor) for x in rgblist] lablist = numpy.array([[x.lab_l, x.lab_a, x.lab_b] for x in lablist]) k_means_ex = KMeans(n_clusters=k_clusters) x = k_means_ex.fit_predict(lablist) codes = k_means_ex.cluster_centers_ labels = k_means_ex.labels_ return codes, labels
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
def open_base_img(full_profile, res, base_color, color): # get base image according to profile and perceptual gray of key color base_num = str([0xE0, 0xB0, 0x80, 0x50, 0x20].index(base_color) + 1) # open image and convert to Lab with Image.open('images/{0}_{1}{2}.png'.format(*full_profile, base_num)) as img: key_img = img.resize((int(s * res / 200) for s in img.size), resample=Image.BILINEAR).convert('RGBA') if full_profile[1] in ('ISO', 'BIGENTER'): alpha = key_img.split()[-1] l, a, b = ImageCms.applyTransform(key_img, rgb2lab_transform).split() # convert key color to Lab # a and b should be scaled by 128/100, but desaturation looks more natural rgb_color = color_objects.sRGBColor(*ImageColor.getrgb(color), is_upscaled=True) lab_color = color_conversions.convert_color(rgb_color, color_objects.LabColor) l1, a1, b1 = lab_color.get_value_tuple() l1, a1, b1 = int(l1 * 256 / 100), int(a1 + 128), int(b1 + 128) # change Lab of base image to match that of key color l = ImageMath.eval('convert(l + l1 - l_avg, "L")', l=l, l1=l1, l_avg=base_color) a = ImageMath.eval('convert(a + a1 - a, "L")', a=a, a1=a1) b = ImageMath.eval('convert(b + b1 - b, "L")', b=b, b1=b1) key_img = ImageCms.applyTransform(Image.merge('LAB', (l, a, b)), lab2rgb_transform).convert('RGBA') if full_profile[1] in ('ISO', 'BIGENTER'): key_img.putalpha(alpha) return key_img
def cluster_image(image, k_clusters=5): ''' Clusters an image into k cluster points. Then, converts each color point from RGB to LAB color format. Args: image: An open PIL image k_clusters: Number of clusters to produce. Defaulted to 10. Returns: cluster_list: A list containing elements in the following format: [(name), (array of colors)] Replaced vq with sklearn ''' arr = scipy.misc.fromimage(image) shape = arr.shape if len(shape) > 2: arr = arr.reshape(scipy.product(shape[:2]), shape[2]) rgblist = [sRGBColor(z[0] / 255, z[1] / 255, z[2] / 255) for z in arr] lablist = [convert_color(x, LabColor) for x in rgblist] lablist = numpy.array([[x.lab_l, x.lab_a, x.lab_b] for x in lablist]) # codes, dist = scipy.cluster.vq.kmeans2(lablist, k_clusters, iter=20) # print('LEN clusters', len(codes)) return cluster_array(k_clusters, lablist) else: print('Invalid image') return [], []
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
def srgbc(rgbv): # New Color object with Standard RGB format rgbv = rgbv.replace('#', '') return sRGBColor(float(int(rgbv[0:2], 16)), float(int(rgbv[2:4], 16)), float(int(rgbv[4:6], 16)), is_upscaled=True)
def ipt_jch(start, amount, saturation, luminosity): # Generate colors k = 360/amount colors = [(luminosity, saturation, start + i*k) for i in range(amount)] # From lch to IPT ans = ((l/100, c/100*cos(radians(h)), c/100*sin(radians(h))) for l, c, h in colors) # From IPT to XYZ1 ans = (convert_color(IPTColor(i, p, t), XYZColor, target_illuminant="d65") for i, p, t in ans) ipt_colors = (color.get_value_tuple() for color in ans) # From JCh to XYZ1 ans = (cspace_convert(color, "JCh", "XYZ1") for color in colors) jch_colors = (color.tolist() for color in ans) # Compute average ans = (((x1 + x2)/2, (y1 + y2)/2 , (z1 + z2)/2) for (x1, y1, z1), (x2, y2, z2) in zip(ipt_colors, jch_colors)) # From XYZ1 to sRGB1 ans = (cspace_convert(color, "XYZ1", "sRGB1") for color in ans) ans = ((color.tolist() for color in ans)) ans = (sRGBColor(*color) for color in ans) return to_hex_rgb(ans)
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)
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()
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 __init__(self, data = None, color1 = None, color2 = None): self.color1, self.color2 = color1, color2 if data is None or color1 == color2: self.__data = [0 for _ in xrange(0, 64)] return assert len(data) == 64 self.__data = [] lab1 = convert_color(sRGBColor(*color1[1], is_upscaled = True), LabColor) lab2 = convert_color(sRGBColor(*color2[1], is_upscaled = True), LabColor) for rgb in data: rgb = sRGBColor(*rgb, is_upscaled = True) lab = convert_color(rgb, LabColor) d1 = delta_e_cmc(lab, lab1, 1, 1) d2 = delta_e_cmc(lab, lab2, 1, 1) self.__data.append(d1 / (d1 + d2)) assert len(self.__data) == 64
def add_lab_field(): global colors for c in colors: rgb = sRGBColor(c['rgb'][0], c['rgb'][1], c['rgb'][2], True) #print(rgb) lab = convert_color(rgb, LabColor) #print(lab) c['lab'] = lab.get_value_tuple();
def getClosestColorNameByRGB(red, green, blue, colorDictionary): minDistance = sys.maxint closestColor = '' color = sRGBColor(red, green, blue) lab1 = convert_color(color, LabColor) for colorName in colorDictionary: dictionaryColor = sRGBColor(colorDictionary[colorName][0], colorDictionary[colorName][1], colorDictionary[colorName][2]) lab2 = convert_color(dictionaryColor, LabColor) distance = delta_e_cie2000(lab1, lab2) if distance < minDistance: minDistance = distance closestColor = colorName print minDistance return closestColor
def test_conversion_to_rgb_zero_div(self): """ The formula I grabbed for LCHuv to XYZ had a zero division error in it if the L coord was 0. Also check against LCHab in case. """ lchab = LCHabColor(0.0, 0.0, 0.0) rgb = convert_color(lchab, sRGBColor) self.assertColorMatch(rgb, sRGBColor(0.0, 0.0, 0.0))
def getColorsFromImg(infile, outfile="tmp.jpg", numcolors=8, swatchsize=20, resize=150): try: image = Image.open(infile) except: return [] image = image.resize((resize, resize)) result = image.convert('P', palette=Image.ADAPTIVE, colors=numcolors) result.putalpha(0) colors = result.getcolors(resize*resize) xyColorList = [] totalCount = 0 for c in colors: totalCount = totalCount + c[0] print "total count %d" % (totalCount) for c in colors: print c r = c[1][0] g = c[1][1] b = c[1][2] occPercent = (float(c[0])/float(totalCount))*100 if occPercent > 20: occPercent = 12 s = "R = %d G = %d B = %d occ = %d" % (r, g, b, occPercent) print s rgbColor = sRGBColor(r, g, b, is_upscaled=True) # print rgbColor xyzColor = convert_color(rgbColor, XYZColor) # print xyzColor totalXYZ = (xyzColor.get_value_tuple()[0] + xyzColor.get_value_tuple()[1] + xyzColor.get_value_tuple()[2]) if totalXYZ == 0: continue; x = xyzColor.get_value_tuple()[0] / totalXYZ y = xyzColor.get_value_tuple()[1] / totalXYZ xyColor_string="[%1.3f, %1.3f]" % (x, y) for i in range(0, int(occPercent)): xyColorList.append(xyColor_string) # pal = Image.new('RGB', (swatchsize*numcolors, swatchsize)) # draw = ImageDraw.Draw(pal) # posx = 0 # for count, col in colors: # draw.rectangle([posx, 0, posx+swatchsize, swatchsize], fill=col) # posx = posx + swatchsize # del draw # pal.save(outfile, "PNG") return xyColorList
def build_color_map(tile_dir): color_map = {} for filename in os.listdir(tile_dir): _file = tile_dir + '/' + filename primary = colorz(_file, n=1) for m in primary: c = sRGBColor(*m[0], is_upscaled=True) lab_c = convert_color(c, LabColor) color_map[_file] = lab_c return color_map
def refresh(self): full_data = self.request('GET', "http://www.cal-print.com/InkColorChart.htm") tds = full_data.find_all('td', attrs={"bgcolor": re.compile(r".*")}) raw_data = {} known_names = [] for td in tds: table = td.find_parent('table') name = table.find("font").text color = self.hex_to_rgb(td['bgcolor']) # remove excess whitespace name = re.sub(re.compile(r"\s+"), " ", name.strip()) if 'PMS' not in name and 'Pantone' not in name: name = 'Pantone ' + name raw_data[name] = color if not name.startswith('PMS'): known_names.append(name) # Add white raw_data['White'] = (255, 255, 255) known_names.append('White') # Find distance between colors and find better names for unnamed # colors in the table. data = {} for name, color in raw_data.items(): rgb = sRGBColor(*color) lab = convert_color(rgb, LabColor, target_illuminant='D65') min_diff = float("inf") min_name = "" for known_name in known_names: known_color = raw_data[known_name] known_rgb = sRGBColor(*known_color) known_lab = convert_color(known_rgb, LabColor, target_illuminant='D65') diff = delta_e_cie2000(lab, known_lab) if min_diff > diff: min_diff = diff min_name = known_name data['{0} ({1})'.format(name, min_name)] = color return data
def RgbToLab(rgb_color): """Returns a tuple of LabColor pairs for a given RGB color. The provided RGB color should either be a tuple (red, green, blue) or a hex string of 3 or 6 characters (with optional preceeding octothorpe) """ if isinstance(rgb_color, basestring): rgb_color = HexToRgb(rgb_color) rgb_color = color_objects.sRGBColor(*rgb_color) return convert_color(rgb_color, color_objects.LabColor).get_value_tuple()
def compare_colors(centroids): from colormath.color_objects import sRGBColor, LabColor from colormath.color_conversions import convert_color from colormath.color_diff import delta_e_cie2000 global n_colors colors = list() for i in range(len(centroids)): [r, g, b] = centroids[i] print int(r*255), int(g*255), int(b*255), convert_color(sRGBColor(r, g, b), LabColor) colors.append(convert_color(sRGBColor(r, g, b), LabColor)) for i in range(len(colors)): for j in range(len(colors)): deltaE = delta_e_cie2000(colors[i], colors[j]) output = '%.4f\t' % deltaE sys.stdout.write(output) sys.stdout.write('\n')