def contrast_text(self): """Returns hex code of a color that contrasts with this one, for overlaying text. Includes the #.""" # get rgb and hsv values rgbcolor = RGBColor() rgbcolor.set_from_rgb_hex(self.color_hex) hsvcolor = rgbcolor.convert_to('hsv') new_v = hsvcolor.hsv_v; if new_v <= .55: new_v = 1.0; elif new_v > .55: new_v = 0.0; new_h = hsvcolor.hsv_h new_s = 0 contrast = HSVColor(hsv_h = new_h, hsv_s = new_s, hsv_v = new_v) contrast_rgb = contrast.convert_to('rgb') return contrast_rgb.get_rgb_hex()
def find_color_code_naive(h, s, b): if check_gray(s, b): return 'gray' if check_black(s, b): return 'black' if check_white(s, b): return 'white' first = find_nearest_idx(HUE_TABLE.values(), h) if b > BRIGHTNESS_IMPORTANCE_LEVEL: logger.info('Brightness is important') second = find_nearest_idx(SATURATION_TABLE, s) else: logger.info('Saturation is important') second = find_nearest_idx(BRIGHTNESS_TABLE, b) color = HSVColor(HUE_TABLE[first], SATURATION_TABLE[second]/100.0, BRIGHTNESS_TABLE[second]/100.0) color = convert_color(color, sRGBColor) return color.get_value_tuple(), (first, second)
def test_conversion_to_hsv(self): hsv = convert_color(self.color, HSVColor) self.assertColorMatch(hsv, HSVColor(90.816, 0.750, 0.784))
# The color numbers are: # 0: black # 1: red # 2: green # 3: yellow # 4: blue # 5: magenta # 6: cyan # 7: white # blk red grn ylw blu mag cya wht hues = [50, 0, 105, 58, 220, 295, 175, 50] sats = [10, 80, 80, 80, 60, 80, 80, 10] vals = [12, 80, 70, 80, 95, 80, 80, 87] cursor_color = HSVColor(85, .95, 1) colors = [] for i in range(8): color = HSVColor(hues[i], sats[i] / 100, vals[i] / 100) colors.append(color) for i in range(8): dark = colors[i] light = HSVColor(dark.hsv_h, min(1, dark.hsv_s * 0.8), min(1, dark.hsv_v * 3)) colors.append(light) rgb_colors = []
def setUp(self): self.color = HSVColor(91.0, 0.750, 0.784)
def get_multiple_dominant_colors(image1, image2, image3, k, image_processing_size=None): """ takes an image as input returns two lists i) five dominant colors of the image as a list (int values) ii) list of confidence values of the same size (2 decimal places) dominant colors are found by running k means on the pixels & returning the centroid of the largest cluster processing time is sped up by working with a smaller image; this resizing can be done with the image_processing_size param which takes a tuple of image dims as input >>> get_multiple_dominant_colors(my_image, k, image_processing_size = (25, 25)) [ [0, 0, 254], [110, 37, 188], [101, 13, 241], [45, 26, 181], [85, 28, 133] ] // five dominant colors in HSV format [0.84, 0.05, 0.05, 0.04, 0.02] // confidence values """ # resize image if new dims provided if image_processing_size is not None: image1 = cv2.resize(image1, image_processing_size, interpolation=cv2.INTER_AREA) image2 = cv2.resize(image2, image_processing_size, interpolation=cv2.INTER_AREA) image3 = cv2.resize(image3, image_processing_size, interpolation=cv2.INTER_AREA) # reshape the image to be a list of pixels image1 = image1.reshape((image1.shape[0] * image1.shape[1], 3)) image2 = image2.reshape((image2.shape[0] * image2.shape[1], 3)) image3 = image3.reshape((image3.shape[0] * image3.shape[1], 3)) image = np.concatenate((image1, image2, image3)) # cluster and assign labels to the pixels clt = KMeans(n_clusters=k) labels = clt.fit_predict(image) # count labels to find most popular label_counts = Counter(labels) # subset out k popular centroids topK = label_counts.most_common(k) dominant_colors_hsv = [] confidences = [] for label in topK: tmp = [ int(e) for e in clt.cluster_centers_[label[0]].tolist() ] dominant_colors_hsv.append(tmp) confidences.append(round(label[1]/TOTAL, 2)) print(dominant_colors_hsv) print(confidences) # exclude colors that are similar to existing ones and with < 0.1 confidence value index_to_remove = set() for i in range(k): color_i = dominant_colors_hsv[i] color_i_hsv = HSVColor(color_i[0], color_i[1], color_i[2]) color_i_lab = convert_color(color_i_hsv, LabColor) color_i_delta = [] for j in range(i+1, k): color_j = dominant_colors_hsv[j] color_j_hsv = HSVColor(color_j[0], color_j[1], color_j[2]) color_j_lab = convert_color(color_j_hsv, LabColor) delta_e = delta_e_cie2000(color_i_lab, color_j_lab); color_i_delta.append(delta_e) for j in range (len(color_i_delta)): if (confidences[i+j+1] < 0.2 and color_i_delta[j] < 40): index_to_remove.add(i+j+1) # print("color {} ({}) : \n\t{}".format(i, color_i, color_i_delta)) # print("index to remove : {}".format(index_to_remove)) itr = list(index_to_remove) itr.sort(reverse = True) print("ITR : {}".format(itr)) # trim insignificant colors for i in range(len(itr)): dominant_colors_hsv.pop(itr[i]) confidences.pop(itr[i]) dominant_colors_rgb = [] for color_hsv in dominant_colors_hsv: color_rgb = colorsys.hsv_to_rgb(color_hsv[0]/180., color_hsv[1]/255., color_hsv[2]/255.) # print(list(color_rgb)) ret = list(map(lambda a : round(a*255), list(color_rgb))) # print(ret) dominant_colors_rgb.append(ret) print("\n") print(dominant_colors_hsv) print(dominant_colors_rgb) print(confidences) return len(confidences), dominant_colors_hsv, dominant_colors_rgb, confidences
def getColor(id): color = HSVColor(id * 60 % 360, 150, 200) return np.array( convert_color(color, sRGBColor).get_value_tuple() ) / 255.0 # FIXME: This is bgr color
def get_hex(self, hsv_h, hsv_s, hsv_v): hsv = HSVColor(hsv_h=hsv_h / 200, hsv_s=hsv_s / 254, hsv_v=hsv_v / 254) rgb = hsv.convert_to('rgb') return rgb.get_rgb_hex()
def _make_cols(n, hue): return [ convert_color(HSVColor(hue, i / (n - 1), 1), sRGBColor).get_rgb_hex() for i in range(n) ]
def detailTable(colors): print("\033[1m{:7} {:20} {:3} {:7} {:25} {:20} {:21}\033[0m".format( "HEX", "NAME", "ID", "XHEX", "L*A*B", "RGB", "HSV")) for color in colors: codes = colorCodes(color) print( "{:7} {:20} {:3} {:7} {:8.3f} {: 8.3f} {: 8.3f} {:6.3f} {:6.3f} {:6.3f} {:7.3f} {:7.3f} {:7.3f}" .format(fmtHex(codes['hex']), codes['xname'], codes['xid'], fmtHex(codes['xhex']), codes['lab'].lab_l, codes['lab'].lab_a, codes['lab'].lab_b, codes['rgb'].rgb_r, codes['rgb'].rgb_g, codes['rgb'].rgb_b, codes['hsv'].hsv_h, codes['hsv'].hsv_s, codes['hsv'].hsv_v)) colors = [] for l in np.linspace(0, 100, 3): for a in np.linspace(-127, 127, 3): for b in np.linspace(-127, 127, 3): colors.append(LabColor(l, a, b)) detailTable(colors) colors = [] for r in np.linspace(0, 1, 3): for g in np.linspace(0, 1, 3): for b in np.linspace(0, 1, 3): colors.append(sRGBColor(r, g, b)) detailTable(colors) colors = [] for h in np.linspace(0, 360, 9): colors.append(HSVColor(h, 1, 1)) detailTable(colors)
def generat_tf_from_tf1d(tf1d_filename, num_modes, bg_color, min_scalar_value, max_scalar_value, res=256, write_scalars=True): if write_scalars: opacity_map = np.zeros((res, 2)) else: opacity_map = np.zeros((res, 1)) f = open(tf1d_filename, 'r') i = 0 intensity = [] al = [] r = [] g = [] b = [] for line in f.readlines(): i = i + 1 if i == 1: keyNum, thresholdL, threhsholdU = line.split() keyNum = int(keyNum) else: Tintensity = float(line.split()[0]) * res + np.random.normal(0, 1) if Tintensity < min_scalar_value: Tintensity = min_scalar_value elif Tintensity > max_scalar_value: Tintensity = max_scalar_value intensity.append(Tintensity) #intensity r.append(float(line.split()[1]) / 255.0) #red g.append(float(line.split()[2]) / 255.0) #green b.append(float(line.split()[3]) / 255.0) #blue al.append(float(line.split()[4]) / 255.0) #opcaity #order = np.argsort(intensity) #intensity = np.asarray(intensity)[order] #al = np.asarray(al)[order] intensity[-1] = max_scalar_value intensity[0] = min_scalar_value for idx in range(len(intensity) - 1): if intensity[idx] > intensity[idx + 1]: intensity[idx + 1] = intensity[idx] #pdb.set_trace() cur = 0 for idx in range(res): interp = float(idx) / (res - 1) scalar_val = min_scalar_value + interp * (max_scalar_value - min_scalar_value) if cur < keyNum - 1 and scalar_val > intensity[cur + 1]: cur = cur + 1 if write_scalars: opacity_map[idx, 0] = scalar_val if cur < keyNum - 1: if intensity[cur + 1] == intensity[cur]: opacity_map[idx, 1] = al[cur] else: opacity_map[idx, 1] = (al[cur + 1] - al[cur]) * ( scalar_val - intensity[cur]) / ( intensity[cur + 1] - intensity[cur]) + al[cur] else: opacity_map[idx, 1] = al[cur] else: if cur < keyNum - 1: opacity_map[idx, 1] = (al[cur + 1] - al[cur]) * ( scalar_val - intensity[cur]) / (intensity[cur + 1] - intensity[cur]) + al[cur] else: opacity_map[idx, 1] = al[cur] if num_modes > (i - 3): num_modes = i - 3 color_gmm = np.zeros((i - 1, 4)) for idx in range(i - 1): color_gmm[idx, 0] = intensity[idx] color_gmm[idx, 1] = r[idx] color_gmm[idx, 2] = g[idx] color_gmm[idx, 3] = b[idx] #pdb.set_trace() seq1 = range(i - 3) seq = [] for idx in seq1: seq.append(idx) np.random.shuffle(seq) #color_gmm[0, 0] = intensity[0] #color_gmm[-1, 0] = intensity[-1] slide_window_size = 0.4 v_scale = 0.8 window_st = (1 - slide_window_size) * al[0] window_en = (1 - slide_window_size) * al[0] + slide_window_size if bg_color == 0: color_gmm[0, 1:] = convert_color( HSVColor(360.0 * np.random.uniform(), np.random.uniform(), (1 - v_scale) / 2 + v_scale * np.random.uniform(window_st, window_en)), sRGBColor).get_value_tuple() else: color_gmm[0, 1:] = convert_color( HSVColor(360.0 * np.random.uniform(), np.random.uniform(), (1 - v_scale) / 2 + v_scale * (1 - np.random.uniform(window_st, window_en))), sRGBColor).get_value_tuple() window_st = (1 - slide_window_size) * al[-1] window_en = (1 - slide_window_size) * al[-1] + slide_window_size if bg_color == 0: color_gmm[-1, 1:] = convert_color( HSVColor(360.0 * np.random.uniform(), np.random.uniform(), (1 - v_scale) / 2 + v_scale * np.random.uniform(window_st, window_en)), sRGBColor).get_value_tuple() else: color_gmm[-1, 1:] = convert_color( HSVColor(360.0 * np.random.uniform(), np.random.uniform(), (1 - v_scale) / 2 + v_scale * (1 - np.random.uniform(window_st, window_en))), sRGBColor).get_value_tuple() for idx in range(num_modes): color_gmm[idx + 1, 0] = intensity[seq[idx] + 1] window_st = (1 - slide_window_size) * al[seq[idx] + 1] window_en = (1 - slide_window_size) * al[seq[idx] + 1] + slide_window_size if (bg_color == 0): color_gmm[idx + 1, 1:] = convert_color( HSVColor(360.0 * np.random.uniform(), np.random.uniform(), v_scale * np.random.uniform(window_st, window_en)), sRGBColor).get_value_tuple() else: color_gmm[idx + 1, 1:] = convert_color( HSVColor( 360.0 * np.random.uniform(), np.random.uniform(), v_scale * (1 - np.random.uniform(window_st, window_en))), sRGBColor).get_value_tuple() sorted_color_inds = np.argsort(color_gmm[:, 0]) color_gmm = color_gmm[sorted_color_inds, :] #pdb.set_trace() color_map = pw_color_map_sampler(min_scalar_value, max_scalar_value, color_gmm, res, write_scalars) #pdb.set_trace() return opacity_map, color_map
def get_multiple_dominant_colors(image1, image2, image3=None, image_processing_size=None): global res_red, res_green, res_blue """ takes an image as input returns FOUR values i) number of colors ii) X number of dominant colors in HSV (int values) iii) X number of dominant colors in RGB (int values) iv) list of confidence values of the same size (2 decimal places) dominant colors are found by running k-means algorithm on the pixels of an image & returning the centroid of the largest cluster(s) processing time is sped up by working with a smaller image; this resizing can be done with the image_processing_size param which takes a tuple of image dims as input >>> get_multiple_dominant_colors(my_image, k, image_processing_size = (25, 25)) 4 # 4 colors [[20, 79, 72], [33, 182, 38], [4, 5, 241], [139, 17, 178]] # dominant colors in HSV [[72, 65, 50], [35, 38, 11], [241, 237, 236], [174, 166, 178]] # dominant colors in RGB [268.7, 103.0, 73.79, 15.32] # confidence values """ k = CLUSTERS image = None # read in image of interest bgr_image1 = cv2.imread(image1) bgr_image2 = cv2.imread(image2) # convert to HSV; this is a better representation of how we see color hsv_image1 = cv2.cvtColor(bgr_image1, cv2.COLOR_BGR2HSV) hsv_image2 = cv2.cvtColor(bgr_image2, cv2.COLOR_BGR2HSV) image1 = cv2.resize(hsv_image1, image_processing_size, interpolation=cv2.INTER_AREA) image2 = cv2.resize(hsv_image2, image_processing_size, interpolation=cv2.INTER_AREA) # reshape the image to be a list of pixels image1 = image1.reshape((image1.shape[0] * image1.shape[1], 3)) image2 = image2.reshape((image2.shape[0] * image2.shape[1], 3)) if (image3 is not None): bgr_image3 = cv2.imread(image3) hsv_image3 = cv2.cvtColor(bgr_image3, cv2.COLOR_BGR2HSV) image3 = cv2.resize(hsv_image3, image_processing_size, interpolation=cv2.INTER_AREA) image3 = image3.reshape((image3.shape[0] * image3.shape[1], 3)) if (image3 is None): image = np.concatenate((image1, image2)) else: image = np.concatenate((image1, image2, image3)) # else: # # read in image of interest # bgr_image1 = cv2.imread(image1) # # convert to HSV; this is a better representation of how we see color # hsv_image1 = cv2.cvtColor(bgr_image1, cv2.COLOR_BGR2HSV) # # image1 = cv2.resize(hsv_image1, image_processing_size, interpolation=cv2.INTER_AREA) # # # reshape the image to be a list of pixels # image = image1.reshape((image1.shape[0] * image1.shape[1], 3)) # cluster and assign labels to the pixels clt = KMeans(n_clusters=k) labels = clt.fit_predict(image) # count labels to find most popular label_counts = Counter(labels) # subset out k popular centroids topK = label_counts.most_common(k) dominant_colors_hsv = [] confidences = [] for label in topK: tmp = [ int(e) for e in clt.cluster_centers_[label[0]].tolist() ] dominant_colors_hsv.append(tmp) base = TOTAL*3 confidences.append(round(label[1]/base, 2)) index_to_remove = set() confidence_value_threshold = 0.1 if (len(dominant_colors_hsv) >= k): # exclude colors that are similar to existing ones and with < 0.1 confidence value for i in range(k): color_i = dominant_colors_hsv[i] color_i_hsv = HSVColor(color_i[0], color_i[1], color_i[2]) color_i_lab = convert_color(color_i_hsv, LabColor) color_i_delta = [] for j in range(i+1, k): color_j = dominant_colors_hsv[j] color_j_hsv = HSVColor(color_j[0], color_j[1], color_j[2]) color_j_lab = convert_color(color_j_hsv, LabColor) delta_e = delta_e_cie2000(color_i_lab, color_j_lab); color_i_delta.append(delta_e) for j in range(len(color_i_delta)): if (confidences[i+j+1] < confidence_value_threshold and color_i_delta[j] < 40): index_to_remove.add(i+j+1) else: # if the # of domcol is less than k, trim colors that are < 0.1 confidence value only for i in range(len(dominant_colors_hsv)): if (confidences[i] < confidence_value_threshold): index_to_remove.add(i) itr = list(index_to_remove) itr.sort(reverse = True) # trim insignificant colors for i in range(len(itr)): dominant_colors_hsv.pop(itr[i]) confidences.pop(itr[i]) # convert HSV to get RGB colors dominant_colors_rgb = [] for color_hsv in dominant_colors_hsv: ret = hsvToRgb(color_hsv[0], color_hsv[1], color_hsv[2]) dominant_colors_rgb.append(ret) res_red.append(str(dominant_colors_rgb[0][0])) res_green.append(str(dominant_colors_rgb[0][1])) res_blue.append(str(dominant_colors_rgb[0][2])) return len(confidences), dominant_colors_hsv, dominant_colors_rgb, confidences
def set_hsv(self, h, s, v): self._set_hsv_color(HSVColor(h, s, v))