def vispy_process(queue, world_ltrb):
    def data_thread(queue, markers):
        while True:
            data = queue.get()
            if data is None:
                time.sleep(0.1)
                canvas.close()
                break
            points, face_colors, edge_colors = data
            if face_colors is not None and len(points) > 0:
                edge_width = 1 if isinstance(edge_colors, str) else 3
                markers.set_data(
                    points,
                    edge_width=edge_width,
                    edge_color=edge_colors,
                    face_color=face_colors,
                )
            else:
                markers.set_data(points)

    canvas = scene.SceneCanvas(title="3D Poses",
                               bgcolor="w",
                               size=(400, 400),
                               show=True)
    view = canvas.central_widget.add_view()
    view.camera = cameras.TurntableCamera()
    view.camera.fov = 80
    view.camera.distance = (
        max(world_ltrb[2] - world_ltrb[0], world_ltrb[3] - world_ltrb[1]) * 0.8
    )  # 200 or 800
    visuals.create_visual_node(XYZAxisVisual)(world_ltrb,
                                              100,
                                              parent=view.scene)
    x1, y1, x2, y2 = world_ltrb
    visuals.SurfacePlot(
        x=np.array([x1, x2]),
        y=np.array([y1, y2]),
        z=np.zeros((2, 2)),
        color=(0.5, 0.5, 0.5, 1),
        parent=view.scene,
    )

    markers = scene.visuals.Markers()
    markers.parent = view.scene

    # events
    def on_close(event):
        if event.text.lower() == "q":
            queue.put(None)

    canvas.events.key_press.connect(on_close)

    thread = Thread(target=data_thread, args=[queue, markers])
    thread.start()

    canvas.app.run()
    thread.join()
Beispiel #2
0
def on_draw(event):
    canvas.context.clear((0.3, 0.3, 0.3, 1.0))
    for v in order:
        v.draw()


def on_resize(event):
    # Set canvas viewport and reconfigure visual transforms to match.
    vp = (0, 0, canvas.physical_size[0], canvas.physical_size[1])
    canvas.context.set_viewport(*vp)
    for v in order:
        v.transforms.configure(canvas=canvas, viewport=vp)
canvas.events.resize.connect(on_resize)
on_resize(None)

Line = create_visual_node(LineVisual)
canvas2 = SceneCanvas(keys='interactive', title='Scene Canvas', show=True)
v = canvas2.central_widget.add_view(margin=10)
v.border_color = (1, 1, 1, 1)
v.bgcolor = (0.3, 0.3, 0.3, 1)
v.camera = 'panzoom'
line2 = Line(pos, parent=v.scene)


def mouse(ev):
    print(ev)

v.events.mouse_press.connect(mouse)

if __name__ == '__main__':
    if sys.flags.interactive != 1:
            )
        )

        # Set up RGBA texture
        self.texture = tex_cls((10, 10, 10, 4), interpolation="linear", wrapping="clamp_to_edge")
        self.texture.set_data(data.astype(np.float32))
        self.shared_program["u_volumetex"] = self.texture

        self._vol_shape = data.shape[:-1]
        self.shared_program["u_shape"] = self._vol_shape[::-1]

        self.shared_program["a_position"] = self._vertices
        self.shared_program["a_texcoord"] = self._texcoord

        self._draw_mode = "triangle_strip"
        self._index_buffer = IndexBuffer()

        self.shared_program.frag["sampler_type"] = self.texture.glsl_sampler_type
        self.shared_program.frag["sample"] = self.texture.glsl_sample

        # Only show back faces of cuboid. This is required because if we are
        # inside the volume, then the front faces are outside of the clipping
        # box and will not be drawn.
        self.set_gl_state("translucent", cull_face=False)

        self.relative_step_size = relative_step_size
        self.freeze()


RGBAVolume = create_visual_node(RGBAVolumeVisual)
    def normalize(self, normalize):
        self._normalize = normalize
        self._update_image()

    def _calculate_spectrogram(self):
        if self._x is not None:
            x = self._x
            nan_mean = np.nanmean(x)
            idx = np.isnan(x)
            x[idx] = nan_mean
            data = stft(x, self._n_fft, self._step, self._fs, self._window)
            data = np.abs(data)
            data = 20 * np.log10(data) if self._color_scale == 'log' else data
            if self._normalize:
                for i in range(data.shape[0]):
                    data[i, :] -= np.mean(data[i, :])
                    data[i, :] /= np.std(data[i, :])
            return data
        else:
            return None

    def _update_image(self):
        data = self._calculate_spectrogram()
        self.set_data(data)
        self.update()
        if self._clim_auto:
            self.clim = 'auto'


