def run_movie_gui(filename):
    print('Starting up movie gui...')
    canvas = Canvas(filename)
    vispy.use('PyQt5')
    w = MainWindow(canvas)
    w.show()
    vispy.app.run()
Beispiel #2
0
    def __init__(self, im, conf, roi, logger):
        vispy.set_log_level('DEBUG')
        try:
            vispy.use(app='glfw', gl='gl+')
        except RuntimeError as e:
            pass

        app.Canvas.__init__(self,
                        keys = 'interactive',
                        size = (conf['ipmWidth'], conf['ipmHeight']),
                        position = (0,0),
                        title = 'IPM',
                        show = False,
                        resizable = False)


        self._rendertex = gloo.Texture2D(shape=(self.size[1], self.size[0], 4))
        self._fbo = gloo.FrameBuffer(self._rendertex,
                                    gloo.RenderBuffer((self.size[1], self.size[0])))

        try:
            fragmentShaderSourceString = open(FRAGMENT_SHADER_FILENAME).read()
        except:
            logger.fatal("%s does not exist !", FRAGMENT_SHADER_FILENAME)
            sys.exit()

        try:
            vertexShaderSourceString = open(VERTEX_SHADER_FILENAME).read()
        except:
            logger.fatal("%s does not exist !", VERTEX_SHADER_FILENAME)
            sys.exit()

        self.program = gloo.Program(vertexShaderSourceString, fragmentShaderSourceString)
        self.program["position"] = [(-1, -1), (-1, 1), (1, 1), (-1, -1), (1, 1), (1, -1)]

        gloo.set_viewport(0, 0, *self.size)

        tex = gloo.Texture2D(im)
        tex.interpolation = 'linear'
        tex.wrapping = 'repeat'
        self.program['iChannel'] = tex
        if len(im.shape) == 3:
            self.program['iChannelResolution'] = (im.shape[1], im.shape[0], im.shape[2])
        else:
            self.program['iChannelResolution'] = (im.shape[1], im.shape[0], 1)
        self.program['iResolution'] = (self.size[0], self.size[1], 0.)

        self.getUniforms(conf, roi)
        self.update()
        app.run()
        return self
Beispiel #3
0
    def __init__(self, config) -> None:
        self.config = yaml.load(open(config, 'r'))
        if os.name == 'nt':
            vispy.use(app='pyqt5')
        else:
            vispy.use(app='egl')

        if isinstance(self.config['gpu_ids'], int) and (self.config['gpu_ids'] >= 0):
            self.device = self.config['gpu_ids']
        else:
            self.device = "cpu"

        print(f"Loading edge model at {time.time()}")
        self.depth_edge_model = Inpaint_Edge_Net(init_weights=True)
        self.depth_edge_weight = torch.load(self.config['depth_edge_model_ckpt'],
                                       map_location=torch.device(self.device))
        self.depth_edge_model.load_state_dict(self.depth_edge_weight)
        self.depth_edge_model = self.depth_edge_model.to(self.device)
        self.depth_edge_model.eval()

        print(f"Loading depth model at {time.time()}")
        self.depth_feat_model = Inpaint_Depth_Net()
        self.depth_feat_weight = torch.load(self.config['depth_feat_model_ckpt'],
                                       map_location=torch.device(self.device))
        self.depth_feat_model.load_state_dict(self.depth_feat_weight, strict=True)
        self.depth_feat_model = self.depth_feat_model.to(self.device)
        self.depth_feat_model.eval()
        self.depth_feat_model = self.depth_feat_model.to(self.device)

        print(f"Loading rgb model at {time.time()}")
        self.rgb_model = Inpaint_Color_Net()
        self.rgb_feat_weight = torch.load(self.config['rgb_feat_model_ckpt'],
                                     map_location=torch.device(self.device))
        self.rgb_model.load_state_dict(self.rgb_feat_weight)
        self.rgb_model.eval()
        self.rgb_model = self.rgb_model.to(self.device)
        self.graph = None
Beispiel #4
0
def main():
    parser = argparse.ArgumentParser(
        description="Generate block images for Mapcrafter.")
    parser.add_argument("--osmesa", action="store_true")
    parser.add_argument("--no-render", action="store_true")
    parser.add_argument("--texture-size", "-t", type=int, action="append")
    parser.add_argument("--view", "-v", type=str, action="append")
    parser.add_argument("--rotation", "-r", type=int, action="append")
    parser.add_argument("--assets",
                        "-a",
                        type=str,
                        action="append",
                        required=True)
    parser.add_argument("--blocks", "-b", type=str, action="append")
    parser.add_argument("--output-dir", "-o", type=str, required=True)

    args = parser.parse_args()
    if args.osmesa:
        import vispy
        vispy.use("osmesa")
        assert vispy.app.use_app().backend_name == "osmesa"

    c = Canvas(args)
    app.run()
Beispiel #5
0
headless = int(os.environ.get('PYMAID_HEADLESS', '0'))
if utils._type_of_script() == 'ipython':
    if headless:
        logger.info('Pymaid is running in headless mode')
    elif utils.is_headless():
        logger.info('No display detected. Pymaid is running in headless mode')
    else:
        try:
            ipython = get_ipython()
            ipython.magic("%gui qt5")
        except BaseException:
            pass

try:
    # Try setting vispy backend to PyQt5
    vispy.use(app='PyQt5')
except BaseException:
    pass


