def compare(referenceRgbas, comparisonRgbas): referenceLabs = convertToLabs(referenceRgbas) comparisonLabs = convertToLabs(comparisonRgbas) n = len(comparisonLabs) m = len(referenceLabs) / n diff = np.zeros(n) for i in range(m): diff += color.deltaE_ciede2000(referenceLabs[i::m], comparisonLabs) diff /= m return diff
def coloursort(pal, index): i = 0 maxcon = 0.001 maxind = 0 print(pal[index]) print(pal[0]) i += 1 while i < 5: if i != index: a = abs(color.deltaE_ciede2000(pal[index], pal[i])[0][0]) if a > maxcon: maxcon = a maxind = i i += 1 i = 0 maxcon = 0.001 maxind2 = 0 while i < 5: if i != index and i != maxind: a = abs(color.deltaE_ciede2000(pal[i], pal[maxind])[0][0]) if a > maxcon: maxcon = a maxind2 = i i += 1 inds = [index, maxind, maxind2] return inds
def get_nearest_color(color, reference_colors, color_space='lab'): """ Gets the argument and value of the nearest color in reference color array. The nearance is calculated with skimage.color.deltaE_ciede2000 function Parameters: ----------- color: the color in lab color space to be compared reference_colors: array of lab colors; shape (..., ..., 3) Returns: -------- arg = position of nearest color in reference colors nearest_color = nearest color in lab color space """ color.reshape(-1, 1, 3) reference_colors.reshape(-1, 1, 3) if color_space is not 'lab': color = skimage_color.rgb2lab(color) # reference_colors = skimage_color.rgb2lab(reference_colors) arg = np.argmin(skimage_color.deltaE_ciede2000(color, reference_colors), axis=0) nearest_color = np.take(reference_colors, arg, axis=0) return arg, nearest_color
def cie_de( reference: numpy.ndarray, distorted: numpy.ndarray, dE_function="2000", lightness_weight=1.0, chroma_weight=1.0, hue_weight=1.0, ) -> numpy.ndarray: assert reference.shape == distorted.shape, "Shapes do not match" if len(reference.shape) == 2: reference = reference[numpy.newaxis, ...] distorted = distorted[numpy.newaxis, ...] reference_lab = rgb2lab(reference) distorted_lab = rgb2lab(distorted) if dE_function == "2000": deltaE = deltaE_ciede2000(reference_lab, distorted_lab, lightness_weight, chroma_weight, hue_weight) elif dE_function == "1994": deltaE = deltaE_ciede94(reference_lab, distorted_lab, hue_weight, chroma_weight, lightness_weight) elif dE_function == "1976": deltaE = deltaE_cie76(reference_lab, distorted_lab) else: raise NameError( "CIE dE function with name {} not found".format(dE_function)) return deltaE
def closest_color_index(color): """ returns index of closest color in global color_terms matrix """ return np.argmin(skimage_color.deltaE_ciede2000( color, color_terms[['l', 'a', 'b']].as_matrix()), axis=0)
def deltaE(c1,c2): # http://scikit-image.org/docs/dev/api/skimage.color.html#skimage.color.deltaE_ciede2000 if not isinstance(c1, Color): c1=Color(c1) if not isinstance(c2, Color): c2=Color(c2) return skcolor.deltaE_ciede2000(c1.lab, c2.lab)
def deltaE(c1, c2): # http://scikit-image.org/docs/dev/api/skimage.color.html#skimage.color.deltaE_ciede2000 if not isinstance(c1, Color): c1 = Color(c1) if not isinstance(c2, Color): c2 = Color(c2) return skcolor.deltaE_ciede2000(c1.lab, c2.lab)
def CIEDE2000(self, color_value_expand, color_feat_expand): bs, color_dim, num_top_k = color_value_expand.shape color_value_expand = np.transpose(color_value_expand, (0, 2, 1)) color_feat_expand = np.transpose(color_feat_expand, (0, 2, 1)) color_value_expand = np.reshape(color_value_expand, (bs, num_top_k, 3, 10)) color_feat_expand = np.reshape(color_feat_expand, (bs, num_top_k, 3, 10)) color_value_expand = np.transpose(color_value_expand, (0, 1, 3, 2)) color_feat_expand = np.transpose(color_feat_expand, (0, 1, 3, 2)) color_sim = [ deltaE_ciede2000(rgb2lab(color_value_expand[i]), rgb2lab(color_feat_expand[i])) for i in range(bs) ] color_sim = np.mean(np.array(color_sim), axis=2) color_sim = torch.tensor(color_sim).to(self.device) color_sim.requires_grad = False return color_sim
def deltaE(self, other): import skimage.color as skcolor a = skcolor.deltaE_ciede2000( self.convert('lab').array, other.convert('lab').array, ) return Image(a, 'F')
def get_color_from_lab(lab_color: List[float]) -> Dict: """ Given an array of 3 values representing an LAB color, return an object representing the closest color to that LAB value. L values should be between 0 and 100; A and B between -128 and 127. The returned value has the following keys: xkcd_color, xkcd_color_hex, xkcd_r, xkcd_g, xkcd_b, design_color, design_color_hex, design_r, design_g, design_b, common_color, common_color_hex, common_r, common_g, common_b, color_family, color_type, color_or_neutral. """ color_data = _get_color_data() assert (hasattr(lab_color, "__len__") and len(lab_color) == 3), "lab_color must be a list of 3 floats." assert lab_color[0] >= 0 and lab_color[ 0] <= 100, "L should be between 0 and 100." assert (lab_color[1] >= -128 and lab_color[1] <= 127), "A should be between -128 and 127." assert (lab_color[2] >= -128 and lab_color[2] <= 127), "B should be between -128 and 127." dists = np.array([ deltaE_ciede2000(lab_color, item) for item in color_data["lab_values"] ]) xkcd_name = color_data["xkcd_names"][dists.argmin()] return color_data["color_hierarchy"][xkcd_name]
def cost(array_a, array_b): a = array_a.reshape(-1) b = array_b.reshape(-1) sum = 0 sum += deltaE_ciede2000(a, b) return sum
def deltaE(self, other): import skimage.color as skcolor a = skcolor.deltaE_ciede2000( self.convert('lab').array, other.convert('lab').array, ) return Image(a, 'F')
def calcVarCiede(x, y, variation, img, gaussKernel): counter = 0 value = 0 for vary in range(-variation, variation + 1): for varx in range(-variation, variation + 1): if (x + varx < 0 or x + varx >= img.shape[1] or y + vary < 0 or y + vary >= img.shape[0]): #out of bounds do not take into average #do nothing continue elif (vary == 0 and varx == 0): #do not compare with yourself continue else: diff = color.deltaE_ciede2000(img[y][x], img[y + vary][x + varx]) #multipli with the gaussian value gausDiff = diff * gaussKernel[vary + variation][varx + variation] #take the power of it for the euclidian distance value += gausDiff**2 #print(str(color.deltaE_ciede2000(img[y][x],img[y+vary][x+varx])) + "value") counter += 1 #calculate and save the euclidian difference with its surroundings #values[y][x] = value/counter return np.sqrt(value / counter)
def process_pair(ref, recons): ref_lab = color.rgb2lab(decode_y4m_buffer(ref)) recons_lab = color.rgb2lab(decode_y4m_buffer(recons)) # "Color Image Quality Assessment Based on CIEDE2000" # Yang Yang, Jun Ming and Nenghai Yu, 2012 # http://dx.doi.org/10.1155/2012/273723 dE = color.deltaE_ciede2000(ref_lab, recons_lab, kL=0.65, kC=1.0, kH=4.0) scores.append(45. - 20. * np.log10(dE.mean())) print('%08d: %2.4f' % (ref.count, scores[-1]))
def process_pair(ref, recons): ref_lab = color.rgb2lab(decode_y4m_buffer(ref)) recons_lab = color.rgb2lab(decode_y4m_buffer(recons)) # "Color Image Quality Assessment Based on CIEDE2000" # Yang Yang, Jun Ming and Nenghai Yu, 2012 # http://dx.doi.org/10.1155/2012/273723 dE = color.deltaE_ciede2000(ref_lab, recons_lab, kL=0.65, kC=1.0, kH=4.0) scores.append(45. - 20. * np.log10(dE.mean())) print('%08d: %2.4f' % (ref.count, scores[-1]))
def color_confidence(im1, im2): #switch from BGR to RGB im1RGB = cv2.cvtColor(im1, cv2.COLOR_BGR2RGB) im2RGB = cv2.cvtColor(im2, cv2.COLOR_BGR2RGB) im1LAB = color.rgb2lab(im1RGB) im2LAB = color.rgb2lab(im2RGB) diff = color.deltaE_ciede2000(im1LAB,im2LAB) diff = diff + 0.4 return diff
def color_confidence(im1, im2): #switch from BGR to RGB im1RGB = cv2.cvtColor(im1, cv2.COLOR_BGR2RGB) im2RGB = cv2.cvtColor(im2, cv2.COLOR_BGR2RGB) im1LAB = color.rgb2lab(im1RGB) im2LAB = color.rgb2lab(im2RGB) diff = color.deltaE_ciede2000(im1LAB,im2LAB) dist = (im1RGB[:,:,0]-im2RGB[:,:,0])**2+(im1RGB[:,:,1]-im2RGB[:,:,1])**2 + (im1RGB[:,:,2]-im2RGB[:,:,2])**2 rgb_diff = dist return diff, rgb_diff
def closest_colors(color): """ Calculates closest colour referred to global color_terms matrix returns closest color """ return np.take(color_terms.as_matrix(), np.argmin(skimage_color.deltaE_ciede2000( color, color_terms[['l', 'a', 'b']].as_matrix()), axis=0), axis=0)
def delta_e_dist(color1, color2): """color1 and color2 are in rgb space""" # do some nice integer conversions color1 = np.round(255*color1) color2 = np.round(255*color2) # convert colors to lab color1_lab = color.rgb2lab(np.array([[color1]], dtype=np.uint8)).flatten() color2_lab = color.rgb2lab(np.array([[color2]], dtype=np.uint8)).flatten() # compute Delta E CIEDE 2000 distance return color.deltaE_ciede2000(color1_lab, color2_lab)
def check_color(x_range, y_range, color_list): min_error = -1 min_error_color = None for c in color_list: sum = 0.0 for i in x_range: for j in y_range: dist = deltaE_ciede2000(TARGET_IMAGE[i][j], c) sum += dist if min_error == -1 or sum < min_error: min_error = sum min_error_color = c print(x_range, y_range, min_error_color) return min_error_color
def get_contrasting_colors(color_array): """ calculates distance matrix for colors in color_array returns: a : fist color of most distant b : second color of most distant max_dist : distance of these colors measured with deltaE_ciede2000 """ distances = cdist(color_array, color_array, lambda a, b: skimage_color.deltaE_ciede2000(a, b)) max_args = np.argmax(distances) t = np.unravel_index(max_args, distances.shape) return color_array[t[0]], color_array[t[1]], distances.reshape( -1)[max_args]
def _initialize_parameters(self, X, random_state): """Changes init parameters from K-means to CIE LAB distance when palette is assigned""" assert self.init_params == "kmeans", "Initialization is overwritten, can only be set as 'kmeans'." n_samples, _ = X.shape resp = np.zeros((n_samples, self.n_components)) if self.find_palette: # original label = KMeans(n_clusters=self.n_components, n_init=1, random_state=random_state).fit(X).labels_ else: # color distance label = np.argmin([deltaE_ciede2000(rgb2lab(X), rgb2lab(p), kH=3, kL=2) for p in self.palette], axis=0) resp[np.arange(n_samples), label] = 1 self._initialize(X, resp)
def test_ciede2000_dE(): data = load_ciede2000_data() N = len(data) lab1 = np.zeros((N, 3)) lab1[:, 0] = data['L1'] lab1[:, 1] = data['a1'] lab1[:, 2] = data['b1'] lab2 = np.zeros((N, 3)) lab2[:, 0] = data['L2'] lab2[:, 1] = data['a2'] lab2[:, 2] = data['b2'] dE2 = deltaE_ciede2000(lab1, lab2) assert_allclose(dE2, data['dE'], rtol=1.e-4)
def test_ciede2000_dE(): data = load_ciede2000_data() N = len(data) lab1 = np.zeros((N, 3)) lab1[:, 0] = data['L1'] lab1[:, 1] = data['a1'] lab1[:, 2] = data['b1'] lab2 = np.zeros((N, 3)) lab2[:, 0] = data['L2'] lab2[:, 1] = data['a2'] lab2[:, 2] = data['b2'] dE2 = deltaE_ciede2000(lab1, lab2) assert_allclose(dE2, data['dE'], rtol=1.e-4)
def color_calculation(rgb1, rgb2, mode='euclidean'): # simple euclidean and CIELAB color calculation distance = 0 if mode == 'euclidean': distance = ((rgb1[0] - rgb2[0])**2 + (rgb1[1] - rgb2[1])**2 + (rgb1[2] - rgb2[2])**2)**.5 elif mode == 'deltaE': try: lab1 = rgb2lab([[rgb1]]) lab2 = rgb2lab([[rgb2]]) distance = deltaE_ciede2000(lab1, lab2) except ImportError: print( '----WARNING----- use pip install scikit-image to use deltaE color difference\n' ) return distance
def color_distance(): diff_bl = 255 - base_image_representative_rgb[0] diff_g = 255 - base_image_representative_rgb[1] diff_r = 255 - base_image_representative_rgb[2] def skimage_rgb2lab(rgb): return color.rgb2lab(rgb.reshape(1, 1, 3)) euclid_distance = math.sqrt(((base_image_representative_rgb[0] - compare_image_representative_rgb[0])**2) + ((base_image_representative_rgb[1] - compare_image_representative_rgb[1])**2) + ((base_image_representative_rgb[2] - compare_image_representative_rgb[2])**2)) de2000 = color.deltaE_ciede2000( skimage_rgb2lab(base_image_representative_rgb), skimage_rgb2lab(compare_image_representative_rgb))[0][0] # rgb_img = np.zeros((30, 30, 3), dtype=np.uint8) # cv2.rectangle(rgb_img, (0, 0), (30, 30), collected_rgb, thickness=-1) # rgb_image_canvas = tk.Canvas(width = 30, height = 30) # rgb_image_canvas.image = ImageTk.PhotoImage(opencv2pillow(rgb_img)) # rgb_image_canvas.create_image(0,0,image = rgb_image_canvas.image, anchor = tk.NW) # collected_lab = [ # np.uint8(compare_image_representative_lab[0] + diff_l), # np.uint8(compare_image_representative_lab[1] + diff_a), # np.uint8(compare_image_representative_lab[2] + diff_b) # ] # lab_img = np.full((30, 30, 3), collected_lab) # rgb_from_lab = lab2rgb(lab_img)[0][0] # cv2.rectangle(lab_img, (0, 0), (30, 30), (int(rgb_from_lab[0]), int(rgb_from_lab[1]), int(rgb_from_lab[2])), thickness=-1) # lab_image_canvas = tk.Canvas(width = 30, height = 30) # lab_image_canvas.image = ImageTk.PhotoImage(opencv2pillow(lab_img)) # lab_image_canvas.create_image(0,0,image = lab_image_canvas.image, anchor = tk.NW) title = tk.Label(text='色の距離', relief=tk.RIDGE) title.grid(row=6, column=0, padx=5, pady=5) euclid = tk.Label(text='ユークリッド距離: ' + str(euclid_distance), relief=tk.RIDGE) euclid.grid(row=6, column=2, padx=5, pady=5) de2000 = tk.Label(text='DE2000: ' + str(de2000), relief=tk.RIDGE) de2000.grid(row=6, column=3, padx=5, pady=5)
def draw(l, a, b, index, v = 201): # v = 201 x = np.zeros((v, v)) y = np.zeros((v, v)) z = np.zeros((v, v)) m = (v-1)//2 for i in range(v): for j in range(v): da = (i-m)*0.1 db = (j-m)*0.1 a2 = a+da b2 = b+db x[i, j] = a2 y[i, j] = b2 cd = color.deltaE_ciede2000(np.array([l, a, b]), np.array([l, a2, b2])) print(type(cd), cd) z[i, j] = cd # exit() fig, ax = plt.subplots() ax.scatter([a], [b], color = 'b') # ax.axhline(y=0, color='k') # ax.axvline(x=0, color='k') # # 设置轴的位置 # ax.spines['left'].set_position('center') # # 设置轴的颜色 # ax.spines['right'].set_color('none') # # 设置轴的位置 # ax.spines['bottom'].set_position('center') # # 设置轴的颜色 # ax.spines['top'].set_color('none') ax.set_xlabel('a*') ax.set_ylabel('b*') CS = ax.contour(x,y,z, 10) ax.clabel(CS, inline = 1, fontsize = 10) title = f'Macbeth_{index}' ax.set_title(title) plt.annotate(f'M{index}', xy=(a,b),xytext = (0, -10), textcoords = 'offset points',ha = 'center', va = 'top') # plt.show() plt.savefig(os.path.join('imgs', title+'.png'))
def get_match_ratio(color_: Tuple[Union[int, float]], palette: np.ndarray, freqs: np.ndarray) -> np.float: """ Calculates how close the *color* is to the palette colors, considering amounts of each color Uses CIEDE 2000 standard to measure color distance :param color_: Source color in RGB (0 to 1) float array representation :param palette: Array of colors in RGB (0 to 255) float array representation :param freqs: Array with amounts (0 to 1) for each color in palette :returns: Matching ratio (0 to 1) """ limit = np.float64(25) palette = color.rgb2lab(palette / 255) color_ = color.rgb2lab(np.float64(color_)) deltas = color.deltaE_ciede2000(color_, palette, kL=2) deltas_inverted = limit - deltas deltas_inverted[deltas_inverted < 0] = 0 ratios = deltas_inverted / limit * freqs return ratios.max()
def __call__(self, genImage, gtImage): for pair in range(len(genImage)): # Converting and changing shape of torch tensor into numpy imageGTNP = self.torchTensorToNumpy(gtImage[pair]) imageGenNP = self.torchTensorToNumpy(genImage[pair]) # Calculating color difference deltaE = np.absolute( color.deltaE_ciede2000(color.rgb2lab(imageGTNP), color.rgb2lab(imageGenNP))) if self.normalize: deltaE /= 255.0 # Mean deifference for an image pair self.loss.append(np.mean(deltaE)) deltaELoss = torch.mean(torch.tensor( self.loss, requires_grad=True)).to(self.device) #print(deltaELoss) return deltaELoss
def main(args): args = parse_arguments(args) org_img_paths = sorted(glob.glob(args.org_dir + '/*.jpg')) res_img_paths = sorted(glob.glob(args.res_dir + '/*.jpg')) all_des = [] all_ssim = [] all_psnr = [] for i in range(len(org_img_paths)): print(i, org_img_paths[i]) img_org = io.imread(org_img_paths[i]) if len(img_org.shape) == 2: img_org = np.repeat(img_org[:, :, np.newaxis], 3, axis=2) img_res = io.imread(res_img_paths[i]) if img_org.shape != img_res.shape: img_org = cv2.resize(img_org, (img_res.shape[1], img_res.shape[0])) ssim = metrics.structural_similarity(img_org, img_res, multichannel=True) all_ssim.append(ssim) psnr = metrics.peak_signal_noise_ratio(img_org, img_res) all_psnr.append(psnr) if args.de: img_org = color.rgb2lab(img_org) img_res = color.rgb2lab(img_res) de = color.deltaE_ciede2000(img_org, img_res) all_des.append([np.mean(de), np.median(de), np.max(de)]) np.savetxt(args.out_dir + '/ssim_' + args.colour_space + '.txt', np.array(all_ssim)) np.savetxt(args.out_dir + '/psnr_' + args.colour_space + '.txt', np.array(all_psnr)) if args.de: np.savetxt(args.out_dir + '/' + args.colour_space + '.txt', np.array(all_des))
def palette_diversity(fake_lab, real_lab): fake_lab_np = np.array(fake_lab) real_lab_np = np.array(real_lab) palette_len = int(len(fake_lab_np)) diff_np = np.zeros((palette_len, 2)) # 저장할 평균, 분산 # fake 계산 for i, value in enumerate(fake_lab_np): # i 이미지 diff_tmp = np.zeros(5) for j in range(len(value)): # j 팔레트 fake_pal_cal = value[j] diff_last = 999 for k in range(len(real_lab_np[i])): # k real 팔레트 real_pal_cal = real_lab_np[i][k] diff_value = deltaE_ciede2000(fake_pal_cal, real_pal_cal) if diff_value < diff_last: diff_last = diff_value diff_tmp[j] = diff_last diff_data = [np.mean(diff_tmp), np.std(diff_tmp)] diff_np[i][0] = diff_data[0] diff_np[i][1] = diff_data[1] return diff_np
def deltaE(self,other): """color difference according to CIEDE2000 https://en.wikipedia.org/wiki/Color_difference """ assert(self.illuminant==other.illuminant) return skcolor.deltaE_ciede2000(self.lab, other.lab)
def distancia_color(imagen_lab, color_id): return color.deltaE_ciede2000(imagen_lab, colors[color_id])
def test_single_color_ciede2000(): lab1 = (0.5, 0.5, 0.5) lab2 = (0.4, 0.4, 0.4) deltaE_ciede2000(lab1, lab2)
def test_single_color_ciede2000(): lab1 = (0.5, 0.5, 0.5) lab2 = (0.4, 0.4, 0.4) deltaE_ciede2000(lab1, lab2)
mae_a = mean_absolute_error(y_test[:, 1], Test_predict[:, 1]) mae_b = mean_absolute_error(y_test[:, 2], Test_predict[:, 2]) max_ae_J = np.max(np.abs(y_test[:, 0] - Test_predict[:, 0])) max_ae_a = np.max(np.abs(y_test[:, 1] - Test_predict[:, 1])) max_ae_b = np.max(np.abs(y_test[:, 2] - Test_predict[:, 2])) #Pearson R correlation_J = np.corrcoef(Test_predict[:, 0], y_test[:, 0])[0, 1] correlation_a = np.corrcoef(Test_predict[:, 1], y_test[:, 1])[0, 1] correlation_b = np.corrcoef(Test_predict[:, 2], y_test[:, 2])[0, 1] #Color difference D_76 = deltaE_cie76(y_test, Test_predict) D_94 = deltaE_94(y_test, Test_predict) D_2000 = deltaE_ciede2000(y_test, Test_predict) Mean_D76 = np.mean(D_76) Mean_D94 = np.mean(D_94) Mean_D2000 = np.mean(D_2000) Max_D76 = np.max(D_76) Max_D94 = np.max(D_94) Max_D2000 = np.max(D_2000) #////////////////////////////////////////////////////////////////////////////// #Figure plots fig, ax = plt.subplots() ax.scatter(y_test[:, 0], Test_predict[:, 0], marker='o', c='', edgecolors='r') line = mlines.Line2D([0, 1], [0, 1], color='black') transform = ax.transAxes
def get_delta(pic): print(color.deltaE_cmc(LabPic, pic)[0][0]) print(color.deltaE_ciede94(LabPic, pic)[0][0]) print(color.deltaE_ciede2000(LabPic, pic)[0][0])