Spectrogram = create_visual_node(SpectrogramVisual)
            ], dtype=np.float32))

        # Set up RGBA texture
        self.texture = tex_cls((10, 10, 10, 4), interpolation='linear',
                                                wrapping='clamp_to_edge')
        self.texture.set_data(data.astype(np.float32))
        self.shared_program['u_volumetex'] = self.texture

        self._vol_shape = data.shape[:-1]
        self.shared_program['u_shape'] = self._vol_shape[::-1]

        self.shared_program['a_position'] = self._vertices
        self.shared_program['a_texcoord'] = self._texcoord

        self._draw_mode = 'triangle_strip'
        self._index_buffer = IndexBuffer()

        self.shared_program.frag['sampler_type'] = self.texture.glsl_sampler_type
        self.shared_program.frag['sample'] = self.texture.glsl_sample

        # Only show back faces of cuboid. This is required because if we are
        # inside the volume, then the front faces are outside of the clipping
        # box and will not be drawn.
        self.set_gl_state('translucent', cull_face=False)

        self.relative_step_size = relative_step_size
        self.freeze()


RGBAVolume = create_visual_node(RGBAVolumeVisual)
Beispiel #6
0
        v_norm = meshdata.get_vertex_normals(indexed='faces').astype(float32)
        self._normals = VertexBuffer(v_norm)

        if color is not None:
            if len(color) == 3:
                color = r_[array(color), 1.]
            self._colors = color

        else:
            v_col = meshdata.get_vertex_colors(indexed='faces').astype(float32)
            self._colors = VertexBuffer(v_col)

        self._light_vec = light_vec

        self._draw_mode = 'triangles'
        self.set_gl_state('opaque', depth_test=True, cull_face=True)

    def update_color(self, color):
        self._colors = color

    def _prepare_transforms(self, view):
        view.view_program.vert['transform'] = view.get_transform()

    def _prepare_draw(self, view):
        self.shared_program.vert['position'] = self._vertices
        self.shared_program.vert['normal'] = self._normals
        self.shared_program.vert['color'] = self._colors
        self.shared_program.frag['light_vec'] = self._light_vec

SimpleMesh = create_visual_node(SimpleMeshVisual)
Beispiel #7
0
            alpha = 0.1
        else:
            self.set_gl_state('translucent', depth_test=True, cull_face=False)
            alpha = 1.
        self._translucent = value
        self.alpha = alpha
        self.update_gl_state()

    # ----------- ALPHA -----------
    @property
    def alpha(self):
        """Get the alpha value."""
        return self._alpha

    @alpha.setter
    def alpha(self, value):
        """Set alpha value."""
        assert isinstance(value, (int, float))
        value = min(value, .1) if self._translucent else 1.
        self._alpha = value
        self.shared_program.frag['u_alpha'] = value
        self.update()

    @property
    def minmax(self):
        """Get the data limits value."""
        return self._data_lim[self._n_overlay - 1]


BrainMesh = create_visual_node(BrainVisual)
Beispiel #8
0
                ip = (i + 1) % segments if closed else i + 1
                jp = (j + 1) % tube_points

                index_a = i * tube_points + j
                index_b = ip * tube_points + j
                index_c = ip * tube_points + jp
                index_d = i * tube_points + jp

                indices.append([index_a, index_b, index_d])
                indices.append([index_b, index_c, index_d])

        vertices = grid.reshape(grid.shape[0] * grid.shape[1], 3)

        color = ColorArray(color)
        if vertex_colors is None:
            point_colors = np.resize(color.rgba, (len(points), 4))
            vertex_colors = np.repeat(point_colors, tube_points, axis=0)

        indices = np.array(indices, dtype=np.uint32)

        MeshVisual.__init__(self,
                            vertices,
                            indices,
                            vertex_colors=vertex_colors,
                            face_colors=face_colors,
                            shading=shading,
                            mode=mode)


Tube = create_visual_node(TubeVisual)
Beispiel #9
0
from vispy.color import get_colormap
from vispy.scene.visuals import create_visual_node
from vispy.visuals.shaders import Function

from .vendored import VolumeVisual as BaseVolumeVisual
from .vendored.volume import FRAG_SHADER, frag_dict

BaseVolume = create_visual_node(BaseVolumeVisual)

ATTENUATED_MIP_SNIPPETS = dict(
    before_loop="""
        float maxval = -99999.0; // The maximum encountered value
        float sumval = 0.0; // The sum of the encountered values
        float scaled = 0.0; // The scaled value
        int maxi = 0;  // Where the maximum value was encountered
        vec3 maxloc = vec3(0.0);  // Location where the maximum value was encountered
        """,
    in_loop="""
        sumval = sumval + val;
        scaled = val * exp(-u_attenuation * (sumval - 1) / u_relative_step_size);
        if( scaled > maxval ) {
            maxval = scaled;
            maxi = iter;
            maxloc = loc;
        }
        """,
    after_loop="""
        gl_FragColor = applyColormap(maxval);
        """,
)
ATTENUATED_MIP_FRAG_SHADER = FRAG_SHADER.format(**ATTENUATED_MIP_SNIPPETS)
Beispiel #10
0
            return False

        if self._recompute:
            self._vertices_cache, self._faces_cache = isosurface(
                np.ascontiguousarray(self._data), self._level)
            self._recompute = False
            self._update_meshvisual = True

        if self._update_meshvisual:
            MeshVisual.set_data(self,
                                vertices=self._vertices_cache,
                                faces=self._faces_cache,
                                vertex_colors=self._vertex_colors,
                                face_colors=self._face_colors,
                                color=self._color)
            self._update_meshvisual = False

    if HAS_PREPARE_DRAW:

        def _prepare_draw(self, view):
            self._update_mesh_visual()
            return MeshVisual._prepare_draw(self, view)
    else:

        def draw(self, transforms):
            self._update_mesh_visual()
            return MeshVisual.draw(self, transforms)


