def test_colormap(): """Test named colormaps.""" autumn = get_colormap('autumn') assert autumn.glsl_map is not "" assert len(autumn[0.]) == 1 assert len(autumn[0.5]) == 1 assert len(autumn[1.]) == 1 assert len(autumn[[0., 0.5, 1.]]) == 3 assert len(autumn[np.array([0., 0.5, 1.])]) == 3 fire = get_colormap('fire') assert_array_equal(fire[0].rgba, np.ones((1, 4))) assert_array_equal(fire[1].rgba, np.array([[1, 0, 0, 1]])) grays = get_colormap('grays') assert_array_equal(grays[.5].rgb, np.ones((1, 3)) * .5) hot = get_colormap('hot') assert_allclose(hot[0].rgba, [[0, 0, 0, 1]], 1e-6, 1e-6) assert_allclose(hot[0.5].rgba, [[1, .52272022, 0, 1]], 1e-6, 1e-6) assert_allclose(hot[1.].rgba, [[1, 1, 1, 1]], 1e-6, 1e-6) # Test the GLSL and Python mapping. for name in get_colormaps(): colormap = get_colormap(name) Function(colormap.glsl_map) colors = colormap[np.linspace(-2., 2., 50)] assert colors.rgba.min() >= 0 assert colors.rgba.max() <= 1
def vispy_or_mpl_colormap(name): """Try to get a colormap from vispy, or convert an mpl one to vispy format. Parameters ---------- name : str The name of the colormap. Returns ------- cmap : vispy.color.Colormap The found colormap. Raises ------ KeyError If no colormap with that name is found within vispy or matplotlib. """ vispy_cmaps = get_colormaps() if name in vispy_cmaps: cmap = get_colormap(name) else: try: mpl_cmap = getattr(cm, name) except AttributeError: raise KeyError(f'Colormap "{name}" not found in either vispy ' 'or matplotlib.') mpl_colors = mpl_cmap(np.linspace(0, 1, 256)) cmap = Colormap(mpl_colors) return cmap
import sip import pickle from trainingGui import * from functions import * import glob from makehdf5 import makehdf5 from tf_lstm import lstm from waveletTransform import wavelet_transform as wavelet_trans import os from serialRedis import redis_serial from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas import matplotlib.pyplot as plt from betaGui import betaGui from plots import plots as plots_info get_colormaps() class RawPlot(scene.SceneCanvas): def __init__(self, time, pos, dt, apply_redis, size=(1400, 700)): """ pos is a Matrix (nChan * Time) """ scene.SceneCanvas.__init__(self, keys="interactive", size=size) self.unfreeze() # allow the creation of new attribute to the clas self.grid = self.central_widget.add_grid() #layout definition self.training_window = Second() # Display parameters self.raw_wind_size = 1200 self.alpha_wind_size = 1200 self.raw_interline = 10
vec4 translucent_fire(float t) { return vec4(pow(t, 0.5), t, t*t, max(0, t*1.05 - 0.05)); } """ class TransGrays(BaseColormap): glsl_map = """ vec4 translucent_grays(float t) { return vec4(t, t, t, t*0.05); } """ # Setup colormap iterators opaque_cmaps = cycle(get_colormaps()) translucent_cmaps = cycle([TransFire(), TransGrays()]) opaque_cmap = next(opaque_cmaps) translucent_cmap = next(translucent_cmaps) # Implement axis connection with cam2 @canvas.events.mouse_move.connect def on_mouse_move(event): if event.button == 1 and event.is_dragging: axis.transform.reset() axis.transform.rotate(cam2.roll, (0, 0, 1)) axis.transform.rotate(cam2.elevation, (1, 0, 0)) axis.transform.rotate(cam2.azimuth, (0, 1, 0))
inferno=trans._p('colormap', 'inferno'), plasma=trans._p('colormap', 'plasma'), gray=trans._p('colormap', 'gray'), gray_r=trans._p('colormap', 'gray r'), hsv=trans._p('colormap', 'hsv'), turbo=trans._p('colormap', 'turbo'), twilight=trans._p('colormap', 'twilight'), twilight_shifted=trans._p('colormap', 'twilight shifted'), gist_earth=trans._p('colormap', 'gist earth'), PiYG=trans._p('colormap', 'PiYG'), ) _MATPLOTLIB_COLORMAP_NAMES_REVERSE = { v: k for k, v in matplotlib_colormaps.items() } _VISPY_COLORMAPS_ORIGINAL = _VCO = get_colormaps() _VISPY_COLORMAPS_TRANSLATIONS = OrderedDict( autumn=(trans._p('colormap', 'autumn'), _VCO['autumn']), blues=(trans._p('colormap', 'blues'), _VCO['blues']), cool=(trans._p('colormap', 'cool'), _VCO['cool']), greens=(trans._p('colormap', 'greens'), _VCO['greens']), reds=(trans._p('colormap', 'reds'), _VCO['reds']), spring=(trans._p('colormap', 'spring'), _VCO['spring']), summer=(trans._p('colormap', 'summer'), _VCO['summer']), fire=(trans._p('colormap', 'fire'), _VCO['fire']), grays=(trans._p('colormap', 'grays'), _VCO['grays']), hot=(trans._p('colormap', 'hot'), _VCO['hot']), ice=(trans._p('colormap', 'ice'), _VCO['ice']), winter=(trans._p('colormap', 'winter'), _VCO['winter']), light_blues=(trans._p('colormap', 'light blues'), _VCO['light_blues']), orange=(trans._p('colormap', 'orange'), _VCO['orange']),
# vispy: gallery 30 # ----------------------------------------------------------------------------- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- """ Demonstration of various features of Line visual. """ import itertools import numpy as np from vispy import app, scene from vispy.color import get_colormaps from vispy.visuals.transforms import STTransform colormaps = itertools.cycle(get_colormaps()) # vertex positions of data to draw N = 200 pos = np.zeros((N, 2), dtype=np.float32) pos[:, 0] = np.linspace(10, 390, N) pos[:, 1] = np.random.normal(size=N, scale=20, loc=0) canvas = scene.SceneCanvas(keys='interactive', size=(400, 200), show=True) # Create a visual that updates the line with different colormaps color = next(colormaps) line = scene.Line(pos=pos, color=color, method='gl') line.transform = STTransform(translate=[0, 140]) line.parent = canvas.central_widget
# ----------------------------------------------------------------------------- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- """ Demonstration of various features of Line visual. """ import itertools import numpy as np from vispy import app, scene from vispy.color import get_colormaps from vispy.visuals.transforms import STTransform from vispy.ext.six import next colormaps = itertools.cycle(get_colormaps()) # vertex positions of data to draw N = 200 pos = np.zeros((N, 2), dtype=np.float32) pos[:, 0] = np.linspace(10, 390, N) pos[:, 1] = np.random.normal(size=N, scale=20, loc=0) canvas = scene.SceneCanvas(keys='interactive', size=(400, 200), show=True) # Create a visual that updates the line with different colormaps color = next(colormaps) line = scene.Line(pos=pos, color=color, method='gl') line.transform = STTransform(translate=[0, 140]) line.parent = canvas.central_widget
glsl_map = """ vec4 translucent_fire(float t) { return vec4(pow(t, 0.5), t, t*t, max(0, t*1.05 - 0.05)); } """ class TransGrays(BaseColormap): glsl_map = """ vec4 translucent_grays(float t) { return vec4(t, t, t, t*0.05); } """ # Setup colormap iterators opaque_cmaps = cycle(get_colormaps()) translucent_cmaps = cycle([TransFire(), TransGrays()]) opaque_cmap = next(opaque_cmaps) translucent_cmap = next(translucent_cmaps) # Implement key presses @canvas.events.key_press.connect def on_key_press(event): global opaque_cmap, translucent_cmap if event.text == '1': cam_toggle = {cam1: cam2, cam2: cam3, cam3: cam1} view.camera = cam_toggle.get(view.camera, cam2) print(view.camera.name + ' camera') elif event.text == '2': methods = ['mip', 'translucent', 'iso', 'additive']
""" from itertools import cycle import numpy as np from vispy import app, scene, io from vispy.color import get_colormaps # Read volume vol1 = np.load(io.load_data_file('volume/stent.npz'))['arr_0'] vol2 = np.load(io.load_data_file('brain/mri.npz'))['data'] vol2 = np.flipud(np.rollaxis(vol2, 1)) # Setup colormaps cmaps = cycle(get_colormaps()) # Prepare canvas canvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True) canvas.measure_fps() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Set whether we are emulating a 3D texture emulate_texture = True # Create the volume visuals, only one is visible volume1 = scene.visuals.Volume(vol1, parent=view.scene, threshold=0.5, emulate_texture=emulate_texture) volume1.transform = scene.STTransform(translate=(64, 64, 0))
def __init__(self, parent): super(SpectrogramTools, self).__init__(parent) self.spectrogram = self.parent().plugin.signal_widget.spectrogram layout = QFormLayout() self.n_fft_le = QLineEdit(str(self.spectrogram.n_fft)) self.n_fft_le_validator = QIntValidator(8, 1024) self.n_fft_le.setValidator(self.n_fft_le_validator) layout.addRow('NFFT', self.n_fft_le) self.n_fft_le.editingFinished.connect(self.set_n_fft) self.step_le = QLineEdit(str(self.spectrogram.step)) self.step_le_validator = QIntValidator(1, 128) self.step_le.setValidator(self.step_le_validator) layout.addRow('Step', self.step_le) self.step_le.editingFinished.connect(self.set_step) self.cmap_cb = QComboBox() layout.addRow('Colormap', self.cmap_cb) # curr_cmap = [x[0] for x in color.get_colormaps().items() \ # if x[1] == self.spectrogram.cmap][0] cmap_list = list(color.get_colormaps().keys()) cmap_list.sort() # curr_idx = cmap_list.index(curr_cmap) self.cmap_cb.addItems(cmap_list) # self.cmap_cb.setCurrentIndex(curr_idx) self.cmap_cb.currentIndexChanged.connect(self.set_cmap) self.interp_cb = QComboBox() layout.addRow('Interpolation', self.interp_cb) interp_list = [ 'nearest', 'bilinear', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'bicubic', 'catrom', 'mitchell', 'spline16', 'spline36', 'gaussian', 'bessel', 'sinc', 'lanczos', 'blackman' ] self.interp_cb.addItems(interp_list) self.interp_cb.currentIndexChanged.connect(self.set_interpolation) self.normalize_chb = QCheckBox() layout.addRow('Normalize', self.normalize_chb) self.normalize_chb.setCheckState(self.spectrogram.normalize) self.normalize_chb.stateChanged.connect(self.set_normalize) clim_low_layout = QHBoxLayout() self.clim_low_s = QSlider(Qt.Horizontal) self.clim_low_s.setMinimum(0) self.clim_low_s.setMaximum(100) self.clim_low_s.setValue(0) self.clim_low_s.setTickInterval(1) self.clim_low_s.valueChanged.connect(self.set_clim_low_s) self.clim_low_le = QLineEdit('0') self.clim_low_le_validator = QIntValidator(1, 100) self.clim_low_le.setValidator(self.clim_low_le_validator) self.clim_low_le.editingFinished.connect(self.set_clim) self.clim_low_le.setMaximumWidth(40) clim_low_layout.addWidget(self.clim_low_s) clim_low_layout.addWidget(self.clim_low_le) layout.addRow('Color limit low', clim_low_layout) clim_high_layout = QHBoxLayout() self.clim_high_s = QSlider(Qt.Horizontal) self.clim_high_s.setMinimum(0) self.clim_high_s.setMaximum(100) self.clim_high_s.setValue(100) self.clim_high_s.setTickInterval(1) self.clim_high_s.valueChanged.connect(self.set_clim_high_s) self.clim_high_le = QLineEdit('100') self.clim_high_le_validator = QIntValidator(1, 100) self.clim_high_le.setValidator(self.clim_high_le_validator) self.clim_high_le.editingFinished.connect(self.set_clim) self.clim_high_le.setMaximumWidth(40) clim_high_layout.addWidget(self.clim_high_s) clim_high_layout.addWidget(self.clim_high_le) layout.addRow('Color limit high', clim_high_layout) self.setLayout(layout)
color_lev='k', parent=vb2.scene) curve2b = scene.visuals.Isocurve(myfunc, levels=levels2, color_lev='cubehelix', parent=vb4.scene) # set viewport vb3.camera.set_range((0, 100), (0, 100)) vb4.camera.set_range((0, 100), (0, 100)) # setup update parameters up = 1 index = 1 clip = np.linspace(myfunc.min(), myfunc.max(), num=51) cmap = cycle(get_colormaps()) color = cycle(get_color_names()) def update(ev): global myfunc, index, up, levels2, noise, cmap, color if index > 0 and index < 25: # update left panes rolling upwards noise = np.roll(noise, 1, axis=0) image1.set_data(noise) curve1a.set_data(noise) curve1b.set_data(noise) # update colors/colormap if (index % 5) == 0:
def scene_building(recon_algos): # Prepare canvas canvas = scene.SceneCanvas(keys='interactive', size=(1024, 768), show=True) # canvas.measure_fps() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Set whether we are emulating a 3D texture emulate_texture = False # Create the volume visuals for the different reconstructions volume1 = scene.visuals.Volume(recon_algos[0], parent=view.scene, threshold=0.225, emulate_texture=emulate_texture) volume2 = scene.visuals.Volume(recon_algos[1], parent=view.scene, threshold=0.225, emulate_texture=emulate_texture) volume3 = scene.visuals.Volume(recon_algos[2], parent=view.scene, threshold=0.225, emulate_texture=emulate_texture) volume4 = scene.visuals.Volume(recon_algos[3], parent=view.scene, threshold=0.225, emulate_texture=emulate_texture) volume5 = scene.visuals.Volume(recon_algos[4], parent=view.scene, threshold=0.225, emulate_texture=emulate_texture) #volume1.transform = scene.STTransform(translate=(64, 64, 0)) # Hacky cyclic volume display setup: volume1.visible = True # set first volume as visible, then switch with 3 volume2.visible = False volume3.visible = False volume4.visible = False volume5.visible = False t1 = Text('ART reconstruction', parent=canvas.scene, color='white') t1.font_size = 18 t1.pos = canvas.size[0] // 2, canvas.size[1] - 10 t2 = Text('fbp reconstruction', parent=canvas.scene, color='white') t2.font_size = 18 t2.pos = canvas.size[0] // 2, canvas.size[1] - 10 t3 = Text('sirt reconstruction', parent=canvas.scene, color='white') t3.font_size = 18 t3.pos = canvas.size[0] // 2, canvas.size[1] - 10 t4 = Text('ospml_quad reconstruction', parent=canvas.scene, color='white') t4.font_size = 18 t4.pos = canvas.size[0] // 2, canvas.size[1] - 10 t5 = Text('pml_quad reconstruction', parent=canvas.scene, color='white') t5.font_size = 18 t5.pos = canvas.size[0] // 2, canvas.size[1] - 10 t1.visible = True t2.visible = False t3.visible = False t4.visible = False t5.visible = False # Implement axis connection with cam2 @canvas.events.mouse_move.connect def on_mouse_move(event): if event.button == 1 and event.is_dragging: axis.transform.reset() axis.transform.rotate(cam2.roll, (0, 0, 1)) axis.transform.rotate(cam2.elevation, (1, 0, 0)) axis.transform.rotate(cam2.azimuth, (0, 1, 0)) axis.transform.scale((50, 50, 0.001)) axis.transform.translate((50., 50.)) axis.update() # Implement key presses @canvas.events.key_press.connect def on_key_press(event): global opaque_cmap, translucent_cmap if event.text == '1': cam_toggle = {cam1: cam2, cam2: cam3, cam3: cam1} view.camera = cam_toggle.get(view.camera, cam2) print(view.camera.name + ' camera') if view.camera is cam2: axis.visible = True else: axis.visible = False elif event.text == '2': methods = ['mip', 'translucent', 'iso', 'additive'] method = methods[(methods.index(volume1.method) + 1) % 4] print("Volume render method: %s" % method) cmap = opaque_cmap if method in [ 'mip', 'iso'] else translucent_cmap volume1.method = method volume1.cmap = cmap elif event.text == '3': # hacky toogle between different reconstructed volumes if(volume1.visible): volume1.visible = False volume2.visible = True t1.visible = False t2.visible = True # t1.update() elif(volume2.visible): volume2.visible = False volume3.visible = True t2.visible = False t3.visible = True elif(volume3.visible): volume3.visible = False volume4.visible = True t3.visible = False t4.visible = True elif(volume4.visible): volume4.visible = False volume5.visible = True t4.visible = False t5.visible = True else: volume5.visible = False volume1.visible = True t5.visible = False t1.visible = True elif event.text == '4': if volume1.method in ['mip', 'iso']: cmap = opaque_cmap = next(opaque_cmaps) else: cmap = translucent_cmap = next(translucent_cmaps) volume1.cmap = volume2.cmap = volume3.cmap = volume4.cmap volume5.cmap = cmap elif event.text == '0': cam1.set_range() cam3.set_range() elif event.text != '' and event.text in '[]': s = -0.025 if event.text == '[' else 0.025 volume1.threshold += s #volume2.threshold += s th = volume1.threshold if volume1.visible else volume2.threshold print("Isosurface threshold: %0.3f" % th) # for testing performance #@canvas.connect # def on_draw(ev): # canvas.update() # @canvas.connect # def on_timer(ev): # # Animation speed based on global time. # t = event.elapsed # c = Color(self.color).rgb # # Simple sinusoid wave animation. # s = abs(0.5 + 0.5 * math.sin(t)) # self.context.set_clear_color((c[0] * s, c[1] * s, c[2] * s, 1)) # self.update() # Create three cameras (Fly, Turntable and Arcball) fov = 60. cam1 = scene.cameras.FlyCamera(parent=view.scene, fov=fov, name='Fly') cam2 = scene.cameras.TurntableCamera(parent=view.scene, fov=fov, name='Turntable') cam3 = scene.cameras.ArcballCamera( parent=view.scene, fov=fov, name='Arcball') view.camera = cam2 # Select turntable at first # Create an XYZAxis visual axis = scene.visuals.XYZAxis(parent=view) # view.scene tout court s = STTransform(translate=(50, 50), scale=(50, 50, 50, 1)) affine = s.as_affine() axis.transform = affine # Setup colormap iterators opaque_cmaps = cycle(get_colormaps()) translucent_cmaps = cycle([TransFire(), TransGrays()]) opaque_cmap = next(opaque_cmaps) translucent_cmap = next(translucent_cmaps) # TODO: add a colorbar, fix error: AttributeError: module 'vispy.scene' has no attribute 'ColorBarWidget' #grid = canvas.central_widget.add_grid(margin=10) # cbar_widget = scene.ColorBarWidget(cmap=translucent_cmaps, orientation="right") #cmap="cool" # grid.add_widget(cbar_widget) # cbar_widget.pos = (800, 600)#(300, 100) # cbar_widget.border_color = "#212121" # grid.bgcolor = "#ffffff" # Create a rotation transform: # tr = MatrixTransform() #TODO: wait 0.5.0 to re-add MatrixTransform # Let's record a .gif: gif_file = Path("reconstruct_animation.mp4") if gif_file.is_file(): print('reconstruct_animation.mp4 is already in the folder, please delete it to get a new one') else: print('Let\'s record a .mp4 of the reconstructed volume:') n_steps = 450 # 360 step_angle = 0.8 # 1. # [] #0.1 fail, 0, 1 fail, (0.5, 0.5, 0.5)ok rotation_axis = np.array([0, 0, 1]) # rt=scene.AffineTransform() #volume1.transform = rt #volume1.transform.rotate(angle=step_angle, axis=rotation_axis) #volume1.transform.translate([1, 1, 0]) axis.visible = False #view.camera.set_range(x=[-3, 3]) writer = imageio.get_writer( 'reconstruct_animation.mp4', fps=50, quality=8) # TODO: add a progress bar gif_bar = progressbar.ProgressBar( redirect_stdout=True, max_value=n_steps) gif_bar.start() for i in range(n_steps): # * 2): im = canvas.render() writer.append_data(im) view.camera.transform.translate([1.8, -1.8, 0]) view.camera.transform.rotate(step_angle, rotation_axis) #volume1.transform.rotate(angle=step_angle, axis=rotation_axis) gif_bar.update(i) gif_bar.finish() writer.close() axis.visible = True