示例#1
0
    def __init__(self, parent=None, **kwargs):
        """Init."""
        # _____________________ INIT _____________________
        self._n = 1000
        self._ratio = 4 / 5
        CbarBase.__init__(self, **kwargs)

        # _____________________ CANVAS _____________________
        if parent is None:
            # Define a canvas :
            self._canvas = scene.SceneCanvas(keys='interactive',
                                             show=False,
                                             resizable=True,
                                             dpi=600,
                                             bgcolor=self._bgcolor,
                                             size=(300, 900))
            self._wc = self._canvas.central_widget.add_view()
            parent = self._wc.scene
            # Define the camera :
            self._camera = FixedCam(rect=(-1.2, -1.2, 2.4, 2.4))
            self._wc.camera = self._camera
        self.parent = parent

        # _____________________ OBJECTS _____________________
        # --------------------- Node ---------------------
        # Define node parent and limit node :
        self._cbNode = Node(name='Colorbar', parent=parent)
        self._limNode = Node(name='Limits', parent=self._cbNode)
        # Rescale between (-1., 1.) :
        self._rsc = vist.STTransform(scale=(self._width, 2 / self._n, 1),
                                     translate=(0, -1., 0))
        # Set transformation to the node :
        self._cbNode.transform = self._rsc

        # --------------------- Image ---------------------
        self._mImage = visuals.Image(parent=self._cbNode, name='image')

        # --------------------- Border ---------------------
        pos = np.array([[0., 0., -3.], [1., 0., -3.], [1., 0., -3.],
                        [1., self._n, -3.], [1., self._n, -3.],
                        [0., self._n, -3.], [0., self._n, -3.], [0., 0., -3.]])
        self._mBorder = visuals.Line(parent=self._cbNode, name='Border')
        self._mBorder.set_data(pos=pos,
                               width=2.,
                               connect='segments',
                               color=self._txtcolor)
        self._mBorder.visible = self._border

        # --------------------- Labels ---------------------
        # Clim labels :
        self._mClimM = visuals.Text(parent=self._limNode,
                                    color=self._txtcolor,
                                    font_size=self._txtsz,
                                    name='Clim_M',
                                    anchor_x='left')
        self._mClimm = visuals.Text(parent=self._limNode,
                                    color=self._txtcolor,
                                    font_size=self._txtsz,
                                    name='Clim_m',
                                    anchor_x='left')

        # Cblabel :
        self._mcblabel = visuals.Text(parent=self._limNode,
                                      name='Cblabel',
                                      color=self._txtcolor,
                                      anchor_x='center',
                                      font_size=self._cbtxtsz)
        self._mcblabel.rotation = -90

        # Vmin/Vmax :
        self._vmMNode = Node(name='VminVmax', parent=self._limNode)
        self._mVm = visuals.Text(parent=self._vmMNode,
                                 color=self._txtcolor,
                                 font_size=self._ratio * self._txtsz,
                                 name='Vmin',
                                 anchor_x='left')
        self._mVM = visuals.Text(parent=self._vmMNode,
                                 color=self._txtcolor,
                                 font_size=self._ratio * self._txtsz,
                                 name='Vmax',
                                 anchor_x='left')

        # Build colorbar :
        self._build(True, 'all')
示例#2
0
# vispy: gallery 30
# -----------------------------------------------------------------------------
# Copyright (c) 2015, Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
"""
Demonstrate the use of the vispy console. Note how the console size is
independent of the canvas scaling.
"""
import sys

from vispy import scene, app
from vispy.scene.widgets import Console
from vispy.scene.visuals import Text

canvas = scene.SceneCanvas(keys='interactive', size=(400, 400))
grid = canvas.central_widget.add_grid()

vb = scene.widgets.ViewBox(border_color='b')
vb.camera = 'panzoom'
vb.camera.rect = -1, -1, 2, 2
grid.add_widget(vb, row=0, col=0)
text = Text('Starting timer...', color='w', font_size=24, parent=vb.scene)

console = Console(text_color='g', font_size=12., border_color='g')
grid.add_widget(console, row=1, col=0)


def on_timer(event):
    text.text = 'Tick #%s' % event.iteration
    if event.iteration > 1 and event.iteration % 10 == 0:
示例#3
0
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

text = scene.Text(color,
                  bold=True,
                  font_size=24,
                  color='w',
                  pos=(200, 40),
                  parent=canvas.central_widget)

print(density, density.shape)


def get_min_and_max(array):
    return float("%.4g" % np.nanmin(array)), float("%.4g" % np.nanmax(array))


#-----------
# For volume data, it's kind of already 'gridded'

trans = (-(xmax - xmin) / 2.0, -(ymax - ymin) / 2.0, -(zmax - zmin) / 2.0)
sur_scale = [(xmax - xmin) / 50., (ymax - ymin) / 50., (zmax - zmin) / 50.]

# Create a canvas with a 3D viewport
canvas = scene.SceneCanvas(keys='interactive',
                           config={'depth_size': 24},
                           bgcolor='white')
view = canvas.central_widget.add_view()

surface = scene.visuals.Isosurface(density,
                                   level=density.max() / 2.,
                                   shading=None,
                                   color=(0.5, 0.6, 1, 0.5),
                                   parent=view.scene)
# surface.transform = scene.transforms.STTransform(translate=(-len(X)/2., -len(Y)/2., -len(Z)/2.))
surface.set_gl_state(depth_test=True, cull_face=True)
surface.transform = scene.STTransform(translate=trans, scale=sur_scale)