Isosurface = create_visual_node(IsosurfaceVisual)
Beispiel #11
0
                 width=1,
                 height=1,
                 depth=1,
                 width_segments=1,
                 height_segments=1,
                 depth_segments=1,
                 planes=None,
                 uniform_colour=(0.5, 0.5, 1.0),
                 uniform_opacity=1.0,
                 vertex_colours=None,
                 wireframe=False,
                 wireframe_offset=None):
        vertices, faces, outline = create_box(width, height, depth,
                                              width_segments,
                                              height_segments,
                                              depth_segments,
                                              planes)

        PrimitiveVisual.__init__(
            self,
            vertices['position'],
            outline if wireframe else faces,
            uniform_colour,
            uniform_opacity,
            vertex_colours,
            wireframe,
            wireframe_offset)


Box = create_visual_node(BoxVisual)
        self.__wireframe = wireframe
        self.__wireframe_offset = wireframe_offset
        mode = 'lines' if self.__wireframe else 'triangles'

        uniform_colour = ColorArray(uniform_colour, alpha=uniform_opacity).rgba
        if vertex_colours is not None:
            if vertex_colours.shape[-1] == 3:
                vertex_colours = np.hstack(
                    (vertex_colours,
                     np.full((vertex_colours.shape[0], 1), uniform_opacity)))
            else:
                vertex_colours[..., 3] = uniform_opacity

        MeshVisual.__init__(
            self,
            vertices,
            faces,
            vertex_colours,
            None,
            uniform_colour,
            mode=mode)

    def draw(self, transforms):
        MeshVisual.draw(self, transforms)
        if self.__wireframe and self.__wireframe_offset:
            set_state(polygon_offset=self.__wireframe_offset,
                      polygon_offset_fill=True)


Primitive = create_visual_node(PrimitiveVisual)
        self.shared_program.vert['u_size'] = value
        self.update()

    # ----------- WIDTH -----------
    @property
    def width(self):
        """Get the width value."""
        return self._width

    @width.setter
    def width(self, value):
        """Set width value."""
        self._width = value
        self.update()

    # ----------- METHOD -----------
    @property
    def method(self):
        """Get the method value."""
        return self._method

    @method.setter
    def method(self, value):
        """Set method value."""
        self._method = value
        self._smooth_line = value == 'agg'
        self.update()


GridSignal = create_visual_node(GridSignalVisual)
Beispiel #14
0
        """Set line_width value."""
        assert isinstance(value, (int, float))
        self._line_width = value

    # ----------- ANTIALIAS -----------
    @property
    def antialias(self):
        """Get the antialias value."""
        return self._antialias

    @antialias.setter
    def antialias(self, value):
        """Set antialias value."""
        assert isinstance(value, bool)
        self._antialias = value

    # ----------- UNICOLOR -----------
    @property
    def unicolor(self):
        """Get the unicolor value."""
        return self._unicolor

    @unicolor.setter
    def unicolor(self, value):
        """Set unicolor value."""
        assert isinstance(value, bool)
        self.shared_program.vert['u_unicolor'] = int(value)
        self._unicolor = value

Hypnogram = create_visual_node(HypogramVisual)  # noqa
Beispiel #15
0
    def update_ref_color(self, plot_ref=0):

        self.shared_program['u_plot_ref'] = plot_ref
        self.update()

    def update_sel_color(self, plot_sel=0):

        self.shared_program['u_plot_sel'] = plot_sel
        self.update()

    def update_point_size(self, point_size):

        self.shared_program['u_point_size'] = point_size
        self.update()

    def update_scale(self, scale):

        print scale

        self.shared_program['u_scale'] = scale
        self.update()

    def _prepare_transforms(self, view):
        # xform = view.transforms.get_transform()
        # view.view_program.vert['transform'] = xform
        view.view_program.vert['transform'] = view.get_transform()


MyMarkerNode = visuals.create_visual_node(MyMarkerVisual)
        self.shared_program.vert['u_size'] = value
        self.update()

    # ----------- WIDTH -----------
    @property
    def width(self):
        """Get the width value."""
        return self._width

    @width.setter
    def width(self, value):
        """Set width value."""
        self._width = value
        self.update()

    # ----------- METHOD -----------
    @property
    def method(self):
        """Get the method value."""
        return self._method

    @method.setter
    def method(self, value):
        """Set method value."""
        self._method = value
        self._smooth_line = value == 'agg'
        self.update()