def block_all(function):
    """Decorator to block all events on canvas and view."""
    @wraps(function)
    def wrapper(*args, **kwargs):
        viewer = args[0]
        viewer.canvas.events.block_all()
        viewer.view3d.events.block_all()
        try:
            # Execute function
            res = function(*args, **kwargs)
        except BaseException:
Beispiel #6
0
#
# Part of p5: A Python package based on Processing
# Copyright (C) 2017-2019 Abhik Pal
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from .userspace import *
import vispy
vispy.use('glfw')
Beispiel #7
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.
"""
This example shows how to retrieve event information from a callback.
You should see information displayed for any event you triggered.
"""

from vispy import gloo, app, use

use('pyqt4')  # can be another app backend name


class Canvas(app.Canvas):
    def __init__(self, *args, **kwargs):
        app.Canvas.__init__(self, *args, **kwargs)
        self.title = 'App demo'

    def on_close(self, event):
        print('closing!')

    def on_resize(self, event):
        print('Resize %r' % (event.size, ))

    def on_key_press(self, event):
        modifiers = [key.name for key in event.modifiers]
        print('Key pressed - text: %r, key: %s, modifiers: %r' %
              (event.text, event.key.name, modifiers))

    def on_key_release(self, event):
        modifiers = [key.name for key in event.modifiers]
Beispiel #8
0
# vispy: testskip
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
This is a simple osmesa example that produce an image of a cube

If you have both osmesa and normal (X) OpenGL installed, execute with
something like the following to pickup the OSMesa libraries::

    VISPY_GL_LIB=/opt/osmesa_llvmpipe/lib/libGLESv2.so \
    LD_LIBRARY_PATH=/opt/osmesa_llvmpipe/lib/ \
    OSMESA_LIBRARY=/opt/osmesa_llvmpipe/lib/libOSMesa.so \
    python examples/offscreen/simple_osmesa.py
"""
import vispy
vispy.use(app='osmesa')  # noqa

import numpy as np
import vispy.plot as vp
import vispy.io as io

# Check the application correctly picked up osmesa
assert vispy.app.use_app().backend_name == 'osmesa', 'Not using OSMesa'

data = np.load(io.load_data_file('electrophys/iv_curve.npz'))['arr_0']
time = np.arange(0, data.shape[1], 1e-4)

fig = vp.Fig(size=(800, 800), show=False)

x = np.linspace(0, 10, 20)
y = np.cos(x)
method. The instability of the Euler Method becomes apparent as the time step
is increased.
"""

from __future__ import division, print_function, absolute_import
from vispy import app, visuals
from vispy.visuals import transforms
from vispy.io import load_data_file
import sys
import numpy as np
import string
import logging
import traceback
from PyQt4 import QtGui, QtCore
import vispy
vispy.use('pyqt4')
logger = logging.getLogger(__name__)

VALID_METHODS = ['euler', 'runge-kutta']

