def perturb(self, img): raw = img_to_matrix(img) perturbed = raw / 255.0 w, h, c = perturbed.shape for i in range(w): for j in range(h): px_color = perturbed[i, j] hsl = np.array(rgb_to_hsluv(px_color)) hsl *= self.mul hsl[0] = np.clip(hsl[0], 0, 360) hsl[1:] = np.clip(hsl[1:], 0, 100) perturbed[i, j] = hsluv_to_rgb(hsl) perturbed *= 255.0 raw_img = Image.fromarray(raw.astype("uint8"), "RGB") perturbed_img = Image.fromarray(perturbed.astype("uint8"), "RGB") noise_img = ImageChops.difference(raw_img, perturbed_img) noise_img = Image.fromarray(img_to_matrix(noise_img) * 50, "RGB") # noise_img = ImageOps.invert(noise_img.convert("L")).convert("RGB") # print((img_to_matrix(noise_img) * 10).max()) # noise_img = Image.fromarray(, "RGB") return raw_img, perturbed_img, noise_img
def main(): saturation = 100 luminance = 30 hues = [ ("myred", 50), ("myyellow", 65), ("mygreen", 140), ("myblue", 250), ("mypurple", 295), ] for name, hue in hues: rgb = hsluv.hsluv_to_rgb((hue, saturation, luminance)) print(rgb_to_latex(rgb, name)) rgb = hsluv.hsluv_to_rgb((0, 0, luminance)) print(rgb_to_latex(rgb, "mygrey"))
def darken(rgb, amount=.15): """ Darken a color by the given amount in HSLuv space. """ h, s, l = hsluv.rgb_to_hsluv(rgb) return hsluv.hsluv_to_rgb((h, s, (1 - amount)*l))
def gradient(length: int, *colors) -> list: """ Generate a looped gradient from multiple evenly-spaced colors Uses the new HSLUV colorspace :param length: Total number of entries in the final gradient :param colors: Color stops, varargs :return: List of colors in the gradient """ luv_colors = [rgb_to_hsluv(to_color(x).rgb) for x in colors] luv_colors.append(luv_colors[0]) steps = max(len(luv_colors), math.floor(length / (len(luv_colors)))) gradient = [] for color_idx in range(0, len(luv_colors) - 1): start = luv_colors[color_idx] end = luv_colors[(color_idx + 1)] for interp in range(0, steps): amount = float(interp) / float(steps) i = ColorUtils._circular_interp(start, end, amount) gradient.append( Color.NewFromRgb(*hsluv_to_rgb([i[0], i[1], i[2]]))) return gradient
def random_color(): time.sleep(2) from random import randint pixels = [] for x in range(512): r, g, b = hsluv.hsluv_to_rgb([randint(0,360), randint(50,101), randint(40,60)]) pixels.append((r*256, g*256, b*256)) return pixels
def from_hsl(self, *args): """ Specify a color from a hue, saturation and luminosity triplet """ if len(args) == 1: args, = args h, s, l = args self.from_rgb(*hsluv.hsluv_to_rgb((h, s, l)))
def generate_img12(name): hue = np.random.random() * 360 bg_color = hsluv.hsluv_to_rgb([ hue, 50 + np.random.random() * 50, 50 + np.random.random() * 50, ]) bg_color = tuple(int(x * 256) for x in bg_color) text_color = hsluv.hsluv_to_rgb([ (hue + 120 + np.random.random() * 120) % 360, 50 + np.random.random() * 50, np.random.random() * 100, ]) text_color = tuple(int(x * 256) for x in text_color) img1 = generate_img_text(252, 352, bg_color, name, text_color) img2 = generate_img_text(240, 320, bg_color, name, text_color) return img1, img2
def __init__(self, h_pos=20, h_neg=250, saturation=1.0, value=0.7, center="light"): saturation *= 99 value *= 99 start = hsluv_to_rgb([h_neg, saturation, value]) mid = ((0.133, 0.133, 0.133) if center == "dark" else (0.92, 0.92, 0.92)) end = hsluv_to_rgb([h_pos, saturation, value]) colors = ColorArray([start, mid, end]) super(Diverging, self).__init__(colors)
def simplex_hsl_as_rgb(x, y, z, w): x = x * simplex_scale_x y = y * simplex_scale_y z = z * simplex_scale_z h = (simplex_a.noise4d(x, y, z, w)+1)*360 s = 100-(simplex_b.noise4d(x, y, z, w)+1)*5 l = 50+(simplex_c.noise4d(x, y, z, w))*5 r, g, b = hsluv.hsluv_to_rgb([h, s, l]) return (r*256, g*256, b*256)
def text_to_colour(text: str) -> RGBf: MASK = 0xffff h = hashlib.sha1() h.update(text.encode("utf-8")) hue = (int.from_bytes(h.digest()[:2], "little") & MASK) / MASK r, g, b = hsluv.hsluv_to_rgb((hue * 360, 75, 60)) # print(text, cb, cr, r, g, b) r, g, b = clip_rgb(r, g, b) return r, g, b
def colourComponents(image): max = image.max() result = numpy.zeros(numpy.append(image.shape, 3)) for y in xrange(image.shape[0]): for x in xrange(image.shape[1]): if image[y, x] != 0: # Since hue is [0, 360) and 67 is coprime to 360, this loops # through all 360 integer hue values before repeating, while # avoiding the issue of hue difference being small for small # differences in component number result[y, x] = numpy.array( hsluv_to_rgb((image[y, x] * 67, 100, 50))) * 255 return result
def make_anglemap(N=256, use_hpl=True): h = np.ones(N) # hue h[:N // 2] = 11.6 # red h[N // 2:] = 258.6 # blue s = 100 # saturation l = np.linspace(0, 100, N // 2) # luminosity l = np.hstack((l, l[::-1])) colorlist = np.zeros((N, 3)) for ii in range(N): if use_hpl: colorlist[ii, :] = hsluv.hpluv_to_rgb((h[ii], s, l[ii])) else: colorlist[ii, :] = hsluv.hsluv_to_rgb((h[ii], s, l[ii])) colorlist[colorlist > 1] = 1 # correct numeric errors colorlist[colorlist < 0] = 0 return col.ListedColormap(colorlist)
def apply_filter(self, color_image, opacity_image, frame_number): curr_opacity = self.opacity_interp_func(frame_number) curr_h = self.color_h_interp_func(frame_number) curr_s = self.color_s_interp_func(frame_number) curr_l = self.color_l_interp_func(frame_number) curr_rgb_tuple = hsluv_to_rgb((curr_h, curr_s, curr_l)) curr_rgb_array = np.clip( np.array([curr_rgb_tuple[0], curr_rgb_tuple[1], curr_rgb_tuple[2]]) * 255, 0, 255).astype("uint8").reshape((1, 1, 3)) opacity_image[:, :] = curr_opacity color_image[:, :, 0] = curr_rgb_array[0, 0, 0] color_image[:, :, 1] = curr_rgb_array[0, 0, 1] color_image[:, :, 2] = curr_rgb_array[0, 0, 2] return
def __init__(self, ncolors=6, hue_start=0, saturation=1.0, value=0.7, controls=None, interpolation='linear'): hues = np.linspace(0, 360, ncolors + 1)[:-1] hues += hue_start hues %= 360 saturation *= 99 value *= 99 colors = ColorArray( [hsluv_to_rgb([hue, saturation, value]) for hue in hues], ) super(HSLuv, self).__init__(colors, controls=controls, interpolation=interpolation)
def ripple(): now = time.time() a = (math.sin(-now*6.28)*6+(now*3.14*2))%360. pixels = [] center_x = max_x/2 center_y = max_y/2 center_z = max_z/2 for x,y,z in lightmap: dist = math.sqrt( (max_x-x)**2 + (max_y-y)**2 + (max_z-z)**2) off_a = (math.sin((dist+now*3.14)/3.14)**4) off_b = (math.sin((dist/10+now*3.14)/3.14)**4) h = a+60*off_a-20*off_b+30*(math.sin(-now)) s = 99 + math.sin(now*3.14/5)*1 l = 50 + math.sin(now*3.14/15)*5 r,g,b = [x * 256. for x in hsluv.hsluv_to_rgb([h, s, l])] pixels.append((r,g,b)) return pixels
def hsv_gradient(color1: ColorType, color2: ColorType, steps: int) -> list: """ Generate a gradient between two points in HSV colorspace :param color1: Starting color :param color2: Ending color :param steps: Number of steps in the gradient :param loop: If the gradient should "loop" back around to it's starting point :return: List of colors in the gradient """ start = ColorUtils._hsva(color1) end = ColorUtils._hsva(color2) gradient = [] for x in range(0, steps): amount = float(x) / float(steps - 1) i = ColorUtils._circular_interp(start, end, amount) gradient.append(Color.NewFromRgb(*hsluv_to_rgb([i[0], i[1], i[2]]))) return gradient
def channel(c, channel=0, amt=1): """Increment a rgb channel""" rgb = hsluv.hsluv_to_rgb(c) rgb[channel] = max(0, min(1, rgb[channel] + amt / 255)) return hsluv.rgb_to_hsluv(rgb)
def getColor(cls): cls.seed = (cls.seed + golden_ratio_conjugate) % 1 hue = 360 * cls.seed sat = random.uniform(cls.minS, cls.maxS) lum = random.uniform(cls.minL, cls.maxL) return hsluv_to_rgb([hue, sat, lum])
def obs_color(obs, subobs): """ Return a nice color for the given observable. """ return hsluv.hsluv_to_rgb(obs_color_hsluv(obs, subobs))
rip_tsd = data['swr'][0]['rip_tsd'] rip_spikes = data['swr'][0]['rip_spikes'] times = data['swr'][0]['times'] wakangle = data['swr'][0]['wakangle'] neurons = data['swr'][0]['neurons'] tcurves = data['swr'][0]['tcurves'] irand = data['rnd'][0]['irand'] iwak2 = data['rnd'][0]['iwak2'] tcurves = tcurves.rolling(window=100,win_type='gaussian',center=True,min_periods=1).mean(std=1.0) H = wakangle.values/(2*np.pi) HSV = np.vstack((H*360, np.ones_like(H)*85, np.ones_like(H)*45)).T RGB = np.array([hsluv.hsluv_to_rgb(HSV[i]) for i in range(len(HSV))]) if n < 4: subplot(outergs[0,n]) else: subplot(outergs[1,n%4]) gca().axis('off') # gca().text(-0.1, 0.94, "c", transform = gca().transAxes, fontsize = 10, fontweight='bold') gca().set_aspect(aspect=1) for i in range(len(iswr)): scatter(iswr[i,:,0], iswr[i,:,1], c = 'lightgrey', marker = '.', alpha = 0.7, zorder = 2, linewidth = 0, s= 40) scatter(iwak[~np.isnan(H),0], iwak[~np.isnan(H),1], c = RGB[~np.isnan(H)], marker = '.', alpha = 0.5, zorder = 2, linewidth = 0, s= 40) if f == 'Mouse17-130129.pickle':
def hsluv2rgb_vec(h, s, l): ret = [] for h_, s_, l_, in zip(h.ravel(), s.ravel(), l.ravel()): ret.append(hsluv.hsluv_to_rgb([h_, s_, l_])) return np.array(ret).reshape(h.shape + (3, ))
def rgba(self) -> ColorTuple: r, g, b = hsluv_to_rgb(self.hsluva) return r * 255, g * 255, b * 255, self.alpha
def converthsv(hsv): t = hsluv.hsluv_to_rgb(hsv) i = tuple(int(i * 255) for i in t) return i
tcurves = tcurves.rolling(window=100,win_type='gaussian',center=True,min_periods=1).mean(std=1.0) # rip_tsd = pd.Serrip_tsd.index.values) colors = np.hstack((np.linspace(0, 1, int(len(times)/2)), np.ones(1), np.linspace(0, 1, int(len(times)/2))[::-1])) colors = np.arange(len(times)) H = wakangle.values/(2*np.pi) HSV = np.vstack((H*360, np.ones_like(H)*85, np.ones_like(H)*45)).T # from matplotlib.colors import hsv_to_rgb # RGB = hsv_to_rgb(HSV) RGB = np.array([hsluv.hsluv_to_rgb(HSV[i]) for i in range(len(HSV))]) # 4644.8144 # 4924.4720 # 5244.9392 # 7222.9480 # 7780.2968 # 11110.1888 # 11292.3240 # 11874.5688 good_ex = (np.array([4644.8144,4924.4720,5244.9392,7222.9480,7780.2968,11110.1888,11292.3240,11874.5688])*1e6).astype('int') exemple = [np.where(i == rip_tsd.index.values)[0][0] for i in [good_ex[0],good_ex[1],good_ex[2]]] # normwak = np.sqrt(np.sum(np.power(iwak,2), 1))
gs_top = gridspec.GridSpecFromSubplotSpec( 4, 5, subplot_spec=outergs[0, 0], wspace=0.3, hspace=0.5, width_ratios=[0.1, 0.1, 0.1, 0.01, 0.1]) for i in range(3): n1, n2 = groups[i][pair_index[i]] subplot(gs_top[0, i], projection='polar') gca().grid(zorder=0) xticks([0, np.pi / 2, np.pi, 3 * np.pi / 2], []) yticks([]) for n in [n1, n2]: clr = hsluv.hsluv_to_rgb([peaks[n] * 180 / np.pi, 85, 45]) tmp = tcurves[n].values tmp /= tmp.max() fill_between(tcurves[n].index.values, np.zeros_like(tmp), tmp, color=clr, alpha=0.5, linewidth=1, zorder=2) for i, epoch, cc in zip(range(3), ['WAKE', 'REM', 'NREM'], [cc_wak, cc_rem, cc_sws]): for j in range(3): nn = groups[j][pair_index[j]] subplot(gs_top[i + 1, j])
#!/data/data/com.termux/files/usr/bin/env python3 from sys import argv, stdout, stderr import hsluv stdout.buffer.write(b"P6\n1 256\n255\n") h, s, luv = hsluv.hex_to_hsluv(argv[1]) print("\n\n\n", h, s, luv, "\n\n", file=stderr) for i in range(256): stdout.buffer.write( bytes( map( lambda x: int(x * 255 + 0.5), hsluv.hsluv_to_rgb( (h, s, ((i / 255) * 100 + ((luv - 50) / 3 if s == 0 else 0)))))))
# rip_tsd = pd.Serrip_tsd.index.values) colors = np.hstack((np.linspace(0, 1, int(len(times) / 2)), np.ones(1), np.linspace(0, 1, int(len(times) / 2))[::-1])) colors = np.arange(len(times)) H = wakangle.values / (2 * np.pi) HSV = np.vstack((H * 360, np.ones_like(H) * 85, np.ones_like(H) * 45)).T # from matplotlib.colors import hsv_to_rgb # RGB = hsv_to_rgb(HSV) RGB = np.array([hsluv.hsluv_to_rgb(HSV[i]) for i in range(len(HSV))]) # 4644.8144 # 4924.4720 # 5244.9392 # 7222.9480 # 7780.2968 # 11110.1888 # 11292.3240 # 11874.5688 good_ex = (np.array([ 4644.8144, 4924.4720, 5244.9392, 7222.9480, 7780.2968, 11110.1888, 11292.3240, 11874.5688 ]) * 1e6).astype('int')
import hsluv # from https://github.com/hsluv/hsluv-python import numpy as np npoints = 255 hsluv_data = [] hpluv_data = [] hues = np.linspace(0, 360, npoints, endpoint=False) for h in hues: hsluv_data.append(hsluv.hsluv_to_rgb([h, 100., 60.])) hpluv_data.append(hsluv.hpluv_to_rgb([h, 100., 60.])) hsluv_data = np.array(hsluv_data) hpluv_data = np.array(hpluv_data) np.savetxt('hsluv.txt', hsluv_data, fmt='%.15g') np.savetxt('hpluv.txt', hpluv_data, fmt='%.15g')
def plot_secant_manifold(self, plot_extrema=True): import matplotlib.pyplot as plt # from colorsys import hls_to_rgb from hsluv import hsluv_to_rgb, hpluv_to_rgb from scipy.special import erfinv # import pyknotid.hsluvcolormap # causes hsluv to be registered points = self.points colours = np.ones((len(points), len(points), 3)) heights = np.zeros((len(points), len(points))) thetas = [] phis = [] for i1, point in enumerate(points): for i2, other_point in enumerate(points[i1+1:]): i2 += i1 + 1 direction = other_point - point theta = np.arccos(direction[2] / mag(direction)) phi = np.arctan2(direction[1], direction[0]) # colours[i2, i1] = hls_to_rgb((phi + np.pi) / (2*np.pi), erfinv((theta / np.pi) * 2 - 1.) / 4.4 + 0.5, 1) colours[i2, i1] = hsluv_to_rgb((360 * (phi + np.pi) / (2*np.pi), 100, 65))# * (erfinv((theta / np.pi) * 2 - 1.) / 4.4 + 0.5))) colours[i1, i2] = hsluv_to_rgb((360 * ((phi + 2*np.pi) % (2*np.pi)) / (2*np.pi), 100, 65)) phis.append(phi) thetas.append(theta) heights[i2, i1] = theta heights[i1, i2] = np.pi - theta print(np.min(phis), np.max(phis), np.min(thetas), np.max(thetas)) fig, ax = plt.subplots() im = ax.imshow(colours, origin='lower', zorder=-1) # ax.contour(heights, cmap='Greys', levels=np.linspace(-1, 1, 13)) ax.contour(heights, cmap='Greys_r', levels=np.linspace(0, np.pi, 11), zorder=0) crossings = self.raw_crossings() # Plot the lines between crossings unique_crossings = [] crossings_done = set() for crossing in crossings: if crossing[0] in crossings_done: continue crossings_done.add(crossing[1]) unique_crossings.append(crossing) for i, crossing in enumerate(unique_crossings): start1, end1, height1, sign1 = crossing for other_crossing in unique_crossings[i+1:]: start2, end2, height2, sign2 = other_crossing if not (start2 > start1 and end1 > start2 and end2 > end1): continue colour = 'crimson' if sign1 * sign2 > 0 else 'lime' ax.plot([start1, start2], [end1, end2], color=colour, zorder=1) # Plot the crossing points for crossing in crossings: if crossing[1] > crossing[0]: colour = 'crimson' if crossing[3] > 0 else 'lime' edge_colour = 'white' if crossing[2] > 0 else 'black' ax.scatter([crossing[0]], [crossing[1]], color=colour, edgecolors=edge_colour, s=30, zorder=2) # Plot extrema of the planar projection zs = points[:, 1] maxima_indices = np.argwhere((zs > np.roll(zs, 1)) & (zs > np.roll(zs, -1))).T[0] minima_indices = np.argwhere((zs < np.roll(zs, 1)) & (zs < np.roll(zs, -1))).T[0] print('maxima indices', maxima_indices) print('minima indices', minima_indices) for maximum in maxima_indices: ax.scatter([maximum], [maximum], color='purple', edgecolors='pink', zorder=5) for minimum in minima_indices: ax.scatter([minimum], [minimum], color='cyan', edgecolors='pink', zorder=5) xs = np.arange(len(points)) ax.plot(xs, xs, linewidth=8, color='black', zorder=4) ax.set_xticks([]) ax.set_yticks([]) fig.tight_layout() # Plot the knot projection inset from mpl_toolkits.axes_grid1.inset_locator import inset_axes inset_ax = inset_axes(ax, width="45%", height="45%", loc=4) # inset_ax = fig.add_axes([0.6, 0.1, 0.4, 0.4]) self.plot_projection(fig_ax=(fig, inset_ax)) # inset_ax.set_axis_off() inset_ax.set_xticks([]) inset_ax.set_yticks([]) inset_ax.patch.set_alpha(0.5) ax.set_xlim(0.5, len(points) - 0.5) ax.set_ylim(0.5, len(points) - 0.5) ax.set_ylabel('i2') ax.set_xlabel('i1') return fig, ax