GridSignal = create_visual_node(GridSignalVisual)
Beispiel #17
0
    def m(self):
        """Get n_rows * n_cols."""
        return self._nrows * self._ncols

    # ----------- N -----------
    @property
    def n(self):
        """Get the number of time points."""
        return self._n

    @n.setter
    def n(self, value):
        """Set n value."""
        if value < 5:
            raise ValueError("The number of time points must be at least >= 5")
        self._n = value

    # ----------- MINMAX -----------
    @property
    def minmax(self):
        """Get the minmax value."""
        return self._minmax

    @minmax.setter
    def minmax(self, value):
        """Set minmax value."""
        self._minmax = value


NdpltMesh = create_visual_node(NdpltVisual)
Beispiel #18
0
    # ----------- ZMAX -----------
    @property
    def zmax(self):
        """Get the zmax value."""
        return self._zmax

    @zmax.setter
    def zmax(self, value):
        """Set zmax value."""
        value = self._vertices[:, 2].max() + 1 if value is None else value
        assert isinstance(value, (int, float))
        self.shared_program.frag['u_zmax'] = value
        self._zmax = value

    # ----------- INV_LIGHT -----------
    @property
    def inv_light(self):
        """Get the inv_light value."""
        return self._inv_light

    @inv_light.setter
    def inv_light(self, value):
        """Set inv_light value."""
        assert isinstance(value, bool)
        value = -1 if value else 1
        self.shared_program.vert['u_inv_light'] = value
        self._inv_light = value


BrainMesh = create_visual_node(BrainVisual)
Beispiel #19
0
    all_vec_norm = norm(all_vec, axis=1)

    # Normalise vectors if necessary
    where = all_vec_norm > epsilon
    all_vec[where, :] /= all_vec_norm[where].reshape((sum(where), 1))

    # Precompute inner dot product
    dp = np.sum(tangents[:-1] * tangents[1:], axis=1)
    # Clip
    cl = np.clip(dp, -1, 1)
    # Get theta
    th = np.arccos(cl)

    # Compute normal and binormal vectors along the path
    for i in range(1, len(points)):
        normals[i] = normals[i - 1]

        vec_norm = all_vec_norm[i - 1]
        vec = all_vec[i - 1]
        if vec_norm > epsilon:
            normals[i] = rotate(-np.degrees(th[i - 1]),
                                vec)[:3, :3].dot(normals[i])

    binormals = np.cross(tangents, normals)

    return tangents, normals, binormals


Tube = create_visual_node(TubeVisual)
MeshNeuron = create_visual_node(NeuronVisual)
Beispiel #20
0
from vispy.scene.visuals import create_visual_node

from .vendored import ImageVisual

Image = create_visual_node(ImageVisual)
Beispiel #21
0
    for v in order:
        v.draw()


def on_resize(event):
    # Set canvas viewport and reconfigure visual transforms to match.
    vp = (0, 0, canvas.physical_size[0], canvas.physical_size[1])
    canvas.context.set_viewport(*vp)
    for v in order:
        v.transforms.configure(canvas=canvas, viewport=vp)


canvas.events.resize.connect(on_resize)
on_resize(None)

Line = create_visual_node(LineVisual)
canvas2 = SceneCanvas(keys='interactive', title='Scene Canvas', show=True)
v = canvas2.central_widget.add_view(margin=10)
v.border_color = (1, 1, 1, 1)
v.bgcolor = (0.3, 0.3, 0.3, 1)
v.camera = 'panzoom'
line2 = Line(pos, parent=v.scene)


def mouse(ev):
    print(ev)


v.events.mouse_press.connect(mouse)

if __name__ == '__main__':
Beispiel #22
0
"""

from vispy.visuals.infinite_line import InfiniteLineVisual
from vispy.visuals.visual import CompoundVisual
from vispy.scene.visuals import create_visual_node


class CrosshairVisual(CompoundVisual):
    def __init__(self, pos=None, color=(1.0, 1.0, 1.0, 1.0)):

        self._vline = InfiniteLineVisual(vertical=True)
        self._hline = InfiniteLineVisual(vertical=False)

        CompoundVisual.__init__(self, [self._vline, self._hline])

        self.set_data(pos, color)

    def set_data(self, pos=None, color=None):

        if pos is None:
            self._vline.set_data(pos, color)
            self._hline.set_data(pos, color)
        else:
            self._vline.set_data(pos[0], color)
            self._hline.set_data(pos[1], color)

        self.update()


Crosshair = create_visual_node(CrosshairVisual)
        # Only show back faces of cuboid. This is required because if we are
        # inside the volume, then the front faces are outside of the clipping
        # box and will not be drawn.
        self.set_gl_state('translucent', cull_face=False)

        # Set data
        self.set_data(vol, clim)

        # Set params
        self.method = 'iso'
        self.relative_step_size = relative_step_size
        self.threshold = threshold if (threshold is not None) else vol.mean()
        self.step = step
        self.freeze()

    @property
    def step(self):
        return self._step

    @step.setter
    def step(self, value):
        self._step = int(value)
        if 'level' in self.shared_program:
            self.unfreeze()
            self.shared_program['level'] = self._step
            self.freeze()
        self.update()


MultiIsoVisual = create_visual_node(MultiIsoVisual)
Beispiel #24
0
            ambient=.2,
            diffuse=.8,
        )
        self._draw_mode = 'triangles'
        # self.set_gl_state('opaque', depth_test=True, cull_face=True)
        self.set_gl_state('translucent',
                          depth_test=True,
                          cull_face=False,
                          blend=True,
                          blend_func=('src_alpha', 'one_minus_src_alpha'))

    def _prepare_transforms(self, view):
        view.view_program.vert['transform'] = view.get_transform()

    def _prepare_draw(self, view):
        self.shared_program.vert['a_position'] = self._vertices
        self.shared_program.vert['a_normal'] = self._normals
        self.shared_program.vert['a_color'] = self._colors

    def set_light(self, position=None, ambient=None, diffuse=None):
        if position is not None:
            self.shared_program.frag['u_light_position'] = position
        if ambient is not None:
            self.shared_program.frag['u_ambient'] = ambient
        if diffuse is not None:
            self.shared_program.frag['u_diffuse'] = diffuse
        self.update()


SurfaceMesh = create_visual_node(SurfaceMeshVisual)
Beispiel #25
0
        self._wireframe = wireframe
        self._wireframe_offset = wireframe_offset
        mode = 'lines' if self._wireframe else 'triangles'

        uniform_colour = ColorArray(uniform_colour, alpha=uniform_opacity).rgba
        if vertex_colours is not None:
            if vertex_colours.shape[-1] == 3:
                vertex_colours = np.hstack(
                    (vertex_colours,
                     np.full((vertex_colours.shape[0], 1), uniform_opacity,
                             DEFAULT_FLOAT_DTYPE)))
            else:
                vertex_colours[..., 3] = uniform_opacity

        MeshVisual.__init__(self,
                            vertices,
                            faces,
                            vertex_colours,
                            None,
                            uniform_colour,
                            mode=mode)

    def draw(self):
        MeshVisual.draw(self)
        if self._wireframe and self._wireframe_offset:
            set_state(polygon_offset=self._wireframe_offset,
                      polygon_offset_fill=True)


Primitive = create_visual_node(PrimitiveVisual)
Beispiel #26
0
            lr = lr.T

        return center, ul, ur, ll, lr

    def update_size(self, length):

        front_vertices = self.set_data(self.fx, self.fy, self.u0, self.v0,
                                       length, self.nW, self.nH, self.rot,
                                       self.trans)

        if (isinstance(self.image, np.ndarray)):
            #self.image_visual.set_data(front_vertices, self.image)
            self.image_visual.update_data(front_vertices)


CameraNode = visuals.create_visual_node(CameraVisual)
""" get points from reconstruction results """


def get_points(reconstruction, has_color=1):

    num_points = len(reconstruction.points)
    position = np.ones((num_points, 3)).astype(np.float32)
    color = np.ones((num_points, 4)).astype(np.float32)

    num = 0
    for key, value in reconstruction.points.iteritems():

        position[num, 0] = value.coordinates[0]
        position[num, 1] = value.coordinates[1]
        position[num, 2] = value.coordinates[2]
Beispiel #27
0
                                vertex_colors=vertex_colors,
                                face_colors=face_colors,
                                color=color)
        if edge_color:
            self._border = MeshVisual(vertices=mesh.get_vertices(),
                                      faces=mesh.get_edges(),
                                      color=edge_color,
                                      mode='lines')
        else:
            self._border = MeshVisual()

        CompoundVisual.__init__(self, [self._mesh, self._border], **kwargs)
        self.mesh.set_gl_state(polygon_offset_fill=True,
                               polygon_offset=(1, 1),
                               depth_test=True)

    @property
    def mesh(self):
        """The vispy.visuals.MeshVisual that used to fil in.
        """
        return self._mesh

    @property
    def border(self):
        """The vispy.visuals.MeshVisual that used to draw the border.
        """
        return self._border


Ellipse = create_visual_node(EllipseVisual)
        if self._data is None or self._level is None:
            return False

        if self._recompute:
            self._vertices_cache, self._faces_cache = isosurface(np.ascontiguousarray(self._data),
                                                                 self._level)
            self._recompute = False
            self._update_meshvisual = True

        if self._update_meshvisual:
            MeshVisual.set_data(self,
                                vertices=self._vertices_cache,
                                faces=self._faces_cache,
                                vertex_colors=self._vertex_colors,
                                face_colors=self._face_colors,
                                color=self._color)
            self._update_meshvisual = False

    if HAS_PREPARE_DRAW:
        def _prepare_draw(self, view):
            self._update_mesh_visual()
            return MeshVisual._prepare_draw(self, view)
    else:
        def draw(self, transforms):
            self._update_mesh_visual()
            return MeshVisual.draw(self, transforms)


Isosurface = create_visual_node(IsosurfaceVisual)
Beispiel #29
0
    def _prepare_transforms(self, view):
        xform = view.transforms.get_transform()
        view.view_program.vert['transform'] = xform

    def _prepare_draw(self, view):
        if self._symbol is None:
            return False
        view.view_program['u_px_scale'] = view.transforms.pixel_scale
        if self.scaling:
            tr = view.transforms.get_transform('visual', 'document').simplified
            scale = np.linalg.norm((tr.map([1, 0]) - tr.map([0, 0]))[:2])
            view.view_program['u_scale'] = scale
        else:
            view.view_program['u_scale'] = 1

        from vispy.gloo import gl
        view.view_program['u_viewport'] = gl.glGetParameter(gl.GL_VIEWPORT)
        view.view_program['u_SimulatePointCoord'] = True

    def _compute_bounds(self, axis, view):
        pos = self._data['a_position']
        if pos is None:
            return None
        if pos.shape[1] > axis:
            return (pos[:, axis].min(), pos[:, axis].max())
        else:
            return (0, 0)


Markers = visuals.create_visual_node(MarkersVisual)  # noqa
Beispiel #30
0
#LinePlot = create_visual_node(visuals.LinePlotVisual)
#Markers = create_visual_node(visuals.MarkersVisual)
#Mesh = create_visual_node(visuals.MeshVisual)
#Plane = create_visual_node(visuals.PlaneVisual)
#Polygon = create_visual_node(visuals.PolygonVisual)
#Rectangle = create_visual_node(visuals.RectangleVisual)
#RegularPolygon = create_visual_node(visuals.RegularPolygonVisual)
#ScrollingLines = create_visual_node(visuals.ScrollingLinesVisual)
#Spectrogram = create_visual_node(visuals.SpectrogramVisual)
#SurfacePlot = create_visual_node(visuals.SurfacePlotVisual)
#Text = create_visual_node(visuals.TextVisual)
#Tube = create_visual_node(visuals.TubeVisual)
#


create_visual_node(visuals.XYZAxisVisual)

class mbFrame(scene.XYZAxis):
    """
    creates a custom Body Frame, a 3D axis for indicating coordinate system orientation. Axes are x=red, y=green, z=blue.
        create_visual_node(visuals.CubeVisual)

    maybee this will become the subvisual in every mbVisual

    :param view: the view as obtained by call to e.g. scene.SceneCanvas().central_widget.add_view()
    :param a: first edge lenght (in x direction)
    :param b: second edge lenght (in y direction)
    :param c: third edge lenght (in z direction)
    :param face_color: the faces color
    :param edge_color: the edge (wire) color
Beispiel #31
0
        Wireframe offset.

    Notes
    -----
    -   `vertex_colours` argument takes precedence over `uniform_colour` if
        provided.
    -   `uniform_opacity` argument will be stacked to `vertex_colours` argument
        if the latter last dimension is equal to 3.
    """
    def __init__(self,
                 width=1,
                 height=1,
                 width_segments=1,
                 height_segments=1,
                 direction='+z',
                 uniform_colour=(0.5, 0.5, 1.0),
                 uniform_opacity=1.0,
                 vertex_colours=None,
                 wireframe=False,
                 wireframe_offset=None):
        vertices, faces, outline = create_plane(width, height, width_segments,
                                                height_segments, direction)

        PrimitiveVisual.__init__(self, vertices['position'],
                                 outline if wireframe else faces,
                                 uniform_colour, uniform_opacity,
                                 vertex_colours, wireframe, wireframe_offset)


Plane = create_visual_node(PlaneVisual)
Beispiel #32
0
    def _prepare_transforms(self, view):
        xform = view.transforms.get_transform()
        view.view_program.vert['transform'] = xform

    def _prepare_draw(self, view):
        if self._symbol is None:
            return False
        view.view_program['u_px_scale'] = view.transforms.pixel_scale
        if self.scaling:
            tr = view.transforms.get_transform('visual', 'document').simplified
            scale = np.linalg.norm((tr.map([1, 0]) - tr.map([0, 0]))[:2])
            view.view_program['u_scale'] = scale
        else:
            view.view_program['u_scale'] = 1

        from vispy.gloo import gl
        view.view_program['u_viewport'] = gl.glGetParameter(gl.GL_VIEWPORT)
        view.view_program['u_SimulatePointCoord'] = True

    def _compute_bounds(self, axis, view):
        pos = self._data['a_position']
        if pos is None:
            return None
        if pos.shape[1] > axis:
            return (pos[:, axis].min(), pos[:, axis].max())
        else:
            return (0, 0)

Markers = visuals.create_visual_node(MarkersVisual)  # noqa
Beispiel #33
0
        vertices = []
        indices = []
        vertex_colors = []

        for visual in visuals:
            if not isinstance(visual, MeshVisual):
                raise ValueError('Non-MeshVisual received')

            md = visual._meshdata
            vertices.append(md.get_vertices().copy())
            indices.append(md.get_faces().copy())
            vertex_colors.append(md.get_vertex_colors().copy())

        cum_lens = np.hstack([[0], np.cumsum(list(map(len, vertices)))[:-1]])

        for cur_len, inds in list(zip(cum_lens, indices)):
            inds += cur_len

        vertices = np.vstack(vertices)
        indices = np.vstack(indices)
        vertex_colors = np.vstack(vertex_colors)

        MeshVisual.__init__(self,
                            vertices,
                            indices,
                            vertex_colors=vertex_colors,
                            shading=shading)


MeshCollection = create_visual_node(MeshCollectionVisual)
Beispiel #34
0
from vispy.scene.visuals import create_visual_node

from .vendored import MeshVisual

Mesh = create_visual_node(MeshVisual)
        if self._need_pos_update:
            pos = np.hstack(self._pos).astype(np.float32)
            pos = np.c_[np.arange(self._pos_len, dtype=np.float32), pos]
            self._pos_vbo.set_data(pos)
            self.shared_program['n_lines'] = len(self._line_sizes)
            self._need_pos_update = False

        if self._need_indices_update:
            self._indices_tex.set_data(self._indices.astype(np.float32))
            self._need_indices_update = False

        if self._need_color_update:
            self._color_vbo.set_data(self._color / self._lut.shape[0])
            self._need_color_update = False

        if self._need_index_update:
            self._index_buffer.set_data(self._create_new_conn())
            self._need_index_update = False

        if self._need_scales_update:
            self._scales_tex.set_data(self._scales.astype(np.float32))
            self._need_scales_update = False

        if self._need_offsets_update:
            self._offsets_tex.set_data(self._offsets.astype(np.float32))
            self._need_offsets_update = False


Multiline = create_visual_node(MultilineVisual)
Beispiel #36
0
                        lmin = start * (step / j)
                        lmax = lmin + step * (k - 1.0)
                        lstep = step

                        s = _simplicity(q, Q, j, lmin, lmax, lstep)
                        c = _coverage(dmin, dmax, lmin, lmax)
                        d = _density(k, m, dmin, dmax, lmin, lmax)
                        leg = 1.  # _legibility(lmin, lmax, lstep)

                        score = w[0] * s + w[1] * c + w[2] * d + w[3] * leg

                        if (score > best_score
                                and (not only_inside or
                                     (lmin >= dmin and lmax <= dmax))):
                            best_score = score
                            best = (lmin, lmax, lstep, q, k)
                    z += 1
                k += 1
            if k == n_max:
                raise RuntimeError('could not converge on ticks')
        j += 1
    if j == n_max:
        raise RuntimeError('could not converge on ticks')

    if best is None:
        raise RuntimeError('could not converge on ticks')
    return np.arange(best[4]) * best[2] + best[0]


Axis = create_visual_node(AxisVisual)
from typing import List

from vispy.scene.visuals import create_visual_node

from ...layers.image.experimental import OctreeChunk
from ...layers.image.experimental.octree_image import OctreeImage
from ...utils.events import EmitterGroup
from ...utils.perf import block_timer
from ..vispy_image_layer import VispyImageLayer
from .tile_grid import TileGrid
from .tiled_image_visual import TiledImageVisual

# Create the scene graph Node version of this visual. Visuals are a mix of
# the visual itself and a scene graph node. The scene graph node is what
# can added to the scene and transformed.
TiledImageNode = create_visual_node(TiledImageVisual)

LOGGER = logging.getLogger("napari.octree.visual")


@dataclass
class ChunkStats:
    """Statistics about chunks during the update process."""

    drawable: int = 0
    start: int = 0
    remaining: int = 0
    low: int = 0
    final: int = 0

    @property
Beispiel #38
0
            self._changed['width'] = False

        if self._changed['index']:
            if self._index is None:
                self._index = np.ones(len(self.pos), 'bool')

            sub_conn = self._conn[self._index]
            sub_conn[:-1, 0] = sub_conn[1:, 1]
            self._index_buffer.set_data(sub_conn)
            self._changed['index'] = False

    def _compute_bounds(self, axis, view):

        # Can and should we calculate bounds?
        if (self._bounds is None) and self._pos is not None:
            pos = self._pos
            self._bounds = [(pos[:, d].min(), pos[:, d].max())
                            for d in range(pos.shape[1])]

        # Return what we can
        if self._bounds is None:
            return
        else:
            if axis < len(self._bounds):
                return self._bounds[axis]
            else:
                return (0, 0)


SimpleLine = create_visual_node(SimpleLineVisual)
Beispiel #39
0
    -   `vertex_colours` argument takes precedence over `uniform_colour` if
        provided.
    -   `uniform_opacity` argument will be stacked to `vertex_colours` argument
        if the latter last dimension is equal to 3.
    """

    def __init__(self,
                 width=1,
                 height=1,
                 depth=1,
                 width_segments=1,
                 height_segments=1,
                 depth_segments=1,
                 planes=None,
                 uniform_colour=(0.5, 0.5, 1.0),
                 uniform_opacity=1.0,
                 vertex_colours=None,
                 wireframe=False,
                 wireframe_offset=None):
        vertices, faces, outline = create_box(width, height, depth,
                                              width_segments, height_segments,
                                              depth_segments, planes)

        PrimitiveVisual.__init__(self, vertices['position'], outline
                                 if wireframe else faces, uniform_colour,
                                 uniform_opacity, vertex_colours, wireframe,
                                 wireframe_offset)


Box = create_visual_node(BoxVisual)
Beispiel #40
0
    """

    def __init__(
        self,
        width=1,
        height=1,
        width_segments=1,
        height_segments=1,
        direction="+z",
        uniform_colour=(0.5, 0.5, 1.0),
        uniform_opacity=1.0,
        vertex_colours=None,
        wireframe=False,
        wireframe_offset=None,
    ):
        vertices, faces, outline = create_plane(width, height, width_segments, height_segments, direction)

        PrimitiveVisual.__init__(
            self,
            vertices["position"],
            outline if wireframe else faces,
            uniform_colour,
            uniform_opacity,
            vertex_colours,
            wireframe,
            wireframe_offset,
        )


Plane = create_visual_node(PlaneVisual)
        0-------1
        """

        # Order is chosen such that normals face outward; front faces will be
        # culled.
        indices = np.array([2, 6, 0, 4, 5, 6, 7, 2, 3, 0, 1, 5, 3, 7],
                           dtype=np.uint32)

        # Apply
        self._vertices.set_data(pos)
        self._index_buffer.set_data(indices)

    def _compute_bounds(self, axis, view):
        return 0, self._vol_shape[axis]

    def _prepare_transforms(self, view):
        trs = view.transforms
        view.view_program.vert['transform'] = trs.get_transform()

        view_tr_f = trs.get_transform('visual', 'document')
        view_tr_i = view_tr_f.inverse
        view.view_program.vert['viewtransformf'] = view_tr_f
        view.view_program.vert['viewtransformi'] = view_tr_i

    def _prepare_draw(self, view):
        if self._need_vertex_update:
            self._create_vertex_data()
            self._need_vertex_update = False

MultiVolume = create_visual_node(MultiVolumeVisual)
Beispiel #42
0
        self._set_clim_vars()
        self._need_texture_upload = False

    def _build_vertex_data(self):
        # _build_vertex_data should not be used in this class, use the 2-step
        # process of '_build_vertex_tiles' and '_set_vertex_tiles'
        return

    def _set_clim_vars(self):
        self._data_lookup_fn["vmin"] = self._clim[0]
        self._data_lookup_fn["vmax"] = self._clim[1]
        self._data_lookup_fn["gamma"] = self._gamma
        # self._need_texture_upload = True


TiledGeolocatedImage = create_visual_node(TiledGeolocatedImageVisual)

_rgb_texture_lookup = """
    vec4 texture_lookup(vec2 texcoord) {
        if(texcoord.x < 0.0 || texcoord.x > 1.0 ||
        texcoord.y < 0.0 || texcoord.y > 1.0) {
            discard;
        }
        vec4 val = texture2D($texture, texcoord);
        // http://stackoverflow.com/questions/11810158/how-to-deal-with-nan-or-inf-in-opengl-es-2-0-shaders
        if (!(val.r <= 0.0 || 0.0 <= val.r)) {
            val.r = 0;
            val.g = 0;
            val.b = 0;
            val.a = 0;
            return val;
        if self._initial_shape:
            self._data_shape = np.asarray(data.shape, dtype=int)
            self._vol_shape = self._data_shape * self._block_size
            self._program['u_shape'] = self._vol_shape[::-1]
            self._create_vertex_data()
            self._initial_shape = False
        elif np.any(data.shape != self._data_shape):
            raise ValueError(
                "Shape of arrays should be {0} instead of {1}".format(
                    self._vol_shape, data.shape))

    @property
    def enabled(self):
        return [
            self._program['u_enabled_{0}'.format(i)] == 1
            for i in range(self._n_volume_max)
        ]

    def draw(self, transforms):
        if not any(self.enabled):
            return
        else:
            try:
                super(MultiVolumeVisual, self).draw(transforms)
            except:
                pass


MultiVolume = create_visual_node(MultiVolumeVisual)
    def delete(self):
        self.remove_parent(self.parent)
        if self in self.dock.rois:
            self.dock.rois.remove(self)
    
    def draw(self, tr_sys):
        if not self.finished:
            color = np.ones((len(self.points), 3)).astype(np.float32)
            lp = LinePlotVisual(data=self.points, color=color, marker_size=1)
            lp.draw(tr_sys)
        elif len(self.points) > 2:
            PolygonVisual.draw(self, tr_sys)
            self.text.draw(tr_sys)

MyROI = visuals.create_visual_node(ROIVisual)

class ClusterVisual(PolygonVisual):
    def __init__(self, points):
        PolygonVisual.__init__(self, color=None, border_color='white')
        self.points = points
        self.border_points = getBorderPoints(self.points)
        self.pos = np.array(self.border_points, dtype=np.float32)

MyCluster = visuals.create_visual_node(ClusterVisual)

class Cluster():
    def __init__(self, points):
        self.points = points
        self.centroid = np.mean(self.points, 0)
        self.averageDistance = averageDistance(self.points)