PARAMETERS = [('d1', 0.0, 10.0, 'double', 0.97),
              ('d2', 0.0, 10.0, 'double', 0.55),
              ('m', 0.01, 100.0, 'double', 2.0),
              ('M', 0.01, 100.0, 'double', 12.5),
              ('k1', 0.01, 75.0, 'double', 1.35),
              ('k2', 0.01, 75.0, 'double', 0.50),
              ('b', 1.0, 1000.0, 'double', 25.75),
              ('time step', 0.001, 1.0, 'double', 1 / 60),
              ('x', -0.25, 0.25, 'double', -0.01),
              ('x dot', -10.0, 10.0, 'double', -0.12),
              ('theta', -np.pi / 5, np.pi / 5, 'double', 0.005),
Beispiel #10
0
Example demonstrating simulation of fireworks using point sprites.
(adapted from the "OpenGL ES 2.0 Programming Guide")

This example demonstrates a series of explosions that last one second. The
visualization during the explosion is highly optimized using a Vertex Buffer
Object (VBO). After each explosion, vertex data for the next explosion are
calculated, such that each explostion is unique.
"""

import time
import numpy as np
from vispy import gloo, app

import vispy
#vispy.use('pyside', 'es2')
vispy.use("pyqt5","gl+")

# Create a texture
radius = 32
im1 = np.random.normal(
    0.8, 0.3, (radius * 2 + 1, radius * 2 + 1)).astype(np.float32)

# Mask it with a disk
L = np.linspace(-radius, radius, 2 * radius + 1)
(X, Y) = np.meshgrid(L, L)
im1 *= np.array((X ** 2 + Y ** 2) <= radius * radius, dtype='float32')

# Set number of particles, you should be able to scale this to 100000
N = 10000

# Create vertex data container
Beispiel #11
0
def wrap_3d_photo_inpainting(config_path, *,
                             depth_handler: Optional[FileChoose] = None,
                             bar_total: Optional[ComplexProgressBar] = None,
                             bar_current: Optional[ComplexProgressBar] = None,
                             just_depth: bool = False
                             ):
    bar_current.reset()
    config = yaml.load(open(config_path, 'r'))
    if config['offscreen_rendering'] is True:
        vispy.use(app='egl')
    init_fs(config)
    sample_list = get_MiDaS_samples(config['src_folder'], config['depth_folder'], config, config['specific'])
    normal_canvas, all_canvas = None, None

    if isinstance(config["gpu_ids"], int) and (config["gpu_ids"] >= 0):
        device = config["gpu_ids"]
    else:
        device = "cpu"

    bar_current.add(bar_current.max)
    bar_total.add(bar_total.max * 2 / 100)

    print(f(_("running on device {device}")))

    for idx in tqdm(range(len(sample_list))):
        bar_current.reset()
        depth = None
        sample = sample_list[idx]
        print(f(_("Current Source ==> {sample['src_pair_name']}")))
        mesh_fi = os.path.join(config['mesh_folder'], sample['src_pair_name'] +'.ply')
        image = imageio.imread(sample['ref_img_fi'])

        print(f(_("Running depth extraction at {datetime.now():%Y-%m-%d %H:%M:%S.%f}")))
        if just_depth or config['require_midas'] is True:
            run_depth([sample['ref_img_fi']], config['src_folder'], config['depth_folder'],
                      config['MiDaS_model_ckpt'], MonoDepthNet, MiDaS_utils, target_w=640)

            update_image_handler(image_handler=depth_handler,
                                 path=Path(f"{config['depth_folder']}/{sample['src_pair_name']}.png"))

        if just_depth:
            bar_total.reset()
            bar_total.value = bar_total.max
            bar_current.reset()
            bar_current.value = bar_current.max
            return

        bar_current.add(bar_current.max)
        bar_total.add(bar_total.max * (2 / len(sample_list)) / 100)

        bar_current.reset()

        image = prepare_config_and_image(config=config, sample=sample, image=image)

        bar_current.add(bar_current.max)
        bar_total.add(bar_total.max * (2 / len(sample_list)) / 100)

        bar_current.reset()

        image = cv2.resize(image, (config['output_w'], config['output_h']), interpolation=cv2.INTER_AREA)
        depth = read_MiDaS_depth(sample['depth_fi'], 3.0, config['output_h'], config['output_w'])
        mean_loc_depth = depth[depth.shape[0]//2, depth.shape[1]//2]

        bar_current.add(bar_current.max)
        bar_total.add(bar_total.max * (2 / len(sample_list)) / 100)

        bar_current.reset()

        if not(config['load_ply'] is True and os.path.exists(mesh_fi)):
            vis_photos, vis_depths = sparse_bilateral_filtering(depth.copy(), image.copy(), config, num_iter=config['sparse_iter'], spdb=False)
            depth = vis_depths[-1]
            model = None
            torch.cuda.empty_cache()
            print(_("Start Running 3D_Photo ..."))

            depth_edge_model = load_edge_model(device=device, depth_edge_model_ckpt=config['depth_edge_model_ckpt'])
            depth_edge_model.eval()

            depth_feat_model = load_depth_model(device=device, depth_feat_model_ckpt=config['depth_feat_model_ckpt'])

            rgb_model = load_rgb_model(device=device, rgb_feat_model_ckpt=config['rgb_feat_model_ckpt'])
            graph = None

            def up_bars(dt=None):
                bar_current.add(bar_current.max * 1.5 / 100)
                bar_total.add(bar_total.max * (1 / len(sample_list)) / 100)

            # increase the bars every 5 sec, up to 5 min
            event = schedule_interval(up_bars, 5, 60 * 5)

            print(f(_("Writing depth ply (and basically doing everything) at {datetime.now():%Y-%m-%d %H:%M:%S.%f}")))
            rt_info = write_ply(image,
                                  depth,
                                  sample['int_mtx'],
                                  mesh_fi,
                                  config,
                                  rgb_model,
                                  depth_edge_model,
                                  depth_edge_model,
                                  depth_feat_model)

            if rt_info is False:
                continue
            rgb_model = None
            color_feat_model = None
            depth_edge_model = None
            depth_feat_model = None
            torch.cuda.empty_cache()

            event.cancel()

        bar_current.add(bar_current.max)
        bar_total.value_normalized = 75 / 100

        bar_current.reset()

        props = read_ply(mesh_fi) if config['save_ply'] is True or config['load_ply'] is True else rt_info
        make_video(
            sample=sample, config=config, props=props,
            depth=depth, normal_canvas=normal_canvas, all_canvas=all_canvas,
        )

        bar_current.value_normalized = 1
        bar_total.value_normalized = 1
Beispiel #12
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This example shows how to actively select and test the pyglet backend.

You should see a black window and any mouse or keyboard event should be
detected. A timer is also run every second and it should print "tick !"
every second.
"""

from vispy import app, use, gloo
use('pyglet')


class Canvas(app.Canvas):

    def __init__(self, *args, **kwargs):
        app.Canvas.__init__(self, *args, **kwargs)
        timer = app.Timer(1.0)
        timer.connect(self.on_timer)
        timer.start()

    def on_initialize(self, event):
        gloo.set_clear_color('black')
        print('on_initialize')

    def on_close(self, event):
        print('on_close')

    def on_resize(self, event):
        print('on_resize (%dx%d)' % event.size)
Beispiel #13
0
                timer.stop()
                self._ready = True

        timer.timeout.connect(_calc_vertices)
        timer.start()
        self.vertices = vertices


if __name__ == '__main__':
    # load config params
    try:
        with open(CONFIG_FILE) as f:
            config = json.load(f)
    except FileNotFoundError:
        print('config file not found.')
        config = {'pre_rendering': True}

    vispy.use('pyqt5')
    canvas = scene.SceneCanvas(keys="interactive",
                               size=(1200, 800),
                               show=False)
    camera = scene.TurntableCamera(up='+z')

    myui = MyUi()

    handler = UIHandler(myui,
                        canvas,
                        camera,
                        use_pre_rendering=config['pre_rendering'])

    canvas.app.run()
Beispiel #14
0
import logging
logging.basicConfig(level=logging.DEBUG)
import xml.etree.ElementTree as ET

import numpy as np

import sys
if True:
    from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QGridLayout
    from PyQt5.QtWidgets import QSpacerItem
    from PyQt5.QtCore import QTimer
else:
    pass

import vispy
vispy.use(app='PyQT5')
from vispy.plot import Fig


def typed(xml):
    """Convert XML value to Python types"""
    type_ = xml.attrib['type']
    # The type function may be within brackets
    type_func = getattr(__builtins__, type_.strip('[]'))
    if type_.startswith('['):
        return [type_func(value.strip()) for value in xml.text.split(',')]
    else:
        return type_func(xml.text.strip())


clog = logging.getLogger('CinfFigure')
Beispiel #15
0
from rendkit import shortcuts
from terial import config, models
from terial.config import SUBSTANCES
from terial.materials import loader
from terial.classifier.data import collector
from terial.models import Shape, ExemplarShapePair, Exemplar
from terial.database import session_scope
from toolbox import cameras
from terial.pairs import utils
from terial.web.utils import make_http_client
from toolbox.images import visualize_map
import toolbox.images
import vispy
from toolbox.logging import init_logger

vispy.use(app='glfw')  # noqa

logger = init_logger(__name__)

vis = visdom.Visdom(env='generate-data')

_TMP_MESH_PATH = '/tmp/_terial_generate_data_temp_mesh.obj'
_TMP_REND_PATH = '/tmp/_terial_generate_data_temp_rend.exr'
_REND_SHAPE = (500, 500)


@attr.s()
class _Envmap(object):
    path: str = attr.ib()
    rotation: Tuple[float, float, float] = attr.ib()
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, **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, use
    try:
        AffineTransform = scene.transforms.AffineTransform
    except:
        AffineTransform = scene.transforms.MatrixTransform

    use(app='pyglet', gl='pyopengl2')
    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
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, use
    try:
        AffineTransform = scene.transforms.AffineTransform
    except:
        AffineTransform = scene.transforms.MatrixTransform

    use(app='pyglet', gl='pyopengl2')
    #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(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

    render_im = canvas.render(size=figsize)
    app.quit()
    if not(name is None):
        import vispy.io as io
        io.write_png(name + ext, render_im)
    else:
        return render_im
Beispiel #18
0
import os
import numpy as np

import vispy
from vispy import plot as vp
from vispy.color import get_colormap
vispy.use("pyqt5", "gl2")

#create plot widget
fig = vp.Fig(size=(800, 800), show=False)

#generate colors
pairs = ["EUR_CHF", "EUR_USD"]
weeks = [1]
cmap = get_colormap('hsl', value=0.5)
colors = cmap.map(np.linspace(0.1, 0.9, len(pairs)*len(weeks)*2))

j = 0
for pair in pairs:
    for week in weeks:
        file = pair + "_Week" + str(week)
        path = os.path.sep.join(["C:", "fxdata", file + ".csv"])
        data = np.genfromtxt(path, skip_header=1, delimiter=",")
        for i in [4, 5]:
            y = data[:, i]
            x = np.arange(0, len(y), 1)
            #create line plot
            line = fig[0, 0].plot((x, y), width=3, title='~1.6 mill. points', xlabel='Time', ylabel='Price', color=colors[j])
            j += 1

# add grid to plot
Beispiel #19
0
:copyright: 2020 Precise Simulation Ltd.

"""

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk
import tkinter.ttk as ttk
import tkinter.font as tkfont
from tkinter.filedialog import askopenfilename

import vispy
import vispy.scene
# import vispy.visuals
vispy.use(app='tkinter')

import numpy as np

import sys
import os
if os.name == 'nt':
    from ctypes import windll, pointer, wintypes
    try:
        windll.shcore.SetProcessDpiAwareness(1)
    except Exception:
        pass  # this will fail on Windows Server and maybe early Windows


class Model():
    def __init__(self, file_name=None):
Beispiel #20
0
import os
import numpy as np

from collections import OrderedDict

from matplotlib import cm

from survos2.utils import find_library

if find_library('libOSMesa'):
    from vispy import use
    use(app='osmesa')

from vispy import app, gloo
from vispy.io import _make_png
from vispy.visuals import ImageVisual, transforms
from vispy.visuals.filters import Alpha
from vispy.color.colormap import Colormap, ColorArray, get_colormaps as get_vispy_cmaps

from survos2.utils import get_logger
from survos2.api.render.backend import Renderer, Layer

BACKEND_NAME = 'Vispy ({})'.format(app.use_app().backend_name)

logger = get_logger()

VispyCmaps = OrderedDict()
VispyCmaps['Primary'] = dict(grays='grays')
VispyCmaps['Others'] = {k: k for k in get_vispy_cmaps() if k != 'grays'}

for cmap_name in ['viridis', 'inferno', 'magma', 'plasma']:
Beispiel #21
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
import time
from vispy import app, use
from vispy.gloo import clear

use('pyqt4')
# use('glut')
# use('pyglet')

canvas = app.Canvas(size=(512, 512), title = "Do nothing benchmark (vispy)",
                    close_keys='escape')


@canvas.connect
def on_draw(event):
    global t, t0, frames
    clear(color=True, depth=True)

    t = time.time()
    frames = frames + 1
    elapsed = (t - t0)  # seconds
    if elapsed > 2.5:
        print("FPS : %.2f (%d frames in %.2f second)"
              % (frames / elapsed, frames, elapsed))
        t0, frames = t, 0
    canvas.update()
Beispiel #22
0
def run(sketch_setup=None,
        sketch_draw=None,
        frame_rate=60,
        mode="P2D",
        renderer="vispy"):
    """Run a sketch.

    if no `sketch_setup` and `sketch_draw` are specified, p5 automatically
    "finds" the user-defined setup and draw functions.

    :param sketch_setup: The setup function of the sketch (None by
         default.)
    :type sketch_setup: function

    :param sketch_draw: The draw function of the sketch (None by
        default.)
    :type sketch_draw: function

    :param frame_rate: The target frame rate for the sketch.
    :type frame_rate: int :math:`\geq 1`

    """

    # get the user-defined setup(), draw(), and handler functions.
    if sketch_setup is not None:
        setup_method = sketch_setup
    elif hasattr(__main__, 'setup'):
        setup_method = __main__.setup
    else:
        setup_method = setup

    if sketch_draw is not None:
        draw_method = sketch_draw
    elif hasattr(__main__, 'draw'):
        draw_method = __main__.draw
    else:
        draw_method = draw

    handlers = dict()
    for handler in handler_names:
        if hasattr(__main__, handler):
            hfunc = getattr(__main__, handler)
            handlers[handler] = _fix_interface(hfunc)

    if renderer == "vispy":
        import vispy
        vispy.use('glfw')
        from p5.sketch.Vispy2DRenderer.base import VispySketch
        from vispy import app
        builtins.current_renderer = "vispy"

        if mode == "P2D":
            p5.mode = 'P2D'
            from p5.sketch.Vispy2DRenderer.renderer2d import VispyRenderer2D
            p5.renderer = VispyRenderer2D()
        elif mode == "P3D":
            p5.mode = 'P3D'
            from p5.sketch.Vispy3DRenderer.renderer3d import Renderer3D
            p5.renderer = Renderer3D()
        else:
            ValueError("Invalid Mode %s" % mode)

        p5.sketch = VispySketch(setup_method, draw_method, handlers,
                                frame_rate)
        physical_width, physical_height = p5.sketch.physical_size
        width, height = p5.sketch.size

        builtins.pixel_x_density = physical_width // width
        builtins.pixel_y_density = physical_height // height
        builtins.start_time = time.perf_counter()

        p5.sketch.timer.start()

        app.run()
        exit()
    else:
        raise NotImplementedError("Invalid Renderer %s" % renderer)
Beispiel #23
0
        note whether the layer returned False and is requesting a re-render when the dust has settled => add to dirty layer list

Idle loop
    For each dirty layer
        Have layer render new draw list
        If layer has problems rendering, call a purge on all layers and then re-render


"""

import sys

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import vispy
vispy.use(app='PyQt4')  #, gl='gl+')

import vispy.scene as vps
from sift.view.MapWidget import SIFTMainMapWidget


class CoordSystem(object):
    """
    converts (y,x) pixel coordinates to geodetic coordinates in meters or degrees (lat/lon)
    """
    UNKNOWN = 0
    DATA_PIXELS = 1  # storage pixels for a given layer
    SCREEN_PIXELS = 2  # OpenGL pixels
    LATLON_DEGREES = 4  # lat/lon

Beispiel #24
0

def get_j_d(day, month, year):
    a = int((14 - month) / 12)
    b = year + 4800 - a
    c = month + 12 * a - 3
    return day + int((153 * c + 2) / 5) + 365 * b + int(b / 4) - int(
        b / 100) + int(b / 400) - 32045


G = 6.67408e-11  # граивтационная постоянная м3·с−2·кг−1 или Н·м2·кг−2
au = 149597870  # а.е. астрономическая единица
C = 299792458  # скорость света м/с

# настройки окна
vispy.use('PyQt5', 'gl+')
canvas = scene.SceneCanvas(keys='interactive',
                           title='Planet System',
                           show=True,
                           bgcolor='w')

view = canvas.central_widget.add_view()
view.camera = 'turntable'
view.camera.fov = 45
view.camera.distance = 5000000000

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

SUN = Star('Sun', m=1.98892e30)  # J2000.0 JD2451545.0
MERCURY = Object('Mercury',
                 color=(.5, .5, .5, 1),
Beispiel #25
0
def plot_sphere(filename,
                directions=None,
                data=None,
                interact=False,
                color_norm='linear',
                color_min=0,
                color_max=4 * np.pi,
                gamma=0.25,
                color_map='coolwarm',
                my_ax=None,
                my_cax=None,
                dpi=500,
                vis_px=1000,
                save_file=False):

    # Setup viewing window
    vispy.use('glfw')
    canvas = vispy.scene.SceneCanvas(keys='interactive',
                                     bgcolor='white',
                                     size=(vis_px, vis_px),
                                     show=interact)
    my_cam = vispy.scene.cameras.turntable.TurntableCamera(fov=0,
                                                           azimuth=135,
                                                           scale_factor=2.05)
    view = canvas.central_widget.add_view(camera=my_cam)

    # Plot dots
    dots = vispy.scene.visuals.Markers(parent=view.scene)
    dots.antialias = False
    dots.set_data(pos=np.array([[1.01, 0, 0], [0, 1.01, 0], [0, 0, 1.01]]),
                  edge_color='black',
                  face_color='black',
                  size=vis_px / 50)

    # Calculate colors
    if color_norm == 'linear':
        norm = matplotlib.colors.Normalize(vmin=color_min, vmax=color_max)
    elif color_norm == 'log':
        norm = matplotlib.colors.LogNorm(vmin=color_min, vmax=color_max)
    elif color_norm == 'linlog':
        norm = matplotlib.colors.SymLogNorm(linthresh=1e-3,
                                            vmin=data.min(),
                                            vmax=data.max())
    elif color_norm == 'power':
        norm = matplotlib.colors.PowerNorm(gamma=gamma,
                                           vmin=data.min(),
                                           vmax=data.max())

    norm_data = norm(data).data
    norm_data = np.expand_dims(norm_data, 1)
    cmap = matplotlib.cm.get_cmap(color_map)
    colors = np.apply_along_axis(cmap, 1, norm_data)

    # Plot sphere
    sphere = visuals.MySphere(parent=view.scene,
                              radius=1.0,
                              directions=directions,
                              colors=colors)

    # Display or save
    if interact:
        visuals.MyXYZAxis(parent=view.scene, origin=[0, 1.3, -0.3], length=0.2)
        canvas.app.run()
    else:
        im = canvas.render()
        f = plt.figure(figsize=(5, 5))
        local_ax = plt.axes([0.0, 0, 0.9, 0.9])  # x, y, width, height
        local_cax = plt.axes([0.95, 0.01, 0.025, 0.86])

        if my_ax == None:
            my_ax = local_ax
        if my_cax == None:
            my_cax = local_cax

        for (ax, cax) in [(local_ax, local_cax), (my_ax, my_cax)]:
            ax.axis('off')
            draw_axis(ax)
            cmap = ax.imshow(im,
                             interpolation='none',
                             cmap=color_map,
                             norm=norm)
            f.colorbar(cmap, cax=cax, orientation='vertical')

        # Save
        if save_file:
            f.savefig(filename, dpi=dpi)
Beispiel #26
0
import logging
logging.basicConfig(level=logging.DEBUG)
import xml.etree.ElementTree as ET

import numpy as np

import sys
if True:
    from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QGridLayout
    from PyQt5.QtWidgets import QSpacerItem
    from PyQt5.QtCore import QTimer
else:
    pass

import vispy
vispy.use(app='PyQT5')
from vispy.plot import Fig


def typed(xml):
    """Convert XML value to Python types"""
    type_ = xml.attrib['type']
    # The type function may be within brackets
    type_func = getattr(__builtins__, type_.strip('[]'))
    if type_.startswith('['):
        return [type_func(value.strip()) for value in xml.text.split(',')]
    else:
        return type_func(xml.text.strip())

clog = logging.getLogger('CinfFigure')
class CinfFigure(object):
def run_rm_viz(roi_path, rm_path):
    canvas = Canvas(roi_path, rm_path)
    vispy.use('PyQt5')
    w = MainWindow(canvas)
    w.show()
    vispy.app.run()
Beispiel #28
0
class Application(object):
    def __init__(self):
        # Create and open the window for user interaction.
        self.window = window.TerminalWindow()

        # Print some default lines in the terminal as hints.
        self.window.log("Operator started the chat.", align="left", color="#808080")
        self.window.log("HAL9000 joined.", align="right", color="#808080")

        # Construct and initialize the agent for this simulation.
        self.agent = HAL9000(self.window)

        # Connect the terminal's existing events.
        self.window.events.user_input.connect(self.agent.on_input)
        self.window.events.user_command.connect(self.agent.on_command)

    def run(self):
        timer = vispy.app.Timer(interval=1.0)
        timer.connect(self.agent.update)
        timer.start()

        vispy.app.run()


if __name__ == "__main__":
    vispy.set_log_level("WARNING")
    vispy.use(app="glfw")

    app = Application()
    app.run()
# -*- coding: utf-8 -*-
"""
"""

import sys

import vispy
vispy.use(app='pyglet', gl=None)

from vispy import app, gloo
from vispy.visuals import CubeVisual, transforms
from vispy.color import Color

from utils.orientation import Orientation
from utils.USB_data import USBData


class Canvas(app.Canvas):
    def __init__(self, connection, orientation):
        self.con = connection
        self.orientation = orientation
        app.Canvas.__init__(self, 'Cube', keys='interactive', size=(400, 400))
        self.cube = CubeVisual((7.0, 4.0, 0.3),
                               color=Color(color='grey', alpha=0.1,
                                           clip=False),
                               edge_color="black")

        # Create a TransformSystem that will tell the visual how to draw
        self.cube_transform = transforms.MatrixTransform()
        self.cube.transform = self.cube_transform
        self._timer = app.Timer('0.05', connect=self.on_timer, start=True)
Beispiel #30
0
import sys
print(sys.version)

import numpy as np
#import scipy as sci

#import matplotlib

#import lasio

import vispy
vispy.use("pyqt5")

import PyQt5

from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout
"""
Test the fps capability of Vispy with meshdata primitive
"""
try:
    from sip import setapi
    setapi("QVariant", 2)
    setapi("QString", 2)
except ImportError:
    pass

import numpy as np
from vispy import app, gloo
from vispy.util.transforms import perspective, translate, rotate
from vispy.geometry import meshdata as md
Beispiel #31
0
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from vispy import scene, app, use
from sklearn import ensemble
from sklearn import tree
use('PyQt5')


def findNextTick(df, type):
    df["nextClose"] = df["High"].shift(-1)
    #df["nextTime"] = df["time"].shift(-1)
    df["nextIndex"] = df.index
    df["nextIndex"] = df["nextIndex"].shift(-1)
    df.at[len(df) - 1, 'nextIndex'] = df.iloc[len(df) - 2]["nextIndex"] + 1
    df = df[0:len(df) - 2]
    #df.to_csv("test3.csv")
    X_pred = df[-1:].drop(["nextClose"], axis=1)
    print(X_pred)
    df = df[0:-1]
    X = df.drop(["nextClose"], axis=1)
    #X.to_csv("test4.csv")
    y = df["nextClose"]
    r1 = LinearRegression(n_jobs=-1)
    r2 = tree.DecisionTreeRegressor()
    r3 = ensemble.RandomForestRegressor(n_jobs=-1)
    r4 = ensemble.AdaBoostRegressor()
    r5 = ensemble.BaggingRegressor(n_jobs=-1)
Beispiel #32
0
        # Create and open the window for user interaction.
        self.window = window.TerminalWindow()

        # Print some default lines in the terminal as hints.
        self.window.log('Operator started the chat.', align='left', color='#808080')
        self.window.log('HAL9000 joined.', align='right', color='#808080')

        # Construct and initialize the agent for this simulation.
        self.agent = HAL9000(self.window)

        # Connect the terminal's existing events.
        self.window.events.user_input.connect(self.agent.on_input)
        self.window.events.user_command.connect(self.agent.on_command)

    def run(self):
        timer = vispy.app.Timer(interval=1.0)
        timer.connect(self.agent.update)
        timer.start()
        
        vispy.app.run()

        self.agent.shutdown()


if __name__ == "__main__":
    vispy.set_log_level('WARNING')
    vispy.use(app='default')
    
    app = Application()
    app.run()
Beispiel #33
0
# -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
This example shows how to retrieve event information from a callback.
You should see information displayed for any event you triggered.
"""

from vispy import gloo, app, use
use('pyqt4')  # can be another app backend name


class Canvas(app.Canvas):

    def __init__(self, *args, **kwargs):
        app.Canvas.__init__(self, *args, **kwargs)
        self.title = 'App demo'

    def on_close(self, event):
        print('closing!')

    def on_resize(self, event):
        print('Resize %r' % (event.size, ))

    def on_key_press(self, event):
        modifiers = [key.name for key in event.modifiers]
        print('Key pressed - text: %r, key: %s, modifiers: %r' % (
            event.text, event.key.name, modifiers))

    def on_key_release(self, event):
        modifiers = [key.name for key in event.modifiers]
def run_complete_viz(aligned_path, roi_path, dff_path):
    canvas = Canvas(aligned_path, roi_path, dff_path)
    vispy.use('PyQt5')
    w = MainWindow(canvas)
    w.show()
    vispy.app.run()
Beispiel #35
0
        if os.path.abspath(event.src_path) == self._filename:
            print("Updating shader...")

            glsl_shader = open(self._filename, 'r').read()

            self._canvas.set_shader(glsl_shader)
            self._canvas.update()


if __name__ == '__main__':
    vispy.set_log_level('WARNING')

    # GLFW not part of anaconda python distro; works fine with default (PyQt4)

    try:
        vispy.use(app='glfw')
    except RuntimeError as e:
        pass

    parser = argparse.ArgumentParser(
        description='Render a ShaderToy-style shader from the specified file.')
    parser.add_argument('input',
                        type=str,
                        help='Source shader file to load from disk.')
    parser.add_argument(
        '--size',
        type=str,
        default='1280x720',
        help='Width and height of the viewport/output, e.g. 1920x1080 (string).'
    )
    parser.add_argument(
def run_transparent_cells(aligned_path, roi_path, dff_path):
    canvas = Canvas(aligned_path, roi_path, dff_path)
    vispy.use('PyQt5')
    w = MainWindow(canvas)
    w.show()
    vispy.app.run()
Beispiel #37
0
import imageio
import copy
from networks import Inpaint_Color_Net, Inpaint_Depth_Net, Inpaint_Edge_Net
from MiDaS.run import run_depth
from MiDaS.monodepth_net import MonoDepthNet
from MiDaS import MiDaS_utils
from bilateral_filtering import sparse_bilateral_filtering

parser = argparse.ArgumentParser()
parser.add_argument(
    "--config", type=str, default="argument.yml", help="Configure of post processing"
)
args = parser.parse_args()
config = yaml.load(open(args.config, "r"))
if config["offscreen_rendering"] is True:
    vispy.use(app="egl")
os.makedirs(config["mesh_folder"], exist_ok=True)
os.makedirs(config["video_folder"], exist_ok=True)
os.makedirs(config["depth_folder"], exist_ok=True)
sample_list = get_MiDaS_samples(
    config["src_folder"], config["depth_folder"], config, config["specific"]
)
normal_canvas, all_canvas = None, None

if isinstance(config["gpu_ids"], int) and (config["gpu_ids"] >= 0):
    device = config["gpu_ids"]
else:
    device = "cpu"

print(f"running on device {device}")
Beispiel #38
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This example shows how to actively select and test the glfw backend.

You should see a black window and any mouse or keyboard event should be
detected. A timer is also run every second and it should print "tick !"
every second.
"""

from vispy import app, keys, use, gloo
use('glfw')


class Canvas(app.Canvas):

    def __init__(self, *args, **kwargs):
        app.Canvas.__init__(self, *args, **kwargs)
        timer = app.Timer(1.0)
        timer.connect(self.on_timer)
        timer.start()

    def on_initialize(self, event):
        gloo.set_clear_color('black')
        print('on_initialize')

    def on_close(self, event):
        print('on_close')

    def on_resize(self, event):
        print('on_resize (%dx%d)' % event.size)
Beispiel #39
0
    
    def __init__(self):
        # Create and open the window for user interaction.
        self.window = window.TerminalWindow()

        # Print some default lines in the terminal as hints.
        self.window.log('Operator started the chat.', align='left', color='#808080')
        self.window.log('HAL9000 joined.', align='right', color='#808080')

        # Construct and initialize the agent for this simulation.
        self.agent = HAL9000(self.window)
        self.speak = speaker()
        # Connect the terminal's existing events.
        self.window.events.user_input.connect(self.agent.on_input)
        self.window.events.user_command.connect(self.agent.on_command)

    def run(self):
        timer = vispy.app.Timer(interval=1.0)
        timer.start()
        self.speak.setDaemon(True)
        self.speak.start()
        vispy.app.run()


if __name__ == "__main__":
    vispy.set_log_level('WARNING')
    vispy.use(app='glfw')
    
    app = Application()
    app.run()
Beispiel #40
0
import imageio
import copy
from networks import Inpaint_Color_Net, Inpaint_Depth_Net, Inpaint_Edge_Net
from MiDaS.run import run_depth
from MiDaS.monodepth_net import MonoDepthNet
import MiDaS.MiDaS_utils as MiDaS_utils

parser = argparse.ArgumentParser()
parser.add_argument('--config',
                    type=str,
                    default='argument.yml',
                    help='Configure of post processing')
args = parser.parse_args()
config = yaml.load(open(args.config, 'r'))
if config['offscreen_rendering'] is True:
    vispy.use(app='egl')
os.makedirs(config['mesh_folder'], exist_ok=True)
os.makedirs(config['video_folder'], exist_ok=True)
os.makedirs(config['depth_folder'], exist_ok=True)
sample_list = get_MiDaS_samples(config['src_folder'], config['depth_folder'],
                                config, config['specific'])
normal_canvas, all_canvas = None, None

if isinstance(config["gpu_ids"], int) and (config["gpu_ids"] >= 0):
    device = config["gpu_ids"]
else:
    device = "cpu"

for idx in tqdm(range(len(sample_list))):
    depth = None
    sample = sample_list[idx]
Beispiel #41
0
import numpy as np
import sys

from PyQt4.QtGui import (QWidget, QGroupBox, QGridLayout, QLabel,
                         QSpinBox, QSplitter, QMainWindow, QAction,
                         QApplication, QVBoxLayout, QHBoxLayout,
                         qApp, QComboBox)

from PyQt4.QtCore import (pyqtSignal, Qt)

from vispy.color.colormap import get_colormaps
from vispy import scene
from vispy.geometry import create_sphere
from vispy import use

use("PyQt4")


def xyz_to_gp(xyz):
    """
    Input X, Y, Z, the Cartesian coordinates of a point
    on the unit sphere.
    Output, float gamma and phi coordinates of the point.

    phi is a longitudinal angle and gamma is a latitudinal

    x = np.sin(gamma)*np.cos(phi)
    y = np.sin(gamma)*np.sin(phi)
    z = np.cos(gamma)

    """
Beispiel #42
0

def use_app(backend_name):
    """Use a specific backend."""
    CONFIG['VISPY_APP'] = visapp.application.Application(backend_name)


# MPL render :
CONFIG['MPL_RENDER'] = False

# Jupyter / iPython :
try:
    ip = get_ipython()
    CONFIG['MPL_RENDER'] = True
    import vispy
    vispy.use('PyQt5')
except NameError:
    pass

# Input command line arguments
VISBRAIN_HELP = """
Visbrain command line arguments:

  --visbrain-log=(profiler|debug|info|warning|error|critical)
    Sets the verbosity of logging output. The default is 'info'.

  --visbrain-search=[search string]
    Search string in logs.

  --visbrain-show=(True|False)
    Control if GUI have to be displayed.
Beispiel #43
0
    def update(self, ev):
        canvas.image.set_data(canvas.tensor_data[canvas.i, :, :])
        #print(canvas.raw_data[canvas.i,:,:])
        print(canvas.i)
        canvas.time_text.text = str(canvas.i)
        canvas.i += 1

        #im=canvas.render()
        #self.writer.append_data(im)
        if canvas.i >= canvas.raw_data.shape[0]:
            #self.writer.close()
            #import sys
            #sys.exit()
            canvas.i = 0

        canvas.update()

    def change_t_c(self):
        canvas.temporal_component = int(self.t_c.text())
        canvas.factors_to_tensors()
        self.timer_init()


canvas = Canvas()
vispy.use('PyQt5')
w = MainWindow(canvas)
w.show()
vispy.app.run()
#vispy.app.processEvents(
Beispiel #44
0
# vispy: testskip
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
This is a simple osmesa example that produce an image of a cube

If you have both osmesa and normal (X) OpenGL installed, execute with
something like the following to pickup the OSMesa libraries::

    VISPY_GL_LIB=/opt/osmesa_llvmpipe/lib/libGLESv2.so \
    LD_LIBRARY_PATH=/opt/osmesa_llvmpipe/lib/ \
    OSMESA_LIBRARY=/opt/osmesa_llvmpipe/lib/libOSMesa.so \
    python examples/offscreen/simple_osmesa.py
"""
import vispy
vispy.use(app='osmesa')  # noqa

import numpy as np
import vispy.plot as vp
import vispy.io as io

# Check the application correctly picked up osmesa
assert vispy.app.use_app().backend_name == 'osmesa', 'Not using OSMesa'

data = np.load(io.load_data_file('electrophys/iv_curve.npz'))['arr_0']
time = np.arange(0, data.shape[1], 1e-4)

fig = vp.Fig(size=(800, 800), show=False)

x = np.linspace(0, 10, 20)
y = np.cos(x)