surface2 = scene.visuals.Isosurface(density,
                                    level=density.max() / 4.,
                                    shading=None,
示例#5
0
# gloo.gl.use('desktop debug')

# Create lines for use in ndc and pixel coordinates
N = 1000
color = np.ones((N, 4), dtype=np.float32)
color[:, 0] = np.linspace(0, 1, N)
color[:, 1] = color[::-1, 0]

pos = np.empty((N, 2), np.float32)
pos[:, 0] = np.linspace(0., 1., N)
pos[:, 1] = np.random.normal(loc=0.5, scale=0.03, size=N)
pos[N // 2:N // 2 + 20, 1] = 0.9  # So we can see which side is up

# Create canvas
canvas = scene.SceneCanvas(size=(800, 600), show=True, keys='interactive')

#
# Create viewboxes on left ...
#

w, h = canvas.size
w2 = w / 2.
h2 = h / 2.

# left (+y up)
vb1 = scene.widgets.ViewBox(parent=canvas.scene,
                            name='vb1',
                            margin=2,
                            border_color='red')
vb1.pos = 0, 0
示例#6
0
文件: plot.py 项目: yurkinx/rainbow
    def __init__(self,
                 icurves,
                 highlight=None,
                 clrmap="husl",
                 colors=None,
                 parent=None):
        """ 
        :param icurves: input curve or list of curves
        :param clrmap: (optional) what colormap name from vispy.colormap to use
        :param colors: (optional) use list of colors instead of colormap
        """
        self.canvas = scene.SceneCanvas(
            size=(1280, 900),
            position=(200, 200),
            keys="interactive",
            bgcolor=bg_clr,
            parent=parent,
        )

        self.grid = self.canvas.central_widget.add_grid(spacing=0)
        self.view = self.grid.add_view(row=0, col=1, camera="panzoom")

        curves = np.array(icurves)
        if len(curves.shape) == 1:
            ## Single curve
            curves = np.array([icurves])

        nb_traces, size = curves.shape

        # the Line visual requires a vector of X,Y coordinates
        xy_curves = np.dstack((np.tile(np.arange(size),
                                       (nb_traces, 1)), curves))

        # Specify which points are connected
        # Start by connecting each point to its successor
        connect = np.empty((nb_traces * size - 1, 2), np.int32)
        connect[:, 0] = np.arange(nb_traces * size - 1)
        connect[:, 1] = connect[:, 0] + 1

        # Prevent vispy from drawing a line between the last point
        # of a curve and the first point of the next curve
        for i in range(size, nb_traces * size, size):
            connect[i - 1, 1] = i - 1

        if highlight is not None:
            # cheat by predrawing a single line over the highlighted one
            scene.Line(pos=xy_curves[highlight],
                       color=highlighted,
                       parent=self.view.scene)
            scene.Line(pos=xy_curves,
                       color=others,
                       parent=self.view.scene,
                       connect=connect)
        else:
            if colors is None:
                colormap = color.get_colormap(clrmap)[np.linspace(
                    0.0, 1.0, nb_traces * size)]
            else:
                colormap = color.get_colormap(clrmap)[colors]
            scene.Line(pos=xy_curves,
                       color=colormap,
                       parent=self.view.scene,
                       connect=connect)

        self.x_axis = scene.AxisWidget(orientation="bottom")
        self.y_axis = scene.AxisWidget(orientation="left")
        self.x_axis.stretch = (1, 0.05)
        self.y_axis.stretch = (0.05, 1)
        self.grid.add_widget(self.x_axis, row=1, col=1)
        self.grid.add_widget(self.y_axis, row=0, col=0)
        self.x_axis.link_view(self.view)
        self.y_axis.link_view(self.view)

        self.view.camera.set_range(x=(-1, size),
                                   y=(curves.min(), curves.max()))

        self.canvas.show()
        if parent is None:
            self.canvas.app.run()
__author__ = 'Penny Qian'
"""
This script is to test creating IsoSurface based on Gaussian Density Estimation for scatter points
Some displacement exists between the scatter points and the produced IsoSurface
"""

import numpy as np
from vispy import app, scene, io
from vispy.color import Color
from scipy import stats

# Prepare canvas
canvas = scene.SceneCanvas(keys='interactive',
                           size=(800, 600),
                           show=True,
                           bgcolor='white')
canvas.measure_fps()

# Set up a viewbox to display the image with interactive pan/zoom
view = canvas.central_widget.add_view()

# Create three cameras (Fly, Turntable and Arcball)
fov = 60.
cam2 = scene.cameras.TurntableCamera(parent=view.scene,
                                     fov=fov,
                                     name='Turntable')
view.camera = cam2  # Select turntable at first

# Add scatter plots here
n = 5000
pos = np.random.normal(size=(n, 3), scale=0.2)
示例#8
0
    def __init__(self, parent):
        super(SignalWidget, self).__init__(parent)

        # Useful trnascripts
        self.plugin = self.parent()
        self.sd = self.plugin.sd
        self.CONF_SECTION = self.parent().CONF_SECTION

        # Variables
        self.measurement_mode = False
        self.curr_pc = None
        self.sig_start = None
        self.sig_stop = None
        self.spect_type = 'spectrum'  # spectrum, spectrogram

        # General variables
        self.low_lim = None
        self.high_lim = None

        # Sepctrum variables
        self.mean_filter = None

        # Setup camera
        self.signal_camera = SignalCamera()
        self.spectrum_camera = SignalCamera()

        self.canvas = scene.SceneCanvas(show=True,
                                        keys='interactive',
                                        parent=self,
                                        bgcolor=CONF.get(
                                            self.CONF_SECTION, 'bgcolor'))

        self.view_grid = self.canvas.central_widget.add_grid(margin=10)

        # Signal
        self.signal_view = self.view_grid.add_view(row=0,
                                                   col=1,
                                                   row_span=2,
                                                   camera=self.signal_camera)
        axis_color = CONF.get(self.CONF_SECTION, 'axis_color')
        self.signal_yaxis = AxisWidget(orientation='left',
                                       axis_label='Amplitude',
                                       axis_font_size=12,
                                       tick_label_margin=5,
                                       axis_color=axis_color,
                                       tick_color=axis_color,
                                       text_color=axis_color)
        self.signal_yaxis.width_max = 60
        self.view_grid.add_widget(self.signal_yaxis, row=0, col=0, row_span=2)

        self.signal_xaxis = scene.AxisWidget(orientation='bottom',
                                             axis_label='Time [s]',
                                             axis_font_size=12,
                                             tick_label_margin=5,
                                             axis_color=axis_color,
                                             tick_color=axis_color,
                                             text_color=axis_color)

        self.signal_xaxis.height_max = 55
        self.view_grid.add_widget(self.signal_xaxis, row=2, col=1)

        self.signal_yaxis.link_view(self.signal_view)
        self.signal_xaxis.link_view(self.signal_view)

        # Spectrum
        self.spectrum_view = self.view_grid.add_view(
            row=3, col=1, row_span=2, camera=self.spectrum_camera)

        self.spectrum_yaxis = AxisWidget(orientation='left',
                                         axis_label='Amplitude',
                                         axis_font_size=12,
                                         tick_label_margin=5,
                                         axis_color=axis_color,
                                         tick_color=axis_color,
                                         text_color=axis_color)
        self.spectrum_yaxis.width_max = 60
        self.view_grid.add_widget(self.spectrum_yaxis,
                                  row=3,
                                  col=0,
                                  row_span=2)

        self.spectrum_xaxis = scene.AxisWidget(orientation='bottom',
                                               axis_label='Frequency [Hz]',
                                               axis_font_size=12,
                                               axis_color=axis_color,
                                               tick_color=axis_color,
                                               text_color=axis_color)

        self.spectrum_xaxis.height_max = 55
        self.view_grid.add_widget(self.spectrum_xaxis, row=5, col=1)

        self.spectrum_yaxis.link_view(self.spectrum_view)
        self.spectrum_xaxis.link_view(self.spectrum_view)

        self.signal_line = Line(parent=self.signal_view.scene, width=1)
        self.spectrum_line = Line(parent=self.spectrum_view.scene, width=1)
        self.spectrogram = Spectrogram([0], parent=self.spectrum_view.scene)

        # ----- Set layout -----
        # Widget layout
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        layout.addWidget(self.canvas.native)

        # Set the whole layout
        self.setLayout(layout)
示例#9
0
BoatNode = scene.visuals.create_visual_node(BoatVisual)
TextNode = scene.visuals.create_visual_node(visuals.TextVisual)

# Create a canvas to display our visual
WINDOW_WIDTH = 1600
WINDOW_HEIGHT = 800
ARENA_WIDTH = 800
ARENA_HEIGHT = WINDOW_HEIGHT
DATA_WIDTH = WINDOW_WIDTH - ARENA_WIDTH
DATA_HEIGHT = WINDOW_HEIGHT
ARENA_CENTER = (ARENA_WIDTH/2., ARENA_HEIGHT/2.)
ARENA_EDGE_SIZE = 100.0

# remember 0, 0 is upper left in pixel coordinates, (pixel_width, pixel_height) is the lower right in pixel coordinates
# In real coordinates 0, 0 is the center, negatives are to the left and down
CANVAS = scene.SceneCanvas(keys='interactive', show=True, size=(WINDOW_WIDTH, WINDOW_HEIGHT))
ARENA_VIEW = scene.widgets.ViewBox(parent=CANVAS.scene, name="arena_view", margin=0, bgcolor=(1, 1, 1, 1), size=(ARENA_WIDTH, ARENA_HEIGHT), pos=(0, 0))
DATA_VIEW = scene.widgets.ViewBox(parent=CANVAS.scene, name="data_view", margin=0, bgcolor=(0.8, 0.8, 0.8, 1), size=(DATA_WIDTH, DATA_HEIGHT), pos=(ARENA_WIDTH, 0))

# Create two instances of the visual, each using canvas.scene as their parent

COLORS = {"pid": (0, .6, .6, 1),
          "q": (.6, 0, 0, 1)}

BOAT_VISUALS = {"pid": BoatNode(ARENA_CENTER[0], ARENA_CENTER[1], 0, 20, 40, COLORS["pid"], parent=CANVAS.scene),
                "q": BoatNode(ARENA_CENTER[0], ARENA_CENTER[1], 0, 20, 40, COLORS["q"], parent=CANVAS.scene)}

NAVIGATION_LINES = {"pid": scene.visuals.Line(pos=np.zeros((2, 2), dtype=np.float32), color=COLORS["pid"], parent=CANVAS.scene),
                    "q": scene.visuals.Line(pos=np.zeros((2, 2), dtype=np.float32), color=COLORS["q"], parent=CANVAS.scene)}
NAVIGATION_LINES["pid"].transform = scene.transforms.STTransform()
NAVIGATION_LINES["q"].transform = scene.transforms.STTransform()
示例#10
0
def visualize(z_in, azimuth=25., elevation=30.,
    thresholds=[0.94, .89, .75, .5, .25, .1], opacities=[.9, .8, .7, .5, .2, .1],
#     thresholds=[0.94, .89, .75], opacities=[.99, .7, .2],
#     thresholds=[0.7, .5, .2], opacities=[.95, .5, .2],
    fourier_label = {'f_x':'f_x', 'f_y':'f_y', 'f_t':'f_t'},
    name=None, ext=ext, do_axis=True, do_grids=False, draw_projections=True,
    colorbar=False, f_N=2., f_tN=2., figsize=figsize, figpath=figpath, **kwargs):
    """

    Visualization of the Fourier spectrum by showing 3D contour plots at different thresholds

    parameters
    ----------
    z : envelope of the cloud

    """
    z = z_in.copy()
    N_X, N_Y, N_frame = z.shape
    fx, fy, ft = get_grids(N_X, N_Y, N_frame)

    # Normalize the amplitude.
    z /= z.max()

    from vispy import app, scene
    try:
        AffineTransform = scene.transforms.AffineTransform
    except:
        AffineTransform = scene.transforms.MatrixTransform

    app.use_app('pyglet')
    #from vispy.util.transforms import perspective, translate, rotate
    from vispy.color import Color
    transparent = Color(color='black', alpha=0.)
    import colorsys
    canvas = scene.SceneCanvas(size=figsize, bgcolor='white', dpi=450)
    view = canvas.central_widget.add_view()

    vol_data = np.rollaxis(np.rollaxis(z, 1), 2)
#         volume = scene.visuals.Volume(vol_data, parent=view.scene)#frame)
    center = scene.transforms.STTransform(translate=( -N_X/2, -N_Y/2, -N_frame/2))
#         volume.transform = center
#         volume.cmap = 'blues'

    if draw_projections:
        from vispy.color import Colormap
        cm = Colormap([(1.0, 1.0, 1.0, 1.0), 'k'])
        opts = {'parent':view.scene, 'cmap':cm, 'clim':(0., 1.)}

        energy_xy = np.rot90(np.max(z, axis=2)[:, ::-1], 3)[:, ::-1]
        fourier_xy = scene.visuals.Image(np.rot90(energy_xy), **opts)
        tr_xy = AffineTransform()
        tr_xy.rotate(90, (0, 0, 1))
        tr_xy.translate((N_X/2, -N_Y/2, -N_frame/2))
        fourier_xy.transform = tr_xy

        energy_xt = np.rot90(np.max(z, axis=1)[:, ::-1], 3)[::-1, ::-1]
        fourier_xt = scene.visuals.Image(energy_xt, **opts)
        tr_xt = AffineTransform()
        tr_xt.rotate(90, (1, 0, 0))
        tr_xt.translate((-N_X/2, N_Y/2, -N_frame/2))
        fourier_xt.transform = tr_xt

        energy_yt = np.max(z, axis=0)#[:, ::-1]
        fourier_yt = scene.visuals.Image(energy_yt, **opts)
        tr_yt = AffineTransform()
        tr_yt.rotate(90, (0, 1, 0))
        tr_yt.translate((-N_X/2, -N_Y/2, N_frame/2))
        fourier_yt.transform = tr_yt

    # Generate iso-surfaces at different energy levels
    surfaces = []
    for i_, (threshold, opacity) in enumerate(list(zip(thresholds, opacities))):
        surfaces.append(scene.visuals.Isosurface(z, level=threshold,
#                                         color=Color(np.array(colorsys.hsv_to_rgb(1.*i_/len(thresholds), 1., 1.)), alpha=opacity),
                                    color=Color(np.array(colorsys.hsv_to_rgb(.66, 1., 1.)), alpha=opacity),
                                    shading='smooth', parent=view.scene)
                                                )
        surfaces[-1].transform = center

    # Draw a sphere at the origin
    axis = scene.visuals.XYZAxis(parent=view.scene)
    for p in ([1, 1, 1, -1, 1, 1], [1, 1, -1, -1, 1, -1], [1, -1, 1, -1, -1, 1],[1, -1, -1, -1, -1, -1],
              [1, 1, 1, 1, -1, 1], [-1, 1, 1, -1, -1, 1], [1, 1, -1, 1, -1, -1], [-1, 1, -1, -1, -1, -1],
              [1, 1, 1, 1, 1, -1], [-1, 1, 1, -1, 1, -1], [1, -1, 1, 1, -1, -1], [-1, -1, 1, -1, -1, -1]):
        line = scene.visuals.Line(pos=np.array([[p[0]*N_X/2, p[1]*N_Y/2, p[2]*N_frame/2], [p[3]*N_X/2, p[4]*N_Y/2, p[5]*N_frame/2]]), color='black', parent=view.scene)

    axisX = scene.visuals.Line(pos=np.array([[0, -N_Y/2, 0], [0, N_Y/2, 0]]), color='red', parent=view.scene)
    axisY = scene.visuals.Line(pos=np.array([[-N_X/2, 0, 0], [N_X/2, 0, 0]]), color='green', parent=view.scene)
    axisZ = scene.visuals.Line(pos=np.array([[0, 0, -N_frame/2], [0, 0, N_frame/2]]), color='blue', parent=view.scene)

    if do_axis:
        t = {}
        for text in ['f_x', 'f_y', 'f_t']:
            t[text] = scene.visuals.Text(fourier_label[text], parent=canvas.scene, face='Helvetica', color='black')
            t[text].font_size = 8
        t['f_x'].pos = canvas.size[0] // 3, canvas.size[1] - canvas.size[1] // 8
        t['f_y'].pos = canvas.size[0] - canvas.size[0] // 8, canvas.size[1] - canvas.size[1] // 6
        t['f_t'].pos = canvas.size[0] // 8, canvas.size[1] // 2

    cam = scene.TurntableCamera(elevation=elevation, azimuth=azimuth, up='z')
    cam.fov = 48
    cam.scale_factor = N_X * 1.8
    if do_axis: margin = 1.35
    else: margin = 1
    cam.set_range((-N_X/2*margin, N_X/2/margin), (-N_Y/2*margin, N_Y/2/margin), (-N_frame/2*margin, N_frame/2/margin))
    view.camera = cam

    im = canvas.render(size=figsize)
    app.quit()
    if not(name is None):
        import vispy.io as io
        io.write_png(name + ext, im)
    else:
        return im
示例#11
0
def cube(im_in, azimuth=30., elevation=45., name=None,
         ext=ext, do_axis=True, show_label=True,
         cube_label = {'x':'x', 'y':'y', 't':'t'},
         colormap='gray', roll=-180., vmin=0., vmax=1.,
         figsize=figsize, figpath=figpath, **kwargs):

    """

    Visualization of the stimulus as a cube

    """
    im = im_in.copy()

    N_X, N_Y, N_frame = im.shape
    fx, fy, ft = get_grids(N_X, N_Y, N_frame)
    import numpy as np
    from vispy import app, scene
    try:
        AffineTransform = scene.transforms.AffineTransform
    except:
        AffineTransform = scene.transforms.MatrixTransform

    app.use_app('pyglet')
    from vispy.util.transforms import perspective, translate, rotate
    canvas = scene.SceneCanvas(size=figsize, bgcolor='white', dpi=450)
    view = canvas.central_widget.add_view()

#         frame = scene.visuals.Cube(size = (N_X/2, N_frame/2, N_Y/2), color=(0., 0., 0., 0.),
#                                         edge_color='k',
#                                         parent=view.scene)
    for p in ([1, 1, 1, -1, 1, 1], [1, 1, -1, -1, 1, -1], [1, -1, 1, -1, -1, 1],[1, -1, -1, -1, -1, -1],
              [1, 1, 1, 1, -1, 1], [-1, 1, 1, -1, -1, 1], [1, 1, -1, 1, -1, -1], [-1, 1, -1, -1, -1, -1],
              [1, 1, 1, 1, 1, -1], [-1, 1, 1, -1, 1, -1], [1, -1, 1, 1, -1, -1], [-1, -1, 1, -1, -1, -1]):
#             line = scene.visuals.Line(pos=np.array([[p[0]*N_Y/2, p[1]*N_X/2, p[2]*N_frame/2], [p[3]*N_Y/2, p[4]*N_X/2, p[5]*N_frame/2]]), color='black', parent=view.scene)
        line = scene.visuals.Line(pos=np.array([[p[0]*N_X/2, p[1]*N_frame/2, p[2]*N_Y/2],
                                                [p[3]*N_X/2, p[4]*N_frame/2, p[5]*N_Y/2]]), color='black', parent=view.scene)

    opts = {'parent':view.scene, 'cmap':'grays', 'clim':(0., 1.)}
    image_xy = scene.visuals.Image(np.rot90(im[:, :, 0], 3), **opts)
    tr_xy = AffineTransform()
    tr_xy.rotate(90, (1, 0, 0))
    tr_xy.translate((-N_X/2, -N_frame/2, -N_Y/2))
    image_xy.transform = tr_xy

    image_xt = scene.visuals.Image(np.fliplr(im[:, -1, :]), **opts)
    tr_xt = AffineTransform()
    tr_xt.rotate(90, (0, 0, 1))
    tr_xt.translate((N_X/2, -N_frame/2, N_Y/2))
    image_xt.transform = tr_xt

    image_yt = scene.visuals.Image(np.rot90(im[-1, :, :], 1), **opts)
    tr_yt = AffineTransform()
    tr_yt.rotate(90, (0, 1, 0))
    tr_yt.translate((+N_X/2, -N_frame/2, N_Y/2))
    image_yt.transform = tr_yt

    if do_axis:
        t = {}
        for text in ['x', 'y', 't']:
            t[text] = scene.visuals.Text(cube_label[text], parent=canvas.scene, face='Helvetica', color='black')
            t[text].font_size = 8
        t['x'].pos = canvas.size[0] // 3, canvas.size[1] - canvas.size[1] // 8
        t['t'].pos = canvas.size[0] - canvas.size[0] // 5, canvas.size[1] - canvas.size[1] // 6
        t['y'].pos = canvas.size[0] // 12, canvas.size[1] // 2

    cam = scene.TurntableCamera(elevation=35, azimuth=30)
    cam.fov = 45
    cam.scale_factor = N_X * 1.7
    if do_axis: margin = 1.3
    else: margin = 1
    cam.set_range((-N_X/2, N_X/2), (-N_Y/2*margin, N_Y/2/margin), (-N_frame/2, N_frame/2))
    view.camera = cam
    if not(name is None):
        im = canvas.render(size=figsize)
        app.quit()
        import vispy.io as io
        io.write_png(name + ext, im)
    else:
        app.quit()
        return im
示例#12
0
    def debug(self, measurements, file_path, add_geodesic):

        # Model object
        model = mesh_lib.Model(file_path)
        model_point_coordinates = model.get_coords()

        canvas = scene.SceneCanvas(keys='interactive')
        view = canvas.central_widget.add_view()

        # all model - GREEN
        points = Markers(parent=view.scene)
        points.set_data(
            pos=model_point_coordinates,
            edge_color=None,
            face_color=(0, 1, 0, .3),
            size=5
        )
        data_list = []
        for m in measurements:  # measurements in config file
            # parsing key vertexes and description text
            point_1 = int(m[1]) + 1
            point_2 = int(m[2]) + 1
            point_3 = int(m[3]) + 1
            text = " ".join(m[4:])

            # coordinates of key vertexes
            key_coords = model.get_coords((point_1, point_2, point_3))
            # plane that goes through all three key vertexes
            plane = mesh_lib.get_plane(key_coords)

            # key vertexes WHITE
            points = Markers()
            points.set_data(
                pos=key_coords,
                edge_color=None,
                face_color=(1, 1, 1, 1),
                size=5
            )

            # "C" - circumference
            if m[0] == "C":
                # 3 segments of path (indexes)
                p_1 = model.get_path(point_1, point_2)
                p_2 = model.get_path(point_2, point_3)
                p_3 = model.get_path(point_3, point_1)
                # full path
                path = p_1 + p_2[1:] + p_3[1:]
            # "L" - Length
            if m[0] == "L":
                # 2 segments of path (indexes)
                p_1 = model.get_path(point_1, point_2)
                p_2 = model.get_path(point_2, point_3)
                # full path
                path = p_1 + p_2[1:]

            # geodesic
            geodesic_coordinates = model.get_coords(path)
            geodesic_length = mesh_lib.get_length(geodesic_coordinates)
            print("{0}:".format(text))
            print(
                "  Geodesic distance: {0} cm".format(
                    round(100 * geodesic_length, 3)
                )
            )

            if add_geodesic:  # if debug_full
                # geodesic line - RED
                line = Line(parent=view.scene)
                line.set_data(
                    pos=geodesic_coordinates,
                    color=(1, 0, 0, 1)
                )

            # approximated
            flattened_coordinates = mesh_lib.get_projections(plane, geodesic_coordinates)
            flattened_length = mesh_lib.get_length(flattened_coordinates)
            print(
                "  Approximated distance: {0} cm".format(
                    round(100 * flattened_length, 3)
                )
            )
            
            data_list.append(geodesic_length)
            data_list.append(flattened_length)
            # flattened line - BLUE
            line = Line(parent=view.scene)
            line.set_data(
                pos=flattened_coordinates,
                color=(0, 0, 1, 1)
            )

        view.camera = 'turntable'
        view.camera.fov = 45
        view.camera.distance = 3

        axis = XYZAxis(parent=view.scene)
        final_result = {"canvas":canvas,"data":data_list}
        return final_result
示例#13
0
import sys
import os
import numpy as np
from vispy import app, scene, io
# from vispy import color

canvas = scene.SceneCanvas(title='Skeleton Pose',
                           size=(600, 600),
                           keys='interactive')
view = canvas.central_widget.add_view(camera='turntable')
view.camera.fov = 45
view.camera.distance = 10

pose_data_fname = './data/error.csv'
data = np.loadtxt(pose_data_fname, skiprows=1, delimiter=',')
pose_data = data[:, :-2]
predict = data[:, -2]
real = data[:, -1]

predict = predict.reshape(-1)
real = real.reshape(-1)
pose_data = pose_data.reshape(-1, 19, 3)

pose_idx = 0
test = 0
max_pose_idx = pose_data.shape[0] - 1

pos = pose_data[pose_idx]
j_colors = np.random.uniform(size=(19, 3), low=.5, high=.8)

# j_colors = color.get_colormap('orange').map(np.array([e/24 for e in range(25)]))
示例#14
0
def oscilloscope():
    # Copyright (c) Vispy Development Team. All Rights Reserved.
    # Distributed under the (new) BSD License. See LICENSE.txt for more info.
    """
    An oscilloscope, spectrum analyzer, and spectrogram.

    This demo uses pyaudio to record data from the microphone. If pyaudio is not
    available, then a signal will be generated instead.
    """

    import threading
    import atexit
    import numpy as np
    from vispy import app, scene, gloo, visuals
    from vispy.util.filter import gaussian_filter

    try:
        import pyaudio

        class MicrophoneRecorder(object):
            def __init__(self, rate=44100, chunksize=1024):
                self.rate = rate
                self.chunksize = chunksize
                self.p = pyaudio.PyAudio()
                self.stream = self.p.open(format=pyaudio.paInt16,
                                          channels=1,
                                          rate=self.rate,
                                          input=True,
                                          frames_per_buffer=self.chunksize,
                                          stream_callback=self.new_frame)
                self.lock = threading.Lock()
                self.stop = False
                self.frames = []
                atexit.register(self.close)

            def new_frame(self, data, frame_count, time_info, status):
                data = np.fromstring(data, 'int16')
                with self.lock:
                    self.frames.append(data)
                    if self.stop:
                        return None, pyaudio.paComplete
                return None, pyaudio.paContinue

            def get_frames(self):
                with self.lock:
                    frames = self.frames
                    self.frames = []
                    return frames

            def start(self):
                self.stream.start_stream()

            def close(self):
                with self.lock:
                    self.stop = True
                self.stream.close()
                self.p.terminate()

    except ImportError:

        class MicrophoneRecorder(object):
            def __init__(self):
                self.chunksize = 1024
                self.rate = rate = 44100
                t = np.linspace(0, 10, rate * 10)
                self.data = (np.sin(t * 10.) * 0.3).astype('float32')
                self.data += np.sin((t + 0.3) * 20.) * 0.15
                self.data += gaussian_filter(
                    np.random.normal(size=self.data.shape) * 0.2, (0.4, 8))
                self.data += gaussian_filter(
                    np.random.normal(size=self.data.shape) * 0.005, (0, 1))
                self.data += np.sin(t * 1760 * np.pi)  # 880 Hz
                self.data = (self.data * 2**10 - 2**9).astype('int16')
                self.ptr = 0

            def get_frames(self):
                if self.ptr + 1024 > len(self.data):
                    end = 1024 - (len(self.data) - self.ptr)
                    frame = np.concatenate(
                        (self.data[self.ptr:], self.data[:end]))
                else:
                    frame = self.data[self.ptr:self.ptr + 1024]
                self.ptr = (self.ptr + 1024) % (len(self.data) - 1024)
                return [frame]

            def start(self):
                pass

    class Oscilloscope(scene.ScrollingLines):
        """A set of lines that are temporally aligned on a trigger.

        Data is added in chunks to the oscilloscope, and each new chunk creates a
        new line to draw. Older lines are slowly faded out until they are removed.

        Parameters
        ----------
        n_lines : int
            The maximum number of lines to draw.
        line_size : int
            The number of samples in each line.
        dx : float
            The x spacing between adjacent samples in a line.
        color : tuple
            The base color to use when drawing lines. Older lines are faded by
            decreasing their alpha value.
        trigger : tuple
            A set of parameters (level, height, width) that determine how triggers
            are detected.
        parent : Node
            An optional parent scenegraph node.
        """
        def __init__(self,
                     n_lines=100,
                     line_size=1024,
                     dx=1e-4,
                     color=(20, 255, 50),
                     trigger=(0, 0.002, 1e-4),
                     parent=None):

            self._trigger = trigger  # trigger_level, trigger_height, trigger_width

            # lateral positioning for trigger
            self.pos_offset = np.zeros((n_lines, 3), dtype=np.float32)

            # color array to fade out older plots
            self.color = np.empty((n_lines, 4), dtype=np.ubyte)
            self.color[:, :3] = [list(color)]
            self.color[:, 3] = 0
            self._dim_speed = 0.01**(1 / n_lines)

            self.frames = []  # running list of recently received frames
            self.plot_ptr = 0

            scene.ScrollingLines.__init__(self,
                                          n_lines=n_lines,
                                          line_size=line_size,
                                          dx=dx,
                                          color=self.color,
                                          pos_offset=self.pos_offset,
                                          parent=parent)
            self.set_gl_state('additive', line_width=2)

        def new_frame(self, data):
            self.frames.append(data)

            # see if we can discard older frames
            while len(self.frames) > 10:
                self.frames.pop(0)

            if self._trigger is None:
                dx = 0
            else:
                # search for next trigger
                th = int(self._trigger[1])  # trigger window height
                tw = int(self._trigger[2] / self._dx)  # trigger window width
                thresh = self._trigger[0]

                trig = np.argwhere((data[tw:] > thresh + th)
                                   & (data[:-tw] < thresh - th))
                if len(trig) > 0:
                    m = np.argmin(np.abs(trig - len(data) / 2))
                    i = trig[m, 0]
                    y1 = data[i]
                    y2 = data[min(i + tw * 2, len(data) - 1)]
                    s = y2 / (y2 - y1)
                    i = i + tw * 2 * (1 - s)
                    dx = i * self._dx
                else:
                    # default trigger at center of trace
                    # (optionally we could skip plotting instead, or place this
                    # after the most recent trace)
                    dx = self._dx * len(data) / 2.

            # if a trigger was found, add new data to the plot
            self.plot(data, -dx)

        def plot(self, data, dx=0):
            self.set_data(self.plot_ptr, data)

            np.multiply(self.color[..., 3],
                        0.98,
                        out=self.color[..., 3],
                        casting='unsafe')
            self.color[self.plot_ptr, 3] = 50
            self.set_color(self.color)
            self.pos_offset[self.plot_ptr] = (dx, 0, 0)
            self.set_pos_offset(self.pos_offset)

            self.plot_ptr = (self.plot_ptr + 1) % self._data_shape[0]

    rolling_tex = """
    float rolling_texture(vec2 pos) {
        if( pos.x < 0 || pos.x > 1 || pos.y < 0 || pos.y > 1 ) {
            return 0.0f;
        }
        vec2 uv = vec2(mod(pos.x+$shift, 1), pos.y);
        return texture2D($texture, uv).r;
    }
    """

    cmap = """
    vec4 colormap(float x) {
        x = x - 1e4;
        return vec4(x/5e6, x/2e5, x/1e4, 1);
    }
    """

    class ScrollingImage(scene.Image):
        def __init__(self, shape, parent):
            self._shape = shape
            self._color_fn = visuals.shaders.Function(rolling_tex)
            self._ctex = gloo.Texture2D(np.zeros(shape + (1, ),
                                                 dtype='float32'),
                                        format='luminance',
                                        internalformat='r32f')
            self._color_fn['texture'] = self._ctex
            self._color_fn['shift'] = 0
            self.ptr = 0
            scene.Image.__init__(self, method='impostor', parent=parent)
            # self.set_gl_state('additive', cull_face=False)
            self.shared_program.frag['get_data'] = self._color_fn
            cfun = visuals.shaders.Function(cmap)
            self.shared_program.frag['color_transform'] = cfun

        @property
        def size(self):
            return self._shape

        def roll(self, data):
            data = data.reshape(data.shape[0], 1, 1)

            self._ctex[:, self.ptr] = data
            self._color_fn['shift'] = (self.ptr + 1) / self._shape[1]
            self.ptr = (self.ptr + 1) % self._shape[1]
            self.update()

        def _prepare_draw(self, view):
            if self._need_vertex_update:
                self._build_vertex_data()

            if view._need_method_update:
                self._update_method(view)

    global fft_frames, scope, spectrum, mic
    mic = MicrophoneRecorder()
    n_fft_frames = 8
    fft_samples = mic.chunksize * n_fft_frames

    win = scene.SceneCanvas(keys='interactive', show=True, fullscreen=True)
    grid = win.central_widget.add_grid()

    view3 = grid.add_view(row=0,
                          col=0,
                          col_span=2,
                          camera='panzoom',
                          border_color='grey')
    image = ScrollingImage((1 + fft_samples // 2, 4000), parent=view3.scene)
    image.transform = scene.LogTransform((0, 10, 0))
    # view3.camera.rect = (0, 0, image.size[1], np.log10(image.size[0]))
    view3.camera.rect = (3493.32, 1.85943, 605.554, 1.41858)

    view1 = grid.add_view(row=1, col=0, camera='panzoom', border_color='grey')
    view1.camera.rect = (-0.01, -0.6, 0.02, 1.2)
    gridlines = scene.GridLines(color=(1, 1, 1, 0.5), parent=view1.scene)
    scope = Oscilloscope(line_size=mic.chunksize,
                         dx=1.0 / mic.rate,
                         parent=view1.scene)

    view2 = grid.add_view(row=1, col=1, camera='panzoom', border_color='grey')
    view2.camera.rect = (0.5, -0.5e6, np.log10(mic.rate / 2), 5e6)
    lognode = scene.Node(parent=view2.scene)
    lognode.transform = scene.LogTransform((10, 0, 0))
    gridlines2 = scene.GridLines(color=(1, 1, 1, 1), parent=lognode)

    spectrum = Oscilloscope(line_size=1 + fft_samples // 2,
                            n_lines=10,
                            dx=mic.rate / fft_samples,
                            trigger=None,
                            parent=lognode)

    mic.start()

    window = np.hanning(fft_samples)

    fft_frames = []

    def update(ev):
        global fft_frames, scope, spectrum, mic
        data = mic.get_frames()
        for frame in data:
            # import scipy.ndimage as ndi
            # frame -= ndi.gaussian_filter(frame, 50)
            # frame -= frame.mean()

            scope.new_frame(frame)

            fft_frames.append(frame)
            if len(fft_frames) >= n_fft_frames:
                cframes = np.concatenate(fft_frames) * window
                fft = np.abs(np.fft.rfft(cframes)).astype('float32')
                fft_frames.pop(0)

                spectrum.new_frame(fft)
                image.roll(fft)

    timer = app.Timer(interval='auto', connect=update)
    timer.start()

    app.run()
示例#15
0
def scatter(pos,
            mfc=[0.5, 0.5, 0.5, 0.8],
            mec=None,
            mfs=8,
            mes=1,
            bgc=[0.9, 0.9, 0.9],
            scaling=False,
            symbol='disc'):
    """ Display a scatter plot in 2D or 3D.

    Parameters
    ----------
    pos : array
        The array of locations to display each symbol.
    mfc : Color | ColorArray
        The color used to draw each symbol interior.
    mec : Color | ColorArray
        The color used to draw each symbol outline.
    mfs : float or array
        The symbol size in px.
    mes : float | None
        The width of the symbol outline in pixels.
    bgc : Color
        The color used for the background.
    scaling : bool
        If set to True, marker scales when rezooming.
    symbol : str
        The style of symbol to draw ('disc', 'arrow', 'ring', 'clobber',
        'square', 'diamond', 'vbar', 'hbar', 'cross', 'tailed_arrow', 'x',
        'triangle_up', 'triangle_down', 'star').
    """
    # Create the Canvas, the Scene and the View
    canvas = scene.SceneCanvas(keys='interactive', show=True, bgcolor=bgc)
    view = canvas.central_widget.add_view()
    # Create the scatter plot
    scatter = visuals.Markers()
    scatter.set_data(pos,
                     face_color=mfc,
                     edge_color=mec,
                     scaling=scaling,
                     size=mfs,
                     edge_width=mes,
                     symbol=symbol)
    view.add(scatter)

    # 2D Shape
    if pos.shape[1] == 2:
        # Set the camera properties
        view.camera = scene.PanZoomCamera(aspect=1)
        view.camera.set_range()
        # Create lines to know the position of the cursor
        tr = canvas.scene.node_transform(scatter)
        win_xmin, win_ymax = tr.map([0, 0])[:2]
        win_xmax, win_ymin = tr.map(canvas.size)[:2]
        win_xsize, win_ysize = win_xmax - win_xmin, win_ymax - win_ymin
        prop = .015
        tick_size = prop * win_xsize
        top_line = scene.visuals.Line(pos=np.array(
            [[win_xmin, win_ymax], [win_xmin, win_ymax - tick_size]]),
                                      color=[.2, .2, .2, 0.5],
                                      width=1,
                                      parent=view.scene,
                                      method='gl')
        right_line = scene.visuals.Line(pos=np.array(
            [[win_xmax, win_ymin], [win_xmax - tick_size, win_ymin]]),
                                        color=[.2, .2, .2, 0.5],
                                        width=1,
                                        parent=view.scene,
                                        method='gl')
        bottom_line = scene.visuals.Line(pos=np.array(
            [[win_xmax, win_ymin], [win_xmax, win_ymin + tick_size]]),
                                         color=[.2, .2, .2, 0.5],
                                         width=1,
                                         parent=view.scene,
                                         method='gl')
        left_line = scene.visuals.Line(pos=np.array(
            [[win_xmin, win_ymax], [win_xmin + tick_size, win_ymax]]),
                                       color=[.2, .2, .2, 0.5],
                                       width=1,
                                       parent=view.scene,
                                       method='gl')

        cross_hline = scene.visuals.Line(pos=np.array(
            [[win_xmax, win_ymin], [win_xmax, win_ymin + tick_size]]),
                                         color=[0, 0, 0, 1],
                                         width=2,
                                         parent=view.scene,
                                         method='gl')
        cross_vline = scene.visuals.Line(pos=np.array(
            [[win_xmin, win_ymax], [win_xmin + tick_size, win_ymax]]),
                                         color=[0, 0, 0, 1],
                                         width=2,
                                         parent=view.scene,
                                         method='gl')

        # TODO: create rectangle around the text
        # Create text to give cursor position
        text_xline = visuals.Text('',
                                  bold=False,
                                  font_size=12,
                                  color=[0, 0, 0, 1],
                                  pos=[50, 50],
                                  anchor_x='left',
                                  anchor_y='baseline')
        text_yline = visuals.Text('',
                                  bold=False,
                                  font_size=12,
                                  color=[0, 0, 0, 1],
                                  pos=[50, 50],
                                  anchor_x='left',
                                  anchor_y='baseline')

        view.add(text_xline)
        view.add(text_yline)

        # When the mouse move, refresh the cursor position
        @canvas.events.mouse_move.connect
        def on_mouse_move(event):
            # Find the cursor position in the windows coordinate
            tr = canvas.scene.node_transform(scatter)
            x, y = tr.map(event.pos)[:2]
            # Find the min and max for both axis in the windows coordinate
            win_xmin, win_ymax = tr.map([0, 0])[:2]
            win_xmax, win_ymin = tr.map(canvas.size)[:2]
            win_xsize, win_ysize = win_xmax - win_xmin, win_ymax - win_ymin
            tick_size = prop * win_xsize
            #refresh
            xtext, ytext = str('%.2e' % x), str('%.2e' % y)
            text_xline.text = xtext
            text_xline.pos = [x, win_ymin]
            text_yline.text = ytext
            text_yline.pos = [win_xmin, y]

            top_line.set_data(
                pos=np.array([[x, win_ymax], [x, win_ymax - tick_size]]))
            right_line.set_data(
                pos=np.array([[win_xmax, y], [win_xmax - tick_size, y]]))
            bottom_line.set_data(
                pos=np.array([[x, win_ymin], [x, win_ymin + tick_size]]))
            left_line.set_data(
                pos=np.array([[win_xmin, y], [win_xmin + tick_size, y]]))

            cross_hline.set_data(
                pos=np.array([[x - tick_size / 2, y], [x + tick_size / 2, y]]))
            cross_vline.set_data(
                pos=np.array([[x, y - tick_size / 2], [x, y + tick_size / 2]]))

    # 3D Shape
    elif pos.shape[1] == 3:
        view.camera = 'turntable'

    app.run()
示例#16
0
#print("filtering")
#start = time()
#vol = filter3d(vol, np.ones( (2,)*3 ))
#print(f"done filtering! {(time()-start)/D**3} sec / voxel")

# Increase the visibility of the x-z plane (where the logistic map lies)
vol[:, vol.shape[1] // 2, :] = np.sqrt(vol[:, vol.shape[1] // 2, :])

# Slice the data to reveal only the logistic map
slice = 0

if slice:
    vol = vol[:, vol.shape[1] // 2 - 1:vol.shape[1] // 2 + 2, :]

# Prepare canvas
canvas = scene.SceneCanvas(keys='interactive', size=rec_size, show=not rec)

# Set up a viewbox to display the image with interactive pan/zoom
view = canvas.central_widget.add_view()

stepsize = .1  # step size inside the fragment shader : 0.1 is highest quality

# Modify the vispy `transclucent` volume OpenGL shader

NEW_TRANSLUCENT_SNIPPETS = dict(
    before_loop="""
        vec4 integrated_color = vec4(0., 0., 0., 0.);
        """,
    in_loop="""

            color = $cmap(val);
示例#17
0
    def fn(i, j, ci=m // 2, cj=n // 2, t=None):
        x = i / m * (x1 - x0) + x0
        y = j / n * (y1 - y0) + y0
        # vx = -dy
        # vy = dx
        # vx = np.cos(t) * dx + np.sin(t) * dy
        # vy = -np.sin(t) * dx + np.cos(t) * dy
        vx = x * (3 - 5 * y)  #x-rabbit
        vy = y * (2 * x - 1)  #y-fox
        return np.array([vx, vy])  #=[vy,vx]

    return fn


VectorField = scene.visuals.create_visual_node(VectorFieldVisual)
canvas = scene.SceneCanvas(size=[1600, 1600], keys='interactive', show=True)
gloo.set_state(
    #     # clear_color=(0.30, 0.30, 0.35, 1.00),
    #  #    polygon_offset=(1, 1),
    #  #    blend_func=('src_alpha', 'one_minus_src_alpha'),
    line_width=2, )
view = canvas.central_widget.add_view(camera='panzoom')
view.camera.set_range()

view.camera.rect = (0, 0, 100, 100)

# text = scene.visuals.Text("Hello world",
#     color='w',anchor_x='left',
#     parent=view, pos=(20, 30))

field = np.fromfunction(getFn(0.0, 5, 100, 0.0, 5, 100),
示例#18
0
# -*- coding: utf-8 -*-
# vispy: gallery 30
# -----------------------------------------------------------------------------
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
"""
Simple use of SceneCanvas to display an Isocurve visual.
"""
import sys
from vispy import app, scene, visuals
from vispy.util.filter import gaussian_filter
import numpy as np

canvas = scene.SceneCanvas(keys='interactive',
                           title='Isocurve(s) overlayed '
                           'over Random Image Example')
canvas.size = 800, 600
canvas.show()

# Set up a viewbox to display the image with interactive pan/zoom
view = canvas.central_widget.add_view()

# Create the image
img_data = np.empty((200, 100, 3), dtype=np.ubyte)
noise = np.random.normal(size=(200, 100), loc=50, scale=150)
noise = gaussian_filter(noise, (4, 4, 0))
img_data[:] = noise[..., np.newaxis]
image = scene.visuals.Image(img_data, parent=view.scene)
# move image behind curves
image.transform = visuals.transforms.STTransform(translate=(0, 0, 0.5))
示例#19
0
def scatter_plot_voxels(gridLabels,
                        suncg_labels,
                        vox_min,
                        vox_unit,
                        save_path=None,
                        animate=False):
    nbr_classes = len(suncg_labels)

    occMask = gridLabels > 0
    xyz = np.nonzero(occMask)
    positions = np.vstack([xyz[0], xyz[1], xyz[2]])
    gridLabelsMasked = gridLabels[occMask]

    canvas = scene.SceneCanvas(keys='interactive',
                               bgcolor='w',
                               size=(1920, 1080))
    view = canvas.central_widget.add_view()
    azimuth = 30
    view.camera = scene.TurntableCamera(up='y',
                                        distance=4,
                                        fov=70,
                                        azimuth=azimuth,
                                        elevation=30.)

    # Sample colormap and adjust alpha
    colormap = get_colormap('hsl',
                            value=1.0,
                            saturation=0.8,
                            ncolors=nbr_classes)
    pos_color = np.zeros((positions.shape[1], 4))
    cm_sampled = []
    for i, (iclass, sample_f) in enumerate(
            zip(suncg_labels[1:], np.linspace(0, 1, nbr_classes - 1))):
        if iclass.lower() in ('floor', 'wall', 'window'):
            alpha = 0.5
        elif iclass.lower() == 'ceiling':
            alpha = 0.0
        else:
            alpha = 1.0
        base_color = colormap[sample_f].rgba.flatten()
        base_color[3] = alpha
        pos_color[i == gridLabelsMasked] = base_color

    Scatter3D = scene.visuals.create_visual_node(visuals.MarkersVisual)
    p1 = Scatter3D(parent=view.scene)
    p1.set_gl_state('translucent', blend=True, depth_test=True)
    p1.set_data(positions.T,
                face_color=pos_color,
                symbol='disc',
                size=10,
                edge_width=0.5,
                edge_color='k')

    p1.transform = scene.transforms.MatrixTransform()
    p1.transform.scale(3 * [vox_unit])
    p1.transform.translate(3 * [-vox_unit * gridLabels.shape[0] / 2.0])

    if save_path is None:
        return

    def make_frame(t):
        view.camera.set_state({'azimuth': azimuth + t * 90})
        return canvas.render()

    if animate:
        animation = VideoClip(make_frame, duration=3)
        animation.write_gif('voxel.gif', fps=8, opt='OptimizePlus')
    else:
        img = canvas.render()
        cv2.imwrite('voxel.png', img[::-1])
示例#20
0
                    dtype=np.float32)

faces = np.array([(0, 3, 2), (0, 2, 1)], dtype=np.uint32)

texture = np.array([((1.0, 0.0, 0.0), (0.0, 1.0, 0.0)),
                    ((0.0, 0.0, 1.0), (1.0, 1.0, 1.0))],
                   dtype=np.float32)

textureCoordinates = np.array([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
                              dtype=np.float32)

# Add mesh as VisPy node
TriangleMesh = scene.visuals.create_visual_node(TriangleMeshVisual)

# Create a new OpenGL window
plt = scene.SceneCanvas(keys='interactive', size=(1024, 768))

view = plt.central_widget.add_view(bgcolor=(0.2, 0.2, 0.2),
                                   border_color=(0.0, 0.0, 0.0),
                                   border_width=1)

# Add and configure camera
view.camera = scene.cameras.ArcballCamera(fov=0)
view.camera.center = (0.5, 0.0, 0.5)

mesh = TriangleMesh(vertices,
                    faces,
                    texture=texture,
                    textureCoordinates=textureCoordinates,
                    vertexShader=defaultVertexShaderWithTexture,
                    fragmentShader=defaultFragmentShaderWithTexture,
示例#21
0
        self.ptr = (self.ptr + 1) % self._shape[1]
        self.update()

    def _prepare_draw(self, view):
        if self._need_vertex_update:
            self._build_vertex_data()

        if view._need_method_update:
            self._update_method(view)


mic = MicrophoneRecorder()
n_fft_frames = 8
fft_samples = mic.chunksize * n_fft_frames

win = scene.SceneCanvas(keys='interactive', show=True, fullscreen=True)
grid = win.central_widget.add_grid()

view3 = grid.add_view(row=0, col=0, col_span=2, camera='panzoom',
                      border_color='grey')
image = ScrollingImage((1 + fft_samples // 2, 4000), parent=view3.scene)
image.transform = scene.LogTransform((0, 10, 0))
# view3.camera.rect = (0, 0, image.size[1], np.log10(image.size[0]))
view3.camera.rect = (3493.32, 1.85943, 605.554, 1.41858)

view1 = grid.add_view(row=1, col=0, camera='panzoom', border_color='grey')
view1.camera.rect = (-0.01, -0.6, 0.02, 1.2)
gridlines = scene.GridLines(color=(1, 1, 1, 0.5), parent=view1.scene)
scope = Oscilloscope(line_size=mic.chunksize, dx=1.0/mic.rate,
                     parent=view1.scene)
示例#22
0
        row = []
        vlines.append(row)
        for j in range(N):
            v = visuals.LineVisual(pos=data, color='w', method='gl')
            v.transform = visuals.transforms.STTransform(translate=(-1, 0),
                                                         scale=scales)
            row.append(v)

    vcanvas = VisualCanvas(vlines,
                           position=(400, 300),
                           size=(800, 600),
                           title="VisualCanvas")

    # Scenegraph version
    scanvas = scene.SceneCanvas(show=True,
                                keys='interactive',
                                title="SceneCanvas")

    scanvas.size = 800, 600
    grid = scanvas.central_widget.add_grid(margin=0)

    lines = []
    for i in range(10):
        lines.append([])
        for j in range(10):
            vb = grid.add_view(camera='panzoom', row=i, col=j)
            vb.camera.set_range([0, 100], [-5, 5], margin=0)
            line = scene.visuals.Line(pos=data, color='w', method='gl')
            vb.add(line)
    scanvas.show()
示例#23
0
from vispy import scene

import numpy as np

data = np.arange(1000).reshape((10, 10, 10))

canvas = scene.SceneCanvas(show=True)
view = canvas.central_widget.add_view()
axis = scene.visuals.XYZAxis(parent=view.scene)
view.camera = scene.cameras.TurntableCamera(parent=view.scene)

with canvas:
    canvas.render()
示例#24
0
from vispy import app, scene
import numpy as np

from gta import GTAData

filename = 'data/gta_test/3fd50f7b-658b-4ef4-bb17-dfc1f287def8_00000819'

data = GTAData(filename)

bbox_edges = []
for v in data.vehicles:
    bbox_edges.extend(v.get_3d_bbox_edges())

# Create a canvas with a 3D viewport
canvas = scene.SceneCanvas(keys='interactive', title='GTA Scene', bgcolor='white')
canvas.show()
view = canvas.central_widget.add_view()

# Add vehicle bounding box to view
if len(bbox_edges) > 0:
    scene.visuals.Line(pos=np.array(bbox_edges),
                       color=(0.2, 0.5, 0.3, 1),
                       connect='segments', parent=view.scene)

scene.visuals.XYZAxis(parent=view.scene)

# Add point cloud
c_pos_marker = scene.visuals.Markers(parent=view.scene)
cloud = np.array(data.load_depth())
cloud = cloud[np.all([-100,-100,-70] < cloud, axis=1), :]
import sys
import numpy as np

from vispy import app, scene
from vispy.util.filter import gaussian_filter

canvas = scene.SceneCanvas(keys='interactive', bgcolor='w')
view = canvas.central_widget.add_view()
view.camera = scene.TurntableCamera(up='z', fov=60)

# Simple surface plot example
# x, y values are not specified, so assumed to be 0:50
z = np.random.normal(size=(160, 120), scale=200)
z[100, 100] += 50000
z = gaussian_filter(z, (10, 10))
p1 = scene.visuals.SurfacePlot(z=z, color=(0.3, 0.3, 1, 1), shading='flat')
p1.transform = scene.transforms.MatrixTransform()
p1.transform.scale([1 / 249., 1 / 249., 1 / 249.])
p1.transform.translate([-0.5, -0.5, 0])

view.add(p1)

# p1._update_data()  # cheating.
# cf = scene.filters.ZColormapFilter('fire', zrange=(z.max(), z.min()))
# p1.attach(cf)

xax = scene.Axis(pos=[[-0.5, -0.5], [0.5, -0.5]],
                 tick_direction=(0, -1),
                 font_size=16,
                 axis_color='k',
                 tick_color='k',
示例#26
0

atoms = [atom for atom in structure.get_atoms()]
natoms = len(atoms)
#atom coordinates
coordinates = np.array([atom.coord for atom in atoms])
center = centroid(coordinates)
coordinates -= center
#atom color
color = [colorrgba(atom.get_id()) for atom in atoms]
#atom radius
radius = [vrad(atom.get_id()) for atom in atoms]

W, H = 1200, 800

MySpheres = scene.visuals.create_visual_node(MySpheresVisual)

canvas = scene.SceneCanvas(keys='interactive',
                           app='pyqt4',
                           bgcolor='black',
                           size=(W, H),
                           show=True)

view = canvas.central_widget.add_view()
view.camera = 'arcball'

spheres = [
    MySpheres(coordinates[0], color[0], radius[0], W, H, parent=view.scene)
]

canvas.app.run()
示例#27
0
from vispy import app, scene

# vertex positions of data to draw
N = 200
pos = np.zeros((N, 2), dtype=np.float32)
x_lim = [50., 750.]
y_lim = [-2., 2.]
pos[:, 0] = np.linspace(x_lim[0], x_lim[1], N)
pos[:, 1] = np.random.normal(size=N)

# color array
color = np.ones((N, 4), dtype=np.float32)
color[:, 0] = np.linspace(0, 1, N)
color[:, 1] = color[::-1, 0]

canvas = scene.SceneCanvas(keys='interactive', show=True)
grid = canvas.central_widget.add_grid(spacing=0)

viewbox = grid.add_view(row=0, col=1, camera='panzoom')

# add some axes
x_axis = scene.AxisWidget(orientation='bottom')
x_axis.stretch = (1, 0.1)
grid.add_widget(x_axis, row=1, col=1)
x_axis.link_view(viewbox)
y_axis = scene.AxisWidget(orientation='left')
y_axis.stretch = (0.1, 1)
grid.add_widget(y_axis, row=0, col=0)
y_axis.link_view(viewbox)

# add a line plot inside the viewbox
示例#28
0
    def __init__(self,
                 axis=False,
                 title=None,
                 xlabel=None,
                 ylabel=None,
                 title_font_size=15.,
                 axis_font_size=12.,
                 axis_color='black',
                 tick_font_size=10.,
                 name=None,
                 x_height_max=80,
                 y_width_max=80,
                 axis_label_margin=50,
                 tick_label_margin=5,
                 rpad=20.,
                 bgcolor='white',
                 add_cbar=False,
                 cargs={},
                 xargs={},
                 yargs={},
                 cbargs={},
                 show=False,
                 camera=None,
                 shortcuts={}):
        """Init."""
        self._axis = axis
        self._title = title
        self._xlabel = xlabel
        self._ylabel = ylabel
        self._title_font_size = title_font_size
        self._axis_font_size = axis_font_size
        self._axis_color = axis_color
        self._tick_font_size = tick_font_size
        self._name = name
        self._x_height_max = x_height_max
        self._y_width_max = y_width_max
        self._axis_label_margin = axis_label_margin
        self._tick_label_margin = tick_label_margin
        self._bgcolor = bgcolor
        self._visible = show

        # ########################## MAIN CANVAS ##########################
        self.canvas = scene.SceneCanvas(keys='interactive',
                                        bgcolor=bgcolor,
                                        show=show,
                                        title=name,
                                        **cargs)

        # ########################## AXIS ##########################
        if axis:  # add axis to canvas
            # ----------- GRID -----------
            grid = self.canvas.central_widget.add_grid(margin=10)
            grid.spacing = 0

            # ----------- COLOR -----------
            axcol = color2vb(axis_color)
            kw = {
                'axis_label_margin': axis_label_margin,
                'tick_label_margin': tick_label_margin,
                'axis_font_size': axis_font_size,
                'axis_color': axcol,
                'tick_color': axcol,
                'text_color': axcol,
                'tick_font_size': tick_font_size
            }

            # ----------- TITLE -----------
            self._titleObj = scene.Label(title,
                                         color=axcol,
                                         font_size=title_font_size)
            self._titleObj.height_max = 40
            grid.add_widget(self._titleObj, row=0, col=0, col_span=2)

            # ----------- Y-AXIS -----------
            yargs.update(kw)
            self.yaxis = scene.AxisWidget(orientation='left',
                                          domain=(0, 129),
                                          axis_label=ylabel,
                                          **yargs)
            self.yaxis.width_max = y_width_max
            grid.add_widget(self.yaxis, row=1, col=0)

            # ----------- X-AXIS -----------
            xargs.update(kw)
            self.xaxis = scene.AxisWidget(orientation='bottom',
                                          axis_label=xlabel,
                                          **xargs)
            self.xaxis.height_max = x_height_max
            grid.add_widget(self.xaxis, row=2, col=1)

            # ----------- MAIN -----------
            self.wc = grid.add_view(row=1, col=1, camera=camera)
            self.grid = grid

            # ----------- LINK -----------
            self.xaxis.link_view(self.wc)
            self.yaxis.link_view(self.wc)

            # ----------- CBAR -----------
            rpad_col = 0
            if add_cbar:
                self.wc_cbar = grid.add_view(row=1, col=2)
                self.wc_cbar.width_max = 150.
                self.cbar = CbarVisual(width=.2, parent=self.wc_cbar.scene)
                rpad_col += 1

            # ----------- RIGHT PADDING -----------
            self._rpad = grid.add_widget(row=1, col=2 + rpad_col, row_span=1)
            self._rpad.width_max = rpad

        else:  # Ignore axis
            self.wc = self.canvas.central_widget.add_view(camera=camera)
示例#29
0
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2015, Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
# vispy: gallery 2
"""
Demonstrating two scenes that share the same camera view by linking the
cameras.
"""

import numpy as np

from vispy import app, scene, io

canvas = scene.SceneCanvas(keys='interactive')
canvas.size = 800, 600
canvas.show()

# Create two ViewBoxes, place side-by-side
vb1 = scene.widgets.ViewBox(border_color='yellow', parent=canvas.scene)
vb2 = scene.widgets.ViewBox(border_color='blue', parent=canvas.scene)
#
grid = canvas.central_widget.add_grid()
grid.padding = 6
grid.add_widget(vb1, 0, 0)
grid.add_widget(vb2, 0, 1)

# Create the image
im1 = io.load_crate().astype('float32') / 255
# Make gray, smooth, and take derivatives: edge enhancement
示例#30
0
        '''
        mode_MSB = (mode << 5) + (polarity << 4) + (den << 3) + (
            iovalue << 1) + data_length
        mode_LSB = (reference << 7) + (0b0 << 6) + (input_range << 4) + (
            clock_enable << 3) + (burn_out << 2) + channel

        self.single_write(self.AD7730_MODE_REG, [mode_MSB, mode_LSB])

    def setFilter(self):
        data = self.single_read(self.AD7730_FILTER_REG)
        data[2] = data[2] | 0b00110011
        self.single_write(self.AD7730_FILTER_REG, data)
        return data


canvas = scene.SceneCanvas(keys='interactive', show=True, size=(1024, 768))
grid = canvas.central_widget.add_grid()
view = grid.add_view(0, 1)
view.camera = scene.MagnifyCamera(mag=1, size_factor=0.5, radius_ratio=0.6)

# Add axes
yax = scene.AxisWidget(orientation='left')
yax.stretch = (0.05, 1)
grid.add_widget(yax, 0, 0)
yax.link_view(view)

xax = scene.AxisWidget(orientation='bottom')
xax.stretch = (1, 0.05)
grid.add_widget(xax, 1, 1)
xax.link_view(view)