Example #1
0
 def set_aspect(self, aspect):
     "Set the aspect of the image, similar to aspect in matplotlib"
     if self.magnify == True:
         if aspect == "auto":
             self.view.camera = MagnifyCamera(
                 mag=1,
                 size_factor=self.magnify_sizefactor,
                 radius_ratio=self.magnify_radius_ratio)
             self.view.camera.set_range()
         elif aspect == "ratio":
             self.view.camera = MagnifyCamera(
                 mag=1,
                 size_factor=self.magnify_sizefactor,
                 aspect=1,
                 radius_ratio=self.magnify_radius_ratio)
             self.view.camera.set_range()
         else:
             print('I dunno this aspect, please use auto or ratio')
     else:
         if aspect == "auto":
             self.view.camera = scene.PanZoomCamera()
             self.view.camera.set_range()
         elif aspect == "ratio":
             self.view.camera = scene.PanZoomCamera(aspect=1)
             self.view.camera.set_range()
         else:
             print('I dunno this aspect, please use auto or ratio')
Example #2
0
def main(dataset_uri):

    logging.basicConfig(level=logging.INFO)

    app.tis = TaggableImageSet(dataset_uri)
    logging.info(f"Loaded image set with {len(app.tis)} items")

    app.image = scene.visuals.Image(app.tis[0], parent=view.scene)
    app.n_current_image = 0

    textstr = "Status bar"
    t1 = scene.visuals.Text(textstr,
                            parent=view.scene,
                            color='red',
                            pos=(300, -20))
    t1.font_size = 14
    app.t1 = t1

    view.camera = scene.PanZoomCamera(aspect=1)
    view.camera.set_range()
    view.camera.flip = (False, True, False)

    update()

    app.run()
Example #3
0
    def __init__(self):
        scene.SceneCanvas.__init__(self, keys='interactive',
                                   size=(800, 800))

        # Create some initial points
        n = 7
        self.unfreeze()
        self.pos = np.zeros((n, 3), dtype=np.float32)
        self.pos[:, 0] = np.linspace(-50, 50, n)
        self.pos[:, 1] = np.random.normal(size=n, scale=10, loc=0)

        # create new editable line
        self.line = EditLineVisual(pos=self.pos, color='w', width=3,
                                   antialias=True, method='gl')

        self.view = self.central_widget.add_view()
        self.view.camera = scene.PanZoomCamera(rect=(-100, -100, 200, 200),
                                               aspect=1.0)
        # the left mouse button pan has to be disabled in the camera, as it
        # interferes with dragging line points
        # Proposed change in camera: make mouse buttons configurable
        self.view.camera._viewbox.events.mouse_move.disconnect(
            self.view.camera.viewbox_mouse_event)

        self.view.add(self.line)
        self.show()
        self.selected_point = None
        scene.visuals.GridLines(parent=self.view.scene)
        self.freeze()
Example #4
0
def main(dataset_uri):

    dataset = DataSet.from_uri(dataset_uri)
    app.dataset = dataset
    app.tags = {}

    app.image_generator = dataset_image_generator(dataset)

    im, app.current_id = next(app.image_generator)
    app.image = scene.visuals.Image(im, parent=view.scene)

    app.counter = 0
    textstr = "Image {}".format(app.counter)
    t1 = scene.visuals.Text(textstr,
                            parent=app.image,
                            color='red',
                            pos=(30, 5))
    t1.font_size = 24
    app.t1 = t1

    view.camera = scene.PanZoomCamera(aspect=1)
    view.camera.set_range()
    view.camera.flip = (False, True, False)

    app.run()
def plot(data):
    canvas = scene.SceneCanvas(keys='interactive')
    canvas.size = 800, 600
    canvas.show()
    view = canvas.central_widget.add_view()
    global i
    i = 10
    image = scene.visuals.Image(-np.mean(data[(i - 10):i, :, :], 0),
                                interpolation='nearest',
                                parent=view.scene,
                                cmap="viridis")
    view.camera = scene.PanZoomCamera(aspect=1)
    view.camera.flip = (0, 1, 0)
    view.camera.set_range()

    def update(ev):
        global i
        i += 1
        image.set_data(-data[i, :, :])
        image.update()
        if i > (data.shape[0] - 2):
            i = 0

    timer = app.Timer(.02, connect=update, start=True)
    app.run()
