Last active
March 13, 2019 15:04
-
-
Save GuillaumeFavelier/7ef040db9ae98a9d14f1da21af7b3e57 to your computer and use it in GitHub Desktop.
Function to generate a set of colors as distinct as possible in VisPy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Ported from: http://www.mathworks.com/matlabcentral/fileexchange/29702-generate-maximally-perceptually-distinct-colors | |
import sys | |
import numpy as np | |
from vispy import scene | |
from vispy.color import ColorArray | |
from vispy.color.color_array import _rgb_to_lab | |
def distinguishable_colors(ncolors, bg=[0, 0, 0]): | |
n_grid = 30 | |
x = np.linspace(0, 1, n_grid) | |
R, G, B = np.meshgrid(x, x, x) | |
rgb = np.column_stack((R.flatten(), | |
G.flatten(), | |
B.flatten())).astype(np.float32) | |
lab = _rgb_to_lab(rgb) | |
bglab = np.array(bg).astype(np.float32) | |
bglab = _rgb_to_lab(bglab) | |
mindist2 = np.full(rgb.shape[0], float('Inf')) | |
for i in range(0, bglab.shape[0]): | |
dX = lab - bglab[i, :] | |
dist2 = np.sum(dX**2, axis=1) | |
mindist2 = np.minimum(dist2, mindist2) | |
colors = np.zeros((ncolors, 3)) | |
lastlab = bglab[-1, :] | |
for i in range(0, ncolors): | |
dX = lab - lastlab | |
dist2 = np.sum(dX**2, axis=1) | |
mindist2 = np.minimum(dist2, mindist2) | |
index = mindist2.argmax() | |
colors[i, :] = rgb[index, :] | |
lastlab = lab[index, :] | |
return ColorArray(color=colors[0:ncolors, :]) | |
canvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True) | |
view = canvas.central_widget.add_view() | |
npoints = 50 | |
delta = 0.1 | |
points = np.array([[i*delta, 0, 0] for i in range(1, npoints)]).astype(np.float32) | |
color = distinguishable_colors(npoints) | |
scene.visuals.Tube(points, color=color, parent=view.scene) | |
view.camera = scene.cameras.ArcballCamera(fov=60, parent=view.scene) | |
if __name__ == '__main__' and sys.flags.interactive == 0: | |
canvas.app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment