def _pixel_loop( self, img ): #todo: kill display on left and right corner gets detected as enemy, thats bad uhh rows, cols, waste = img.shape health = False enemys = [] ung = 20 for i in range(rows): for j in range(cols): if i > 30 and i < 145 and j > 20: if img[i, j][2] > 250 and img[i, j][0] > 250 and img[i, j][ 1] > 250: #bad check if text color above health bars try: #bad check if color under healthbar is like green #i+4 check -> wrong detection of the white circle! color_one = self._convert_color(img[i + 1, j]) color_two = self._convert_color(img[i + 2, j]) if not health and (delta_e_cie2000( color_one, self.colors['health'] ) < ung or delta_e_cie2000( color_two, self.colors['health']) < ung): #cv2.rectangle(clone, (j-25,i-25), (j + 25, i + 25), (0,255,0), 2)#draw bad rectangle around chars healthbar health = True elif not enemy and (delta_e_cie2000( color_one, self.colors['enemy'] ) < ung or delta_e_cie2000( color_two, self.colors['enemy']) < ung): #cv2.rectangle(clone, (j-25,i-25), (j + 25, i + 25), (0,0,255), 2)#draw bad rectangle around chars healthbar enemys.append((i, j)) except: pass return (health, enemys)
def proceed_color_diff_for_debug(RGB1, RGB2): RGB1, RGB2 = np.array(RGB1, np.uint8), np.array(RGB2, np.uint8) XYZ1, XYZ2 = RGB2XYZ(RGB1), RGB2XYZ(RGB2) XYZ1 = XYZ1.xyz_x, XYZ1.xyz_y, XYZ1.xyz_z XYZ2 = XYZ2.xyz_x, XYZ2.xyz_y, XYZ2.xyz_z LMS1, LMS2 = XYZ2LMS(XYZ1), XYZ2LMS(XYZ2) # C型の色差を求める処理 common_Lab1, common_Lab2 = XYZ2Lab(XYZ1), XYZ2Lab(XYZ2) common_color_diff = delta_e_cie2000(common_Lab1, common_Lab2) common_judge_JIS = judge_color_diff(common_color_diff) common_diff = {"result": common_color_diff, "JIS": common_judge_JIS} # P型の色差を求める処理 protan_LMS1, protan_LMS2 = LMS4protan(LMS1), LMS4protan(LMS2) protan_XYZ1, protan_XYZ2 = LMS2XYZ(protan_LMS1), LMS2XYZ(protan_LMS2) protan_Lab1, protan_Lab2 = XYZ2Lab(protan_XYZ1), XYZ2Lab(protan_XYZ2) protan_color_diff = delta_e_cie2000(protan_Lab1, protan_Lab2) protan_judge_JIS = judge_color_diff(protan_color_diff) protan_diff = {"result": protan_color_diff, "JIS": protan_judge_JIS} # D型の色差を求める処理 deutan_LMS1, deutan_LMS2 = LMS4deutan(LMS1), LMS4deutan(LMS2) deutan_XYZ1, deutan_XYZ2 = LMS2XYZ(deutan_LMS1), LMS2XYZ(deutan_LMS2) deutan_Lab1, deutan_Lab2 = XYZ2Lab(deutan_XYZ1), XYZ2Lab(deutan_XYZ2) deutan_color_diff = delta_e_cie2000(deutan_Lab1, deutan_Lab2) deutan_judge_JIS = judge_color_diff(deutan_color_diff) deutan_diff = {"result": deutan_color_diff, "JIS": deutan_judge_JIS} warning = judge_color_valid(common_judge_JIS, protan_judge_JIS, deutan_judge_JIS) return warning, common_diff, protan_diff, deutan_diff
def is_animating(self, img): # Given an image, check if it is animating by checking the colors of various card locations # Check Table for i in range(5): t = (self.table[0] + 60 * i, self.table[1], self.table[2] + 60 * i, self.table[3]) c = img.crop(box=t) img_o = c.load() deltacolorC = delta_e_cie2000( convert_color( sRGBColor( sum([img_o[x, 0][0] for x in range(18, 27)]) / 9 / 255, sum([img_o[x, 0][1] for x in range(18, 27)]) / 9 / 255, sum([img_o[x, 0][2] for x in range(18, 27)]) / 9 / 255), LabColor), convert_color(sRGBColor(1, 1, 1), LabColor)) deltacolorG = delta_e_cie2000( convert_color( sRGBColor( sum([img_o[x, 0][0] for x in range(18, 27)]) / 9 / 255, sum([img_o[x, 0][1] for x in range(18, 27)]) / 9 / 255, sum([img_o[x, 0][2] for x in range(18, 27)]) / 9 / 255), LabColor), convert_color(sRGBColor(68 / 255, 68 / 255, 68 / 255), LabColor)) if (not deltacolorC < 1 and not deltacolorG < 3.5): return True pl0 = self.players[0] img_o = img.crop(pl0[0]).load() deltacolorC = delta_e_cie2000( convert_color( sRGBColor( sum([img_o[x + 2, 2][0] for x in range(10, 19)]) / 9 / 255, sum([img_o[x + 2, 2][1] for x in range(10, 19)]) / 9 / 255, sum([img_o[x + 2, 2][2] for x in range(10, 19)]) / 9 / 255), LabColor), convert_color(sRGBColor(1, 1, 1), LabColor)) deltacolorG = delta_e_cie2000( convert_color( sRGBColor( sum([img_o[x + 2, 2][0] for x in range(10, 19)]) / 9 / 255, sum([img_o[x + 2, 2][1] for x in range(10, 19)]) / 9 / 255, sum([img_o[x + 2, 2][2] for x in range(10, 19)]) / 9 / 255), LabColor), convert_color(sRGBColor(68 / 255, 68 / 255, 68 / 255), LabColor)) deltacolorF = delta_e_cie2000( convert_color( sRGBColor( sum([img_o[x + 2, 2][0] for x in range(10, 19)]) / 9 / 255, sum([img_o[x + 2, 2][1] for x in range(10, 19)]) / 9 / 255, sum([img_o[x + 2, 2][2] for x in range(10, 19)]) / 9 / 255), LabColor), convert_color(sRGBColor(161 / 255, 161 / 255, 161 / 255), LabColor)) if (not deltacolorC < 1 and not deltacolorG < 1 and not deltacolorF < 1): return True return False
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 convertColorToTeam(unknown_color, team_A_color, team_B_color): unknown_color = sRGBColor(unknown_color[2] / 255, unknown_color[1] / 255, unknown_color[0] / 255) unknown_color = convert_color(unknown_color, LabColor) dist_A = delta_e_cie2000(unknown_color, team_A_color) dist_B = delta_e_cie2000(unknown_color, team_B_color) if dist_A < dist_B: return "A" else: return "B"
def colorSort(rgb): r, g, b = rgb.get_value_tuple() color0 = convert_color(rgb, LabColor) threshold = 0.085 isGray = abs(r - g) < threshold and abs(r - b) < threshold and abs( g - b) < threshold if isGray: color1 = convert_color(sRGBColor(0, 0, 0, False), LabColor) return (0, delta_e_cie2000(color0, color1)) color1 = convert_color(sRGBColor(1, 0, 0, False), LabColor) return (1, delta_e_cie2000(color0, color1))
def assignbins(lab_pixel_arr): print("assignbins") midpts = [] x = [-127, 0, 127] mid_pts = [p for p in itertools.product(x, repeat=3)] arr_bins = [] signature_list = [] for i in range(32): #print "a1____" for j in range(32): l_bin = [] for x in range(len(mid_pts)): a = [mid_pts[x], 0] l_bin.append(a) for k in range(8): ##print "a3____" for l in range(8): #print "a4____" temp_arr = lab_pixel_arr[i * 8 + k][j * 8 + l] score = 1000 min_bin = 1000 for m in range(len(l_bin)): if (score > delta_e_cie2000( temp_arr, LabColor(l_bin[m][0][0], l_bin[m][0][1], l_bin[m][0][2]))): score = delta_e_cie2000( temp_arr, LabColor(l_bin[m][0][0], l_bin[m][0][1], l_bin[m][0][2])) min_bin = m #print min_bin l_bin[min_bin][1] += 1 temp_pixel = [] for x in range(3): temp_pixel.append((l_bin[min_bin][0][x] + temp_arr.get_value_tuple()[x]) / 2) temp_pixel = tuple(temp_pixel) l_bin[min_bin][0] = temp_pixel #print "a____" arr_bins.append(l_bin) print("after assignbins") for i in arr_bins: for j in range(len(i)): signature_list.append(i[j][1]) return signature_list
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 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 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 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 fat_chin(pose, image): hdist = (pose.part(8).x - pose.part(7).x) vdist = (pose.part(8).y - pose.part(57).y) pose_max = min(pose.part(7).y, pose.part(9).y) min_x = round(pose.part(8).x - hdist / 3) max_x = round(pose.part(8).x + hdist / 3) min_y = round(pose_max - vdist / 3) max_y = round(pose_max) r, g, b = get_color(min_x, max_x, min_y, max_y, image, 3) if r == -1: return -1 pit_color = sRGBColor(r / 255, g / 255, b / 255) pit_color = convert_color(pit_color, LabColor) min_x = round(pose.part(8).x - hdist / 3) max_x = round(pose.part(8).x + hdist / 3) min_y = round(pose_max - vdist * (2 / 3)) max_y = round(pose_max - vdist * (1 / 3)) r, g, b = get_color(min_x, max_x, min_y, max_y, image, 3) chin_color = sRGBColor(r / 255, g / 255, b / 255) chin_color = convert_color(chin_color, LabColor) return clamp((delta_e_cie2000(pit_color, chin_color) - 7) * 5 + 50, 0, 100)
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(color1, color2): color1_rgb = sRGBColor(color1[0], color1[1], color1[2], True) color2_rgb = sRGBColor(color2[0], color2[1], color2[2], True) color1_lab = convert_color(color1_rgb, LabColor) color2_lab = convert_color(color2_rgb, LabColor) delta_e = delta_e_cie2000(color1_lab, color2_lab) return delta_e
def get_color_name(r, g, b): red = ("RED", 197, 17, 17) lime = ("LIME", 80, 239, 58) black = ("BLACK", 63, 71, 78) purple = ("PURPLE", 108, 46, 188) orange = ("ORANGE", 239, 124, 12) cyan = ("CYAN", 57, 255, 221) green = ("GREEN", 18, 127, 45) pink = ("PINK", 240, 84, 189) yellow = ("YELLOW", 244, 245, 84) blue = ("BLUE", 18, 44, 212) white = ("WHITE", 214, 222, 241) brown = ("BROWN", 113, 73, 30) color_list = [red] + [lime] + [black] + [purple] + [orange] + [cyan] + [ green ] + [pink] + [yellow] + [blue] + [white] + [brown] # print(color_list) best_match_color = "NONE" closest_dist = 99999 for color in color_list: color1_rgb = sRGBColor(r, g, b, True) color2_rgb = sRGBColor(color[1], color[2], color[3], True) color1_lab = convert_color(color1_rgb, LabColor) color2_lab = convert_color(color2_rgb, LabColor) delta_e = delta_e_cie2000(color1_lab, color2_lab) if delta_e < closest_dist: best_match_color = color[0] closest_dist = delta_e return best_match_color
def get_similar_colors(self, brand_color, k=2, level=2): """ this method is aim to find similar colors from YUNA color database to the given color -> 'brand_color' the input of brand_color can be tuple of rgb e.g. (0,5,0) or a Color Hex with/without '#' e.g. #FFF or FFFFFF """ pair_list = [] result_list = [] for index, yuna_color in df.loc[df['level'] == level].iterrows(): pair_dict = {} pair_dict['color'] = yuna_color['short_name'] if isinstance(brand_color, tuple): y_c = (yuna_color['r_color'], yuna_color['g_color'], yuna_color['b_color']) cs = delta_e_cie2000(self.rgb_to_lab(brand_color), self.rgb_to_lab(y_c)) else: if (not brand_color.startswith('#') and (len(brand_color) == 3 or len(brand_color) == 6)) or ( brand_color.startswith('#') and (len(brand_color) == 4 or len(brand_color) == 7)): cs = self.color_similarity(brand_color, yuna_color['hex_color']) else: return None pair_dict['similarity'] = cs pair_list.append(pair_dict) result = sorted(pair_list, key=lambda k: k['similarity'], reverse=False)[:k] for i in result: result_list.append(i['color']) return result_list
def sameColor(color1, color2): ''' @param color1: {String} rgb string such as "rgb(0,0,0)" @param color2: {String} rgb string such as "rgb(0,0,0)" @return: {Boolean} True if the two colors are the same; False otherwise ''' if color1 == "transparent" and color2 == "transparent": return True if color1 != "transparent" and color2 != "transparent": if "," in color1: rgb1 = re.split(r"\D+", color1)[1:-1] rgb1 = sRGBColor(int(rgb1[0]), int(rgb1[1]), int(rgb1[2]), is_upscaled=True) else: rgb1 = sRGBColor.new_from_rgb_hex(color1) if "," in color2: rgb2 = re.split(r"\D+", color2)[1:-1] rgb2 = sRGBColor(int(rgb2[0]), int(rgb2[1]), int(rgb2[2]), is_upscaled=True) else: rgb2 = sRGBColor.new_from_rgb_hex(color2) return delta_e_cie2000(convert_color(rgb1, LabColor), convert_color(rgb2, LabColor)) < 4.65 pass # if color1 != "transparent" and color2 != "ransparent" return False
def discrete_color(color_stroke, just_inds=False): #(n*5, 3) allowed_colors_tensors = [ torch.Tensor([allowed_colors[i]] * color_stroke.shape[0]).to(device) for i in range(len(allowed_colors)) ] l2_distances = torch.zeros( (color_stroke.shape[0], len(allowed_colors_tensors))) for i in range(len(allowed_colors_tensors)): l2_distances[:, i] = torch.sum( (color_stroke - allowed_colors_tensors[i])**2, dim=1) for j in range(l2_distances.shape[0]): color1_rgb = sRGBColor(color_stroke[j, 2], color_stroke[j, 1], color_stroke[j, 0]) color2_rgb = sRGBColor(allowed_colors[i][2], allowed_colors[i][1], allowed_colors[i][0]) color1_lab = convert_color(color1_rgb, LabColor) color2_lab = convert_color(color2_rgb, LabColor) l2_distances[j, i] = delta_e_cie2000(color1_lab, color2_lab) color_inds = torch.argmin(l2_distances, dim=1, keepdims=True).repeat( (1, 3)).to(device) if just_inds: return color_inds new_color_stroke = torch.zeros(color_stroke.shape).to(device) for i in range(len(allowed_colors_tensors)): new_color_stroke = torch.where(color_inds == i, allowed_colors_tensors[i], new_color_stroke) return new_color_stroke
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 color_func(x, y): 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)) diff = (abs(delta_e_cie2000(c1, c2))) return diff
def discrete_color(color_stroke, allowed_colors, just_inds=False): #(n*5, 3) ''' color_stroke in RGB allowed_colors in BGR ''' allowed_colors_tensors = [ np.array([allowed_colors[i]] * color_stroke.shape[0]) for i in range(len(allowed_colors)) ] l2_distances = np.zeros( (color_stroke.shape[0], len(allowed_colors_tensors))) for i in range(len(allowed_colors_tensors)): l2_distances[:, i] = np.sum( (color_stroke - allowed_colors_tensors[i])**2, axis=1) for j in range(l2_distances.shape[0]): color1_rgb = sRGBColor(color_stroke[j, 0], color_stroke[j, 1], color_stroke[j, 2]) color2_rgb = sRGBColor(allowed_colors[i][2], allowed_colors[i][1], allowed_colors[i][0]) color1_lab = convert_color(color1_rgb, LabColor) color2_lab = convert_color(color2_rgb, LabColor) l2_distances[j, i] = delta_e_cie2000(color1_lab, color2_lab) color_inds = np.tile(np.argmin(l2_distances, axis=1)[np.newaxis].T, (1, 3)) if just_inds: return color_inds new_color_stroke = np.zeros(color_stroke.shape) for i in range(len(allowed_colors_tensors)): new_color_stroke = np.where(color_inds == i, allowed_colors_tensors[i], new_color_stroke) return new_color_stroke
def closest_color(hx): if color_list.has_key(hx): return color_list[hx] distances = {} lab = hex_to_lab(hx) for key in color_list.keys(): distances[key] = delta_e_cie2000(lab, hex_to_lab(key)) return min(distances, key=distances.get)
def delta_e(self, other_color, mode='cie2000', *args, **kwargs): """ Compares this color to another via Delta E. Valid modes: cie2000 cie1976 """ if not isinstance(other_color, ColorBase): raise InvalidArgument('delta_e_cie2000', 'other_color', other_color) # Convert the colors to Lab if they are not already. lab1 = self.convert_to('lab', *args, **kwargs) lab2 = other_color.convert_to('lab', *args, **kwargs) mode = mode.lower() if mode == 'cie2000': return delta_e_cie2000(lab1, lab2) elif mode == 'cie1994': return delta_e_cie1994(lab1, lab2, **kwargs) elif mode == 'cie1976': return delta_e_cie1976(lab1, lab2) elif mode == 'cmc': return delta_e_cmc(lab1, lab2, **kwargs) else: raise InvalidDeltaEMode(mode)
def closest_color(self, r, g, b, a=255): if a == 0: # Transparent return None rgb = (r, g, b) cached = self._closest_cache.get(rgb, None) if cached is not None: # Already know the answer for this RGB value return cached else: # Compute cold and cache result rgb_color = sRGBColor(r, g, b, is_upscaled=True) lab = convert_color(rgb_color, LabColor) best_lab = None best_diff = 101 for palette_lab in self._by_lab_lookup: diff = delta_e_cie2000(lab, palette_lab) if diff < best_diff: best_diff = diff best_lab = palette_lab color = self._by_lab_lookup[best_lab] self._closest_cache[rgb] = color return color
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 getSimilarColors(rgb, rgbSwatch=None, swatches=[], maxDist=15, getSimilar=True, getOpposite=True): colorName = getColorName(rgb) color0 = convert_color(rgb, LabColor) categories = list(colorWheel.keys()) index = categories.index(colorName) similarCategories = [] oppositeCategories = [] newSwatches = [] if getSimilar: if index < 3: #white/black/gray similarCategories = [categories[0], categories[1], categories[2]] else: for i in range(index - 3, index + 4): if i < 3: similarCategories.append(categories[i - 3 + len(categories)]) elif i > len(categories) - 1: similarCategories.append(categories[(i % 3) + 3]) else: similarCategories.append(categories[i]) if getOpposite: if index < 3: #white/black/gray oppositeCategories = [] else: oppIndex = int((index + (len(categories) / 2)) if index < len(categories) / 2 else (index - (len(categories) / 2))) for i in range(oppIndex - 1, oppIndex + 2): if i < 3: oppositeCategories.append(categories[i - 3 + len(categories)]) elif i > len(categories) - 1: oppositeCategories.append(categories[(i % 3) + 3]) else: oppositeCategories.append(categories[i]) for swatch in swatches: dist = delta_e_cie2000(color0, convert_color(swatch.color, LabColor)) if rgbSwatch and dist == 0 and swatch.finish == rgbSwatch.finish and swatch.palette == rgbSwatch.palette: continue if dist < maxDist: newSwatches.append(swatch) continue if getSimilar or getOpposite: colorName = getColorName(swatch.color) if getSimilar: if colorName in similarCategories: newSwatches.append(swatch) continue if getOpposite: if colorName in oppositeCategories: newSwatches.append(swatch) continue return newSwatches
def color_diff(color1, color2): color1_rgb = sRGBColor(color1[0]/255, color1[1]/255, color1[2]/255) color2_rgb = sRGBColor(color2[0]/255, color2[1]/255, color2[2]/255) color1_lab = convert_color(color1_rgb, LabColor) color2_lab = convert_color(color2_rgb, LabColor) delta_e = delta_e_cie2000(color1_lab, color2_lab) return delta_e
def test_cie2000_accuracy(self): result = delta_e_cie2000(self.color1, self.color2) expected = 1.523 self.assertAlmostEqual( result, expected, 3, "DeltaE CIE2000 formula error. Got %.3f, expected %.3f (diff: %.3f)." % (result, expected, result - expected))
def color_distance_rgb(self, clr1_rgb, clr2_rgb): # Convert from RGB to Lab Color Space clr1_lab = convert_color(clr1_rgb, LabColor) clr2_lab = convert_color(clr2_rgb, LabColor) # Find the color difference delta_e = delta_e_cie2000(clr1_lab, clr2_lab) return delta_e
def colorDifference(color_rgb_1, color_rgb_2): rgb1 = sRGBColor(color_rgb_1[0], color_rgb_1[1], color_rgb_1[2]) rgb2 = sRGBColor(color_rgb_2[0], color_rgb_2[1], color_rgb_2[2]) color_lab_1 = convert_color(rgb1, LabColor) color_lab_2 = convert_color(rgb2, LabColor) d = delta_e_cie2000(color_lab_1, color_lab_2) return d
def delta_e(self, other_color, mode='cie2000', *args, **kwargs): """ Compares this color to another via Delta E. Valid modes: cie2000 cie1976 """ if not isinstance(other_color, ColorBase): raise InvalidArgument('delta_e_cie2000', 'other_color', other_color) # Convert the colors to Lab if they are not already. lab1 = self.convert_to('lab', *args, **kwargs) lab2 = other_color.convert_to('lab', *args, **kwargs) mode = mode.lower() if mode == 'cie2000': return color_diff.delta_e_cie2000(lab1, lab2) elif mode == 'cie1994': return color_diff.delta_e_cie1994(lab1, lab2, **kwargs) elif mode == 'cie1976': return color_diff.delta_e_cie1976(lab1, lab2) elif mode == 'cmc': return color_diff.delta_e_cmc(lab1, lab2, **kwargs) else: raise InvalidDeltaEMode(mode)
def color_diff(x, y): color1_rgb = sRGBColor(x[2], x[1], x[0], is_upscaled=True) color2_rgb = sRGBColor(y[0], y[1], y[2], is_upscaled=True) color1_lab = convert_color(color1_rgb, LabColor) color2_lab = convert_color(color2_rgb, LabColor) return delta_e_cie2000(color1_lab, color2_lab)
def color_distance(color1_rgb, color2_rgb): # 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 return delta_e_cie2000(color1_lab, color2_lab)
def colorDifferences(color1_RGB, color2_RGB): '''Goal: Compute the color difference between 2 RGB colors Input: Tuple - 2 RGB colors Output: Value - distance of colors ''' try: # Get colors color1_rgb = sRGBColor(color1_RGB[0],color1_RGB[1],color1_RGB[2]) color2_rgb = sRGBColor(color2_RGB[0],color2_RGB[1],color2_RGB[2]) # Convert from RGB to Lab Color Space color1_lab = convert_color(color1_rgb, LabColor) color2_lab = convert_color(color2_rgb, LabColor) # Compute the color difference delta_e = delta_e_cie2000(color1_lab, color2_lab) return delta_e except IndexError: print("IndexError: Tuples need 3 elements as it represent a RGB encoding") except TypeError: print("TypeError: Tuples needed as input") except ValueError: print("ValueError: Use only numerical values in tuples")
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 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 find_color(urgb, colors): cur_distance = 3 * (255 ** 2 + 1) cur_color = None for color, clab in colors: dist = delta_e_cie2000(ulab, clab) if dist < cur_distance: cur_distance = dist cur_color = (color, clab) return cur_color
def find_color(ulab, colors, ctrans): cur_distance = float('inf') cur_color = None i = 0 for clab in colors: dist = delta_e_cie2000(ulab, clab) if dist < cur_distance: cur_distance = dist cur_color = (ctrans(i), clab) i += 1 return cur_color
def measure_delta_e_similarity(tile_data, stock_data): tile_data_colors = convert_pixel_data_to_lab_colors(tile_data) stock_data_colors = convert_pixel_data_to_lab_colors(stock_data) differences = tuple(( delta_e_cie2000(td_color, sd_color) for td_color, sd_color in zip(tile_data_colors, stock_data_colors) )) measure = sum(differences) n_measure = normalize_measure(measure, DELTA_E_MAX_DIFFERENCE) return n_measure
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 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 color_map(color, standards, cformat='rgb'): if cformat == 'rgb': rgb = srgbc(color) lab = convert_color(rgb, LabColor, target_illuminant='d50') elif cformat == 'lab': lab = labc(color) mindis, minindex = 10000000, 0 for index in xrange(len(standards)): distance = delta_e_cie2000(lab, standards[index]) if distance < mindis: mindis = distance minindex = index + 1 return minindex
def test_cie2000_accuracy_2(self): """ Follow a different execution path based on variable values. """ # These values are from ticket 8 in regards to a CIE2000 bug. c1 = LabColor(lab_l=32.8911, lab_a=-53.0107, lab_b=-43.3182) c2 = LabColor(lab_l=77.1797, lab_a=25.5928, lab_b=17.9412) result = delta_e_cie2000(c1, c2) expected = 78.772 self.assertAlmostEqual(result, expected, 3, "DeltaE CIE2000 formula error. Got %.3f, expected %.3f (diff: %.3f)." % ( result, expected, result - expected))
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 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)
def get_color_distance(c1, c2, on_server): if (c1, c2) in dcache: return dcache[(c1, c2)] if (c2, c1) in dcache: return dcache[(c2, c1)] # delta_e_cie2000 is better but is 3x slower on an EV3...1976 is good enough if on_server: distance = delta_e_cie2000(c1, c2) else: distance = delta_e_cie1976(c1, c2) dcache[(c1, c2)] = distance return distance
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 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')
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 identify_colors(tile_dir, colors_to_match): matches = [] logging.info("Building color map...") color_map = build_color_map(tile_dir) logging.info("Comparing {} color map values...".format(len(color_map))) for c2 in colors_to_match: color = c2[0] num_points = c2[1] best_match = None best_match_value = 1000.0 for c1 in color_map: delta_e = delta_e_cie2000(color_map[c1], color) if delta_e < best_match_value: best_match_value = delta_e best_match = c1 match = Match(tile=best_match, color_obj=color_map[best_match], num_points=num_points, freq=None) matches.append(match) del color_map[best_match] return matches
def output_csv(): f = open('delta-e-cie2000.csv', 'w') # header line = ',' for c in colors: line += str(c['id']) + ',' f.write(line + "\n") # body for c1 in colors: line = str(c1['id']) + ',' lab1 = LabColor(c1['lab'][0], c1['lab'][1], c1['lab'][2]) for c2 in colors: if c1['id'] == c2['id']: line += '0,' else: lab2 = LabColor(c2['lab'][0], c2['lab'][1], c2['lab'][2]) line += str(delta_e_cie2000(lab1, lab2)) + ',' f.write(line + "\n") f.close()
def colormatch(color): """ Converts the image-color of a pixel to an ANSI color. """ # need to cast to Lab Colorspace to do color distance computation rgb = sRGBColor(color[0]/255.0,color[1]/255.0,color[2]/255.0) labcol = convert_color(rgb, LabColor) # colors, ansicodes: black, red, green, yellow, blue, magenta, cyan, gray colors = [(0,0,0),(205,0,0),(0,205,0),(205,205,0),(0,0,238),(205,0,205), (0,205,205),(229,229,229)] colorlist = [sRGBColor(y[0]/255.0,y[1]/255.0,y[2]/255.0) for y in colors] labclist = [convert_color(x, LabColor) for x in colorlist] ansicodes = ["\x1b[3" + str(n) + "m" for n in range(8)] minimum = 1000 potentialcolor = 0 for i in range(len(colorlist)): distance = delta_e_cie2000(labclist[i],labcol) if distance < minimum: minimum = distance potentialcolor = i return ansicodes[potentialcolor]
def generate_color_name_list(matches, colorfile=COLORFILE): # Sort them by frequency (highest to lowest) so we allocate the "best" names to the # most-represented colors matches.sort(key = lambda x: x.freq) matches.reverse() color_names = named_colorset(colorfile) for match in matches: color = match.color_obj best_match = None best_match_value = 1000.0 for c2 in color_names: delta_e = delta_e_cie2000(c2['obj'], color) if delta_e < best_match_value: best_match_value = delta_e best_match = c2 logging.info("Think {} is the best name for {}".format(best_match['color'], match.tile)) match.color_name = best_match['color'] color_names.remove(best_match) return matches
def rgb_error(self): return delta_e_cie2000(convert_color(self.m_lch, LabColor), convert_color(sRGBColor.new_from_rgb_hex(self.rgb()), LabColor))
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 not IDs: IDs = range(nlabels) if not names: names = [str(x) for x in range(nlabels)] if not groups: 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
def home(): form =ColorSearchForm(request.form) # Handle search if request.method == 'POST': if form.validate_on_submit(): return redirect(url_for("public.home") + '?color={0}'.format(form.color.data.replace('#', ''))) else: flash_errors(form) color_results = Color.query max_colors = app.config['MAX_COLORS'] color = None colors = None colors_cie2000 = None colors_cie1976 = None colors_cie1994 = None colors_cmc = None colors_cie1976_elapsed = None colors_cie2000_elapsed = None colors_cie1976_db = None colors_cie2000_db = None colors_cie1976_db_elapsed = None colors_cie2000_db_elapsed = None is_show_createschema_msg = False is_show_createcolors_msg = False if not db.engine.dialect.has_table(db.engine.connect(), 'color'): form = None is_show_createschema_msg = True elif (not request.args.get('color', None)) and (not color_results.count()): form = None is_show_createcolors_msg = True elif request.args.get('color', None): color = '#{0}'.format(request.args.get('color')) from operator import itemgetter from colormath.color_conversions import convert_color from colormath.color_objects import sRGBColor, LabColor from colormath.color_diff import (delta_e_cie2000, delta_e_cie1976, delta_e_cie1994, delta_e_cmc) from colorsearchtest.queries import (delta_e_cie1976_query, delta_e_cie2000_query) c_rgb = sRGBColor.new_from_rgb_hex(color) c_lab = convert_color(c_rgb, LabColor) if app.config['IS_DELTA_E_COLORMATH_ENABLED']: start_time = timeit.default_timer() colors_cie2000_tmp = [] for c in color_results.all(): c2_lab = LabColor(lab_l=c.lab_l, lab_a=c.lab_a, lab_b=c.lab_b, illuminant='d65') colors_cie2000_tmp.append({ 'hex': str(c), 'fore_color': ('#{:02X}{:02X}{:02X}'.format(*calc_fore_color((c.rgb_r, c.rgb_g, c.rgb_b)))), 'delta_e_cie2000': delta_e_cie2000(c_lab, c2_lab)}) colors_cie2000 = sorted(colors_cie2000_tmp, key=itemgetter('delta_e_cie2000'))[:max_colors] colors_cie2000_elapsed = timeit.default_timer() - start_time start_time = timeit.default_timer() colors_cie1976_tmp = [] for c in color_results.all(): c2_lab = LabColor(lab_l=c.lab_l, lab_a=c.lab_a, lab_b=c.lab_b, illuminant='d65') colors_cie1976_tmp.append({ 'hex': str(c), 'fore_color': ('#{:02X}{:02X}{:02X}'.format(*calc_fore_color((c.rgb_r, c.rgb_g, c.rgb_b)))), 'delta_e_cie1976': delta_e_cie1976(c_lab, c2_lab)}) colors_cie1976 = sorted(colors_cie1976_tmp, key=itemgetter('delta_e_cie1976'))[:max_colors] colors_cie1976_elapsed = timeit.default_timer() - start_time colors = None if app.config['IS_DELTA_E_DBQUERY_ENABLED']: start_time = timeit.default_timer() color_results = delta_e_cie1976_query( lab_l=c_lab.lab_l, lab_a=c_lab.lab_a, lab_b=c_lab.lab_b, limit=max_colors) colors_cie1976_db = [] for c in color_results: colors_cie1976_db.append({ 'hex': '#{:02X}{:02X}{:02X}'.format(c[0], c[1], c[2]), 'fore_color': ('#{:02X}{:02X}{:02X}'.format(*calc_fore_color((c[0], c[1], c[2])))), 'delta_e_cie1976_db': c[3]}) colors_cie1976_db_elapsed = timeit.default_timer() - start_time start_time = timeit.default_timer() color_results = delta_e_cie2000_query( lab_l=c_lab.lab_l, lab_a=c_lab.lab_a, lab_b=c_lab.lab_b, limit=max_colors) colors_cie2000_db = [] for c in color_results: colors_cie2000_db.append({ 'hex': '#{:02X}{:02X}{:02X}'.format(c[0], c[1], c[2]), 'fore_color': ('#{:02X}{:02X}{:02X}'.format(*calc_fore_color((c[0], c[1], c[2])))), 'delta_e_cie2000_db': c[3]}) colors_cie2000_db_elapsed = timeit.default_timer() - start_time else: colors = [{ 'hex': str(c), 'fore_color': ('#{:02X}{:02X}{:02X}'.format(*calc_fore_color((c.rgb_r, c.rgb_g, c.rgb_b)))), 'delta_e_cie2000': None} for c in color_results .order_by(func.random()) .limit(max_colors) .all()] return render_template("public/home.html", form=form, is_show_createschema_msg=is_show_createschema_msg, is_show_createcolors_msg=is_show_createcolors_msg, colors=colors, colors_cie2000=colors_cie2000, colors_cie1976=colors_cie1976, colors_cie1994=colors_cie1994, colors_cmc=colors_cmc, colors_cie1976_elapsed=colors_cie1976_elapsed, colors_cie2000_elapsed=colors_cie2000_elapsed, colors_cie1976_db=colors_cie1976_db, colors_cie2000_db=colors_cie2000_db, colors_cie1976_db_elapsed=colors_cie1976_db_elapsed, colors_cie2000_db_elapsed=colors_cie2000_db_elapsed, color=color)
def PaletteGenerator( maxNrColors = None, L_min = 50, L_max = 95, a_min = -60, a_max = 80, b_min=-60, b_max=80, L_base=11, a_base=2, b_base=3, L_index = 0, a_index = 0, b_index = 0, minDistance=0, # color distance must be greater than this maxFails=1000, gradient=False): """Generate a color palette using Halton sequences in CIE L*a*b* space.""" # traverse L*a*b* color space using a low-discrepancy sequence (Halton sequence) for each dimension, and reject a color if it is outside the RGB gamut allhex=[] alllab = [] nrFails = 0 HL = HaltonSequence(L_base, L_index) # the first argument controls the number of lighness steps Ha = HaltonSequence(a_base, a_index) Hb = HaltonSequence(b_base, b_index) if gradient: z = HL.next() while True: x = Ha.next() y = Hb.next() if not gradient: z = HL.next() L= z*(L_max-L_min)+L_min a = x*(a_max-a_min)+a_min b = y*(b_max-b_min)+b_min labcolor = LabColor(L, a, b) rgbcolor = convert_color(labcolor, sRGBColor) rgbhex = rgbcolor.get_rgb_hex() valid=True # check if within gamut for v in rgbcolor.get_upscaled_value_tuple(): if v <=0 or v>=255: # colormath keeps values out of gamut; it does not use negative values though, so any 00 is potentialy out of gamut as well valid = False break if valid: if rgbhex in allhex: valid=False # check if too close to a color in the palette if valid and minDistance > 0: for al in alllab: # TODO fast spatial query structure (kd-tree etc., or binning) colorDist = delta_e_cie2000(al, labcolor) if colorDist < minDistance: valid = False break if valid: allhex.append(rgbhex) alllab.append(labcolor) if gradient: z = HL.next() # change the lightness only if we found a valid color, which leads to higher contrast in adjacent colors nrFails = 0 yield rgbhex else: nrFails += 1 if nrFails >= maxFails: print "[ERROR] Could not find a new color after %d iterations!" % maxFails break if len(alllab) == maxNrColors: break
def plot_scheme(schemeIdx,index1=0,index2=0): """ The 5 colors in each theme will be shown in a 3D space. To show the ordinal properties of the colors, colors are connected with lines Distance between colors is shown as text. The first color is shown as a regular triangle. The last color is shown as an inverted triangle. The rest are shown as circles. """ from mpl_toolkits.mplot3d import axes3d, Axes3D from colormath import color_diff from colormath.color_objects import LabColor, sRGBColor from colormath.color_conversions import convert_color # viewpoint if index1 == 'a' and index2 == 'b': el = 90 az = -90 elif index1 == 'L' and index2 == 'a': el = 0 az = 90 elif index1 == 'L' and index2 == 'b': el = 0 az = 180 elif int(index1) == 0 and int(index2) == 0: el = None az = None # draw a figure fig = plt.figure(figsize=(6,6)) ax = fig.add_subplot(111, projection='3d') # loop over the colors in a scheme for i in range(5): # df_ already has cm format(ex. Lab1) and list format (ex. L1, a1...) # 1. conver Lab color to sRGB for assigning colors for the plot LabColor_cm = df_['Lab'+str(i+1)][schemeIdx] sRGBColor_cm = convert_color(LabColor_cm,sRGBColor) # 2. convert this value to list for plotting sRGBColor_list = col_tuple2list(sRGBColor_cm) r = min(sRGBColor_list[0],1) g = min(sRGBColor_list[1],1) b = min(sRGBColor_list[2],1) color = np.array([[r,g,b],[0,0,0]]) # 3. load the Lab coordinates L = df_['L'+str(i+1)][schemeIdx] a = df_['a'+str(i+1)][schemeIdx] b = df_['b'+str(i+1)][schemeIdx] # 4. draw each color (first: triangle, last: reversed triangle, in-betweens: circle) marker_vec = ['^','o','o','o','v'] ax.scatter(a,b,L,c=color,s=250,marker=marker_vec[i]) # 5. draw lines between dots if i > 0: L_prev = df_['L'+str(i)][schemeIdx] a_prev = df_['a'+str(i)][schemeIdx] b_prev = df_['b'+str(i)][schemeIdx] ax.plot([a_prev,a],[b_prev,b],[L_prev,L],color='black',alpha=0.2) # 6. compute distance between dots LabColor_cm_prev = LabColor(L_prev,a_prev,b_prev) diff = color_diff.delta_e_cie2000(LabColor_cm,LabColor_cm_prev) ax.text((a_prev+a)/2,(b_prev+b)/2,(L_prev+L)/2,'%.1f' %diff,(1,0,0)) # view angle ax.view_init(elev=el,azim=az) # labels ax.set_xlabel('a') ax.set_ylabel('b') ax.set_zlabel('L') ax.set_xlim3d(-128, 128) ax.set_ylim3d(-128, 128) ax.set_zlim3d(0, 100) # show theme name and number of likes ax.set_title('#'+str(schemeIdx)+':'+df.name[schemeIdx]+' ('+str(df.Likes[schemeIdx])+')')
def distance(color1, color2): """Color distance as defined by CIE76 (L2 norm)""" return delta_e_cie2000(LabColor(*color1), LabColor(*color2))