Example #6
0
def main(dataset_uri):

    dataset = DataSet.from_uri(dataset_uri)

    display.im_ids = iter(identifiers_where_overlay_is_true(dataset, "is_image"))

    imid = next(display.im_ids)

    display.mask_overlay = dataset.get_overlay("mask_ids")
    im = imread(dataset.item_content_abspath(imid))
    mask_im = imread(dataset.item_content_abspath(display.mask_overlay[imid]))
    display.dataset = dataset
    display.image = scene.visuals.Image(im, parent=view.scene)
    display.mask_image = scene.visuals.Image(mask_im, parent=view.scene)
    display.mask_image.visible = False

    textstr = display.dataset.item_properties(imid)['relpath']
    t1 = scene.visuals.Text(textstr, parent=display.image, color='red', pos=(30,5))
    t1.font_size = 24
    display.t1 = t1

    view.camera = scene.PanZoomCamera(aspect=1)
    view.camera.set_range()
    view.camera.flip = (False, True, False)

    app.run()
Example #7
0
    def __init__(self):
        scene.SceneCanvas.__init__(self, keys='interactive',
                                   size=(800, 800))

        self.unfreeze()

        self.view = self.central_widget.add_view()
        self.view.camera = scene.PanZoomCamera(rect=(-100, -100, 200, 200),
                                               aspect=1.0)
        # the left mouse button pan has to be disabled in the camera, as it
        # interferes with dragging line points
        # Proposed change in camera: make mouse buttons configurable
        self.view.camera._viewbox.events.mouse_move.disconnect(
            self.view.camera.viewbox_mouse_event)

        scene.visuals.Text("Click and drag to add objects, " +
                           "right-click to delete.",
                           color='w',
                           anchor_x='left',
                           parent=self.view,
                           pos=(20, 30))

        self.select_arrow = \
            EditVisual(parent=self.view, editable=False,
                       on_select_callback=self.set_creation_mode,
                       callback_argument=None)
        arrow = scene.visuals.Arrow(parent=self.select_arrow,
                                    pos=np.array([[50, 60], [60, 70]]),
                                    arrows=np.array([[60, 70, 50, 60]]),
                                    width=5, arrow_size=15.0,
                                    arrow_type="angle_60",
                                    color="w",
                                    arrow_color="w",
                                    method="agg"
                                    )
        self.select_arrow.add_subvisual(arrow)

        self.rect_button = \
            EditRectVisual(parent=self.view, editable=False,
                           on_select_callback=self.set_creation_mode,
                           callback_argument=EditRectVisual,
                           center=[50, 120], width=30, height=30)
        self.ellipse_button = \
            EditEllipseVisual(parent=self.view,
                              editable=False,
                              on_select_callback=self.set_creation_mode,
                              callback_argument=EditEllipseVisual,
                              center=[50, 170],
                              radius=[15, 10])

        self.objects = []
        self.show()
        self.selected_point = None
        self.selected_object = None
        self.creation_mode = EditRectVisual
        self.mouse_start_pos = [0, 0]
        scene.visuals.GridLines(parent=self.view.scene)
        self.freeze()
Example #8
0
def preview_shifts(a, b, shifts):

    canvas = scene.SceneCanvas(keys="interactive")
    canvas.size = 1024, 1024
    canvas.show()

    # create view box
    vb_xy = scene.widgets.ViewBox(border_color="white", parent=canvas.scene)
    vb_xz = scene.widgets.ViewBox(border_color="white", parent=canvas.scene)
    vb_yz = scene.widgets.ViewBox(border_color="white", parent=canvas.scene)
    vbs = vb_xy, vb_xz, vb_yz

    # put them in a grid
    grid = canvas.central_widget.add_grid()
    grid.padding = 6
    grid.add_widget(vb_xy, 0, 0)
    grid.add_widget(vb_xz, 1, 0)
    grid.add_widget(vb_yz, 0, 1)

    # genereate colormap
    n_colors = 128
    alphas = np.linspace(0.0, 1.0, n_colors)
    color_red = np.c_[np.ones((n_colors, )),
                      np.zeros((n_colors, )),
                      np.zeros((n_colors)), alphas]
    cmap_red = Colormap(color_red)
    color_blue = np.c_[np.zeros((n_colors)),
                       np.zeros((n_colors, )),
                       np.ones((n_colors, )), alphas]
    cmap_blue = Colormap(color_blue)

    # build shifts for mips
    sz, sy, sx = shifts
    nz, ny, nx = a.shape
    shifts = ((sx, sy), (sx, sz), (sy, sz))
    print(shifts)

    # create visuals
    i = 0
    for im, cm in zip((a, b), (cmap_red, cmap_blue)):
        mips = [im.max(axis=axis) for axis in range(3)]
        for vb, mip, shift in zip(vbs, mips, shifts):
            image = scene.visuals.Image(mip, cmap=cm, parent=vb.scene)
            image.set_gl_state("translucent", depth_test=False)

            # apply transformation
            if i > 0:
                image.transform = scene.STTransform(translate=shift)
            else:
                i += 1

    # assign cameras
    for vb in vbs:
        vb.camera = scene.PanZoomCamera(aspect=1)
        vb.camera.set_range()
        vb.camera.flip = (0, 1, 0)

    app.run()
Example #9
0
 def __init__(self):
     """
     Setup the plot canvas..
     """
     self.canvas = scene.SceneCanvas(keys=None, size=(300, 1200))
     self.view = self.canvas.central_widget.add_view()
     self.view.camera = scene.PanZoomCamera()
     self.tree = TreeVisual(parent=None)
     self.view.add(self.tree)
Example #10
0
 def __init__(self):
     # Initialize canvas
     scene.SceneCanvas.__init__(self, keys='interactive',
                                size=(800, 600))
     # Unfreeze
     self.unfreeze()
     # Create some initial points
     self.pos = np.empty((1,3),dtype=np.float32)
     # create new editable line
     self.objects = {
         'markers'   : EditMarkerVisual( pos=self.pos, 
                                         face_color='w', 
                                         scaling=True    ),
         'spline'    : SplineVisual( pos=self.pos, 
                                     color='w', 
                                     width=1, 
                                     antialias=False, 
                                     method='gl'         )
         }
     # Add view and camera
     self.view = self.central_widget.add_view()
     self.view.camera = scene.PanZoomCamera(rect=(-100, -100, 200, 200),
                                            aspect=1.0)
     # Disable mouse press events for the camera
     self.view.camera._viewbox.events.mouse_move.disconnect(
         self.view.camera.viewbox_mouse_event)
     # Visual objects
     self.view.add( self.objects['markers'] )
     self.view.add( self.objects['spline'] )
     scene.visuals.GridLines(parent=self.view.scene)
     # Add first point (cursor)
     self.activeCursor   = True
     self.lastPoint      = [1.0,1.0]
     self.objects['spline'].addPoint([0.0,0.0])
     # Settings
     self.settings={
         'mode'              : ['define',    self.setMode],
         'polynomialOrder'   : [3,           self.objects['spline'].setPolynomialOrder],
         'snapToGrid'        : [False,       lambda state: state]
     }
     # Modes
     self.modes = {
         'define'    : CanvasDefineMode(self),
         'edit'      : CanvasEditMode(self)
     }
     # Initialize event handlers
     self.eventHandlers = {
             'on_mouse_press'        : self.modes[self.settings['mode'][0]].on_mouse_press,
             'on_mouse_release'      : self.modes[self.settings['mode'][0]].on_mouse_release,
             'on_mouse_move'         : self.modes[self.settings['mode'][0]].on_mouse_move
         }
     # Freeze
     self.freeze()
 def __init__(self, parent=None):
     """Init."""
     # Add PanZoom cameras to each box :
     parent['Sagit'].camera = scene.PanZoomCamera()
     parent['Coron'].camera = scene.PanZoomCamera()
     parent['Axial'].camera = scene.PanZoomCamera()
     # Define three images (Sagittal, Coronal, Axial) :
     kwargs_im = {'interpolation': 'bilinear'}
     self._cspSagit = visu.Image(name='SagitSplit', **kwargs_im)
     self._cspCoron = visu.Image(name='CoronSplit', **kwargs_im)
     self._cspAxial = visu.Image(name='AxialSplit', **kwargs_im)
     # Define three text object :
     kwargs_txt = {
         'color': 'white',
         'font_size': 2,
         'anchor_x': 'left',
         'anchor_y': 'bottom'
     }
     self._cspTxtSagit = visu.Text(text='Sagit', **kwargs_txt)
     self._cspTxtCoron = visu.Text(text='Coron', **kwargs_txt)
     self._cspTxtAxial = visu.Text(text='Axial', **kwargs_txt)
     # Add each image to parent :
     parent['Sagit'].add(self._cspSagit)
     parent['Coron'].add(self._cspCoron)
     parent['Axial'].add(self._cspAxial)
     # Add text to parent :
     parent['Sagit'].add(self._cspTxtSagit)
     parent['Coron'].add(self._cspTxtCoron)
     parent['Axial'].add(self._cspTxtAxial)
     # Add transformations :
     r90 = vist.MatrixTransform()
     r90.rotate(90, (0, 0, 1))
     r180 = vist.MatrixTransform()
     r180.rotate(180, (0, 0, 1))
     self._cspSagit.transform = r90
     self._cspCoron.transform = r90
     self._cspAxial.transform = r180
     self._parent_sp = parent
Example #12
0
    def __init__(self):
        scene.SceneCanvas.__init__(self, keys='interactive', size=(800, 600))

        self.unfreeze()

        # Initialize backend
        self.view = self.central_widget.add_view()
        self.view.camera = scene.PanZoomCamera(rect=(-100, -100, 200, 200),
                                               aspect=1.0)

        # Initialize state storage
        self.eventClass = EventHandlerClass(canvas=self)
        self.objects = {}
        self.observers = []

        self.freeze()
Example #13
0
    def __init__(self, parent=None):
        self.canvas = scene.SceneCanvas(keys='interactive')
        self.canvas.size = 800, 600
        self.canvas.show()
        self.canvas._send_hover_events = True  # temporary workaround

        self.view = self.canvas.central_widget.add_view()
        self.view.camera = scene.PanZoomCamera(aspect=1)
        self.view.camera.flip = (0, 1, 0)
        self.image = scene.visuals.Image(interpolation='nearest',
                                         parent=self.view.scene,
                                         cmap="viridis")

        @self.canvas.events.mouse_press.connect
        def mouse_press(event):
            x, y = self.get_position(event)
            return x, y
def main(image_fpath):
    img_data = imread(image_fpath)
    xdim, ydim = img_data.shape

    im = np.zeros((xdim, ydim, 3), dtype=np.uint8)
    for k, v in colors.items():
        im[np.where(img_data == k)] = v
    image = scene.visuals.Image(im, parent=view.scene)

    t1 = scene.visuals.Text('Text in root scene (24 pt)',
                            parent=image,
                            color='red',
                            pos=(100, 100))
    t1.font_size = 24
    # Set 2D camera (the camera will scale to the contents in the scene)
    view.camera = scene.PanZoomCamera(aspect=1)
    view.camera.set_range()
    view.camera.flip = (False, True, False)

    app.run()
async def viewer(receive_channel, shape):
    display_shape = (512, 512)

    # init app
    app = Application()
    app.create()

    # init viewer
    canvas = scene.SceneCanvas(app=app, keys="interactive")
    canvas.size = display_shape

    # create view and image
    view = canvas.central_widget.add_view()

    # lock view
    view.camera = scene.PanZoomCamera(aspect=1, interactive=False)
    view.camera.flip = (0, 1, 0)

    image = scene.visuals.Image(np.empty(display_shape, np.uint8),
                                parent=view.scene,
                                cmap="grays")
    view.camera.set_range(margin=0)

    canvas.show()

    async with receive_channel:
        async for frame in receive_channel:
            # logger.debug(f".... average {frame.mean():.2f}")

            # resize
            frame = transform.resize(frame, display_shape)
            # rescale intensity to 8-bit
            frame = exposure.rescale_intensity(frame, out_range=np.uint8)
            # change dtype
            frame = frame.astype(np.uint8)

            image.set_data(frame)

            canvas.update()
            app.process_events()
Example #16
0
canvas.show()

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

interpolation = 'bicubic'
img_data = read_png(load_data_file('mona_lisa/mona_lisa_sm.png'))
image = scene.visuals.Image(img_data,
                            interpolation=interpolation,
                            parent=view.scene,
                            method='impostor')
level = 10
iso = IsolineFilter(level=level, width=1., color='white')

# Set 2D camera (the camera will scale to the contents in the scene)
view.camera = scene.PanZoomCamera(aspect=1)
# flip y-axis to have correct aligment
view.camera.flip = (0, 1, 0)
# select face part
view.camera.rect = (160, 130, 240, 200)

canvas.title = ('Spatial Filtering using %s Filter - Isoline %d level' %
                (image.interpolation, iso.level))

# get interpolation functions from Image
names = image.interpolation_functions
act = names.index(interpolation)


# Implement key presses
@canvas.events.key_press.connect
Example #17
0
# Create some visuals to show
# AK: Ideally, we could just create one visual that is present in all
# scenes, but that results in flicker for the PanZoomCamera, I suspect
# due to errors in transform caching.
im1 = io.load_crate().astype('float32') / 255
#image1 = scene.visuals.Image(im1, grid=(20, 20), parent=scenes)
for par in scenes:
    image = scene.visuals.Image(im1, grid=(20, 20), parent=par)

#vol1 = np.load(io.load_data_file('volume/stent.npz'))['arr_0']
#volume1 = scene.visuals.Volume(vol1, parent=scenes)
#volume1.transform = scene.STTransform(translate=(0, 0, 10))

# Assign cameras
vb1.camera = scene.BaseCamera()
vb2.camera = scene.PanZoomCamera()
vb3.camera = scene.TurntableCamera()
vb4.camera = scene.FlyCamera()

# If True, show a cuboid at each camera
if False:
    cube = scene.visuals.Cube((3, 3, 5))
    cube.transform = scene.STTransform(translate=(0, 0, 6))
    for vb in (vb1, vb2, vb3, vb4):
        vb.camera.parents = scenes
        cube.add_parent(vb.camera)

if __name__ == '__main__':
    if sys.flags.interactive != 1:
        app.run()
Example #18
0
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
im2 = im1[:, :, 1]
im2 = (im2[1:-1, 1:-1] + im2[0:-2, 1:-1] + im2[2:, 1:-1] + im2[1:-1, 0:-2] +
       im2[1:-1, 2:]) / 5
im2 = 0.5 + (np.abs(im2[0:-2, 1:-1] - im2[1:-1, 1:-1]) +
             np.abs(im2[1:-1, 0:-2] - im2[1:-1, 1:-1]))

image1 = scene.visuals.Image(im1, parent=vb1.scene)
image2 = scene.visuals.Image(im2, parent=vb2.scene)

# Set 2D camera (PanZoomCamera, TurnTableCamera)
vb1.camera, vb2.camera = scene.PanZoomCamera(), scene.PanZoomCamera()
vb1.camera.aspect = vb2.camera.aspect = 1  # no auto-scale
vb1.camera.link(vb2.camera)

# Set the view bounds to show the entire image with some padding
vb1.camera.set_range()

if __name__ == '__main__':
    app.run()
    def _ui(self):
        l1 = QVBoxLayout()
        self.setLayout(l1)
        l1.setContentsMargins(0, 0, 0, 0)

        self.canvas = scene.SceneCanvas(title="",
                                        show=False,
                                        create_native=False,
                                        px_scale=1,
                                        bgcolor=Color("#101010"),
                                        dpi=None)
        self.canvas.create_native()
        l1.addWidget(self.canvas.native, )  # not set alignment

        #
        grid = self.canvas.central_widget.add_grid()
        grid.spacing = 0

        yaxis = scene.AxisWidget(
            orientation='left',
            # axis_label='Y Axis',
            axis_font_size=12,
            axis_label_margin=50,
            tick_label_margin=5)
        yaxis.width_max = 50
        yaxis.stretch = (0.05, 1)
        grid.add_widget(yaxis, row=0, col=0)

        xaxis = scene.AxisWidget(
            orientation='bottom',
            axis_label='X Axis',
            axis_font_size=12,
            axis_label_margin=100,
            tick_label_margin=10,
        )

        xaxis.height_max = 100
        xaxis.stretch = (1, .1)
        grid.add_widget(xaxis, row=1, col=1)

        view: scene.ViewBox = grid.add_view(row=0, col=1, border_color='white')
        view.camera = scene.PanZoomCamera()
        view.border_color = "#ffffff"

        xaxis.link_view(view)
        yaxis.link_view(view)

        global df
        # Candlestick
        kline1 = Candlestick(borderwidth=.2, padding=.1)
        kline1.set_data(df.x.values, df.o.values, df.h.values, df.l.values,
                        df.c.values)
        view.add(kline1)

        # MA(CLOSE,22)
        try:
            import talib
            pos = np.empty((len(df), 2), dtype=np.float32)
            pos[:, 0] = np.arange(len(df))
            pos[:, 1] = talib.MA(df.c.values, timeperiod=22)
            ma_line = scene.visuals.Line(pos,
                                         color=(1, 1, 1, 1),
                                         method='gl',
                                         width=1)
            view.add(ma_line)
        except:
            pass

        # view.camera.rect = (0, 0, 800, 7000)
        view.camera.set_range()
Example #20
0
import numpy as np

from vispy import scene, app

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

# This is the top-level widget that will hold three ViewBoxes, which will
# be automatically resized whenever the grid is resized.
grid = canvas.central_widget.add_grid()

# Add 4 ViewBoxes to the grid
b1 = grid.add_view(row=0, col=0)
b1.border_color = (0.5, 0.5, 0.5, 1)
b1.camera = scene.PanZoomCamera(rect=(-0.5, -5, 11, 10))

b2 = grid.add_view(row=0, col=1)
b2.camera = 'turntable'
b2.border_color = (0.5, 0.5, 0.5, 1)

b3 = grid.add_view(row=1, col=0)
b3.border_color = (0.5, 0.5, 0.5, 1)
b3.camera = scene.PanZoomCamera(rect=(-10, -5, 15, 10))

b4 = grid.add_view(row=1, col=1)
b4.border_color = (0.5, 0.5, 0.5, 1)
b4.camera = scene.PanZoomCamera(rect=(-5, -5, 10, 10))

# Generate some random vertex data and a color gradient
N = 10000
Example #21
0
    def __init__(self,
                 pos,
                 mfc=[0.5, 0.5, 0.5, 0.8],
                 mec=None,
                 mfs=8,
                 mes=1,
                 bgc=[1, 1, 1],
                 scaling_symbol=False,
                 symbol='disc',
                 size=(800, 600)):
        scene.SceneCanvas.__init__(self,
                                   keys=None,
                                   show=True,
                                   bgcolor=bgc,
                                   size=size)
        self.unfreeze()  # allow the creation of new attribute to the class
        # Create the view and the scatter
        self.view = self.central_widget.add_view()
        self.scatter = visuals.Markers(parent=self.view.scene)
        self.scatter.set_data(pos,
                              face_color=mfc,
                              edge_color=mec,
                              scaling=scaling_symbol,
                              size=mfs,
                              edge_width=mes,
                              symbol=symbol)
        # Set the camera properties
        self.view.camera = scene.PanZoomCamera(aspect=1)
        self.view.camera.set_range()
        # Settings for the lines that indicate the position of the cursor
        self.param_tickprop = .01
        self.pressxy = (0, 0)
        self.movexy = (0, 0)
        tr = self.scene.node_transform(self.scatter)
        win_xmin, win_ymax = tr.map([0, 0])[:2]
        win_xmax, win_ymin = tr.map(self.size)[:2]
        win_xsize, win_ysize = win_xmax - win_xmin, win_ymax - win_ymin
        tick_size = self.param_tickprop * win_xsize
        # Create the lines on the border of the viewbox
        self.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=self.view.scene,
                                           method='gl')
        self.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=self.view.scene,
                                             method='gl')
        self.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=self.view.scene,
                                              method='gl')
        self.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=self.view.scene,
                                            method='gl')
        # Create the cross on the cursor coord
        self.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=self.view.scene,
                                              method='gl')
        self.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=self.view.scene,
                                              method='gl')
        self.freeze()

        @self.events.mouse_move.connect
        def on_mouse_move(event):
            # Find the cursor position in the windows coordinate
            tr = self.scene.node_transform(self.scatter)
            x, y = tr.map(event.pos)[:2]
            self.movexy = (x, y)
            # 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(self.size)[:2]
            win_xsize, win_ysize = win_xmax - win_xmin, win_ymax - win_ymin
            tick_size = self.param_tickprop * win_xsize
            #refresh lines
            self.top_line.set_data(
                pos=np.array([[x, win_ymax], [x, win_ymax - tick_size]]))
            self.right_line.set_data(
                pos=np.array([[win_xmax, y], [win_xmax - tick_size, y]]))
            self.bottom_line.set_data(
                pos=np.array([[x, win_ymin], [x, win_ymin + tick_size]]))
            self.left_line.set_data(
                pos=np.array([[win_xmin, y], [win_xmin + tick_size, y]]))

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

        @self.events.mouse_press.connect
        def on_mouse_press(event):
            # Find the cursor position in the windows coordinate
            tr = self.scene.node_transform(self.scatter)
            x, y = tr.map(event.pos)[:2]
            self.pressxy = (x, y)
Example #22
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()
Example #23
0
    def get_plot(self,
                 start_x=0,
                 start_y=0,
                 span=-1,
                 compression_factor=1,
                 type="3D",
                 elev_scale=0.1):

        start_time = time.time()

        int_data = []

        if start_y + span >= self.real_nrows:

            print "ERROR: Number of rows specified greater than total in data set."
            return

        if start_x + span >= self.real_ncols:

            print "ERROR: Number of columns specified greater than total in data set."
            return

        if span == -1:

            span_x = self.real_ncols - start_x
            span_y = self.real_nrows - start_y

        x_ctr = 0
        for i in xrange(start_y, start_y + span_y):
            x_ctr += 1

            if (x_ctr % compression_factor) == 0:
                cur_row = self.data[i]
                new_row = []

                y_ctr = 0
                for j in xrange(start_x, start_x + span_x):
                    y_ctr += 1

                    if (y_ctr % compression_factor) == 0:
                        new_row.append(int(self.data[i][j]))

                int_data.append(new_row)

        Z = np.array(int_data)

        canvas = scene.SceneCanvas(keys='interactive', title="Terrain Map")
        view = canvas.central_widget.add_view()

        if type == "3D":
            #view.camera = scene.PerspectiveCamera(mode='ortho',fov=60.0)
            view.camera = scene.TurntableCamera(
                up='z',
                center=(span_y * 0.5 / compression_factor,
                        span_x * 0.5 / compression_factor, 0))
        if type == "2D":
            view.camera = scene.PanZoomCamera(up='z')

        # Black background, no paning, blue graph
        p1 = scene.visuals.SurfacePlot(z=Z,
                                       color=(0.5, 0.5, 1, 1),
                                       shading='smooth')

        p1.transform = scene.transforms.AffineTransform()
        p1.transform.scale([1, 1, elev_scale])
        p1.transform.translate([0, 0, 0])

        view.add(p1)
        return canvas
Example #24
0
 def add_pan_zoom_camera(self):
     self.view.camera = scene.PanZoomCamera(aspect=1)
     self.view.camera.flip = (0, 1, 0)
Example #25
0
def main(image_fpath, input_points_fpath, output_points_fpath):
    global canvas

    logging.basicConfig(level=logging.INFO)

    im = imread(image_fpath)
    logging.info(f"Loaded image with shape {im.shape}")
    image = scene.visuals.Image(im, parent=view.scene)

    app.current_pos = None

    if output_points_fpath:
        df = pd.read_csv(input_points_fpath)
        points = [(p.X, p.Y) for p in df.itertuples()]
        output_fpath = output_points_fpath
    else:
        points = []
        output_fpath = input_points_fpath

    @canvas.events.mouse_press.connect
    def on_mouse_press(event):
        # print("Press pos:", event.pos)
        # get transform mapping from canvas to image
        tr = view.node_transform(image)
        # print("Image pos:", tr.map(event.pos)[:2])
        x, y = tr.map(event.pos)[:2]

        print("Click at ", x, y)

        # c, r = int(x), int(y)

        # points.append(np.array((r, c)))

        # rr, cc = circle(r, c, 5)
        # im[rr, cc] = 255, 0, 0
        # image.set_data(im)
        # canvas.update()

    @canvas.connect
    def on_mouse_move(event):
        app.current_pos = event.pos

    def update_drawing():
        draw_im = im.copy()
        for r, c in points:
            rr, cc = circle(r, c, 3)
            try:
                draw_im[rr, cc] = 255  #, 0, 0
            except IndexError:
                print(f"Point at {r}, {c} out of bounds")
                raise

        image.set_data(draw_im)
        canvas.update()

    @canvas.events.key_press.connect
    def key_event(event):

        if event.key.name == 'Escape':
            app.quit()

        if event.key.name == 'P':
            print("Added point")
            tr = view.node_transform(image)
            x, y = tr.map(app.current_pos)[:2]
            c, r = int(x), int(y)
            points.append(np.array((r, c)))
            update_drawing()

        if event.key.name == 'D':
            tr = view.node_transform(image)
            x, y = tr.map(app.current_pos)[:2]
            c, r = int(x), int(y)
            deltas = np.array(points) - np.array((r, c))
            sq_dists = np.sum(deltas * deltas, axis=1)
            del points[np.argmin(sq_dists)]
            update_drawing()

        if event.key.name == 'S':
            df = pd.DataFrame(points, columns=['X', 'Y'])
            df.to_csv(output_fpath, index=False)

    # t1 = scene.visuals.Text('Text in root scene (24 pt)', parent=image, color='red', pos=(100,100))
    # t1.font_size = 24
    # Set 2D camera (the camera will scale to the contents in the scene)
    view.camera = scene.PanZoomCamera(aspect=1)
    view.camera.set_range()
    view.camera.flip = (False, True, False)

    update_drawing()

    app.run()
Example #26
0
#########
# initialize 
# make sure to have the indexes right ...
xx = np.linspace(0,llen,llen)  # llen is max line length
yy = np.linspace(0,lcnt,lcnt) # lcnt is number of lines
x, y = np.meshgrid(yy, xx) # x is cols, y is rows
# fill z with increasing number of lines
zarray = np.full((lcnt, lcnt, llen),32)
for z in range(lcnt):
    for i in range(z):
        zarray[z][i] = lines[i] 

#########
canvas = scene.SceneCanvas(keys='interactive',bgcolor=(0,.3,.3,1))
view = canvas.central_widget.add_view()
cam1 = scene.PanZoomCamera(aspect=1) #SomeCamera()
view.camera = cam1
view.camera = 'turntable'

#### the time variable function: select the Z plane
Z = lambda t: zarray[int(t % lcnt)] # /127

surface = scene.visuals.SurfacePlot(x= np.linspace(0,lcnt-1,lcnt),
                        y=np.linspace(0,llen-1,llen), z= Z(0),
                        shading="smooth", color=(0.5, 0.5, 1, 1))

surface.transform = scene.transforms.MatrixTransform()
surface.transform.scale([1/20, 1/20, 1/200])
surface.transform.translate([-1.5, -2., 0.])
surface.transform.rotate(-45,(0,0,1))
surface.transform.rotate(-10,(1,0,0))