コード例 #1
0
ファイル: test_perspective.py プロジェクト: djhoese/vispy
def test_panzoom_center():
    with TestingCanvas(size=(120, 200)) as canvas:
        grid = canvas.central_widget.add_grid()
        imdata = io.load_crate().astype('float32') / 255

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

        image = scene.visuals.Image(imdata)
        image.transform = scene.STTransform(translate=(-12.8, -12.8),
                                            scale=(0.1, 0.1))
        v.add(image)

        result1 = canvas.render()[..., :3]
        assert v.camera.center == (0.5, 0.5, 0)

        v.camera.center = (-12.8, -12.8, 0)
        result2 = canvas.render()[..., :3]

        assert not np.allclose(result1, result2)
        # we moved to the lower-left corner of the image that means only the
        # upper-right quadrant should have data, the rest is black background
        np.testing.assert_allclose(result2[100:, :], 0)
        np.testing.assert_allclose(result2[:, :60], 0)
        assert not np.allclose(result2[:100, 60:], 0)
        assert v.camera.center == (-12.8, -12.8, 0)
コード例 #2
0
ファイル: test_perspective.py プロジェクト: djhoese/vispy
def test_perspective_render():
    with TestingCanvas(size=(120, 200)) as canvas:

        grid = canvas.central_widget.add_grid()
        imdata = io.load_crate().astype('float32') / 255

        views = []
        images = []
        for i, imethod in enumerate(['impostor', 'subdivide']):
            v = grid.add_view(row=i, col=0, border_color='white')
            v.camera = 'turntable'
            v.camera.fov = 50
            v.camera.distance = 30

            views.append(v)
            image = scene.visuals.Image(imdata, method=imethod, grid=(4, 4))
            image.transform = scene.STTransform(translate=(-12.8, -12.8),
                                                scale=(0.1, 0.1))
            v.add(image)
            images.append(image)

        image = canvas.render()
        canvas.close()

        # Allow many pixels to differ by a small amount--texture sampling and
        # exact triangle position will differ across platforms. However a
        # change in perspective or in the widget borders should trigger a
        # failure.
        assert_image_approved(image,
                              'scene/cameras/perspective_test.png',
                              'perspective test 1: 2 identical views with '
                              'correct perspective',
                              px_threshold=20,
                              px_count=60,
                              max_px_diff=200)
コード例 #3
0
def test_read_write_image():
    """Test reading and writing of images"""
    fname = op.join(temp_dir, 'out.png')
    im1 = load_crate()
    imsave(fname, im1, format='png')
    with warnings.catch_warnings(record=True):  # PIL unclosed file
        im2 = imread(fname)
    assert_allclose(im1, im2)
コード例 #4
0
    def __init__(self, **kwargs):
        app.Canvas.__init__(self, **kwargs)
        self.geometry = 0, 0, 400, 400

        self.program = gloo.Program(VERT_CODE, FRAG_CODE)

        # Set attributes
        self.program['a_position'] = gloo.VertexBuffer(positions)
        self.program['a_texcoord'] = gloo.VertexBuffer(texcoords)

        self.program['u_texture'] = gloo.Texture2D(load_crate())

        # Handle transformations
        self.init_transforms()

        self._timer = app.Timer('auto', connect=self.update_transforms)
        self._timer.start()
コード例 #5
0
ファイル: glsl_sandbox_cube.py プロジェクト: rreilink/vispy
    def __init__(self, **kwargs):
        app.Canvas.__init__(self, **kwargs)
        self.geometry = 0, 0, 400, 400

        self.program = gloo.Program(VERT_CODE, FRAG_CODE)

        # Set attributes
        self.program['a_position'] = gloo.VertexBuffer(positions)
        self.program['a_texcoord'] = gloo.VertexBuffer(texcoords)

        self.program['u_texture'] = gloo.Texture2D(load_crate())

        # Handle transformations
        self.init_transforms()
        
        self._timer = app.Timer('auto', connect=self.update_transforms)
        self._timer.start()
コード例 #6
0
ファイル: test_perspective.py プロジェクト: astrofrog/vispy
def test_perspective_render():
    with TestingCanvas(size=(300, 200)) as canvas:

        grid = canvas.central_widget.add_grid()
        grid.padding = 20

        imdata = io.load_crate().astype('float32') / 255

        views = []
        images = []
        for i, imethod in enumerate(['impostor', 'subdivide']):
            for j, vmethod in enumerate(['fragment', 'viewport', 'fbo']):
                v = grid.add_view(row=i, col=j, border_color='white')
                v.camera = 'turntable'
                v.camera.fov = 50
                v.camera.distance = 30
                v.clip_method = vmethod
                
                views.append(v)
                image = scene.visuals.Image(imdata, method=imethod, 
                                            grid=(4, 4))
                image.transform = scene.STTransform(translate=(-12.8, -12.8),
                                                    scale=(0.1, 0.1))
                v.add(image)
                images.append(image)
        
        image = canvas.render()
        print("ViewBox shapes")
        for v in views:
            print(v.node_transform(canvas.canvas_cs).map(v.rect))
        canvas.close()
        
        # Allow many pixels to differ by a small amount--texture sampling and
        # exact triangle position will differ across platforms. However a 
        # change in perspective or in the widget borders should trigger a 
        # failure.
        assert_image_approved(image, 'scene/cameras/perspective_test.png',
                              'perspective test 1: 6 identical views with '
                              'correct perspective',
                              px_threshold=20,
                              px_count=60,
                              max_px_diff=200)
コード例 #7
0
ファイル: objloader.py プロジェクト: jay3sh/vispy
  def __init__(self):
    app.Canvas.__init__(self, keys='interactive', size=(800, 600))

    dirname = path.join(path.abspath(path.curdir),'data')
    positions, faces, normals, texcoords = \
      read_mesh(load_data_file('cube.obj', directory=dirname))

    self.filled_buf = gloo.IndexBuffer(faces)

    if False:
      self.program = gloo.Program(VERT_TEX_CODE, FRAG_TEX_CODE)
      self.program['a_position'] = gloo.VertexBuffer(positions)
      self.program['a_texcoord'] = gloo.VertexBuffer(texcoords)
      self.program['u_texture'] = gloo.Texture2D(load_crate())
    else:
      self.program = gloo.Program(VERT_COLOR_CODE, FRAG_COLOR_CODE)
      self.program['a_position'] = gloo.VertexBuffer(positions)
      self.program['u_color'] = 1, 0, 0, 1

    self.view = translate((0, 0, -5))
    self.model = np.eye(4, dtype=np.float32)

    gloo.set_viewport(0, 0, self.physical_size[0], self.physical_size[1])
    self.projection = perspective(45.0, self.size[0] /
                                  float(self.size[1]), 2.0, 10.0)

    self.program['u_projection'] = self.projection

    self.program['u_model'] = self.model
    self.program['u_view'] = self.view

    self.theta = 0
    self.phi = 0

    gloo.set_clear_color('gray')
    gloo.set_state('opaque')
    gloo.set_polygon_offset(1, 1)

    self._timer = app.Timer('auto', connect=self.on_timer, start=True)

    self.show()
コード例 #8
0
ファイル: glsl_sandbox_cube.py プロジェクト: bdvd/vispy
    def __init__(self, **kwargs):
        app.Canvas.__init__(self, size=(400, 400), **kwargs)

        self.program = gloo.Program(VERT_CODE, FRAG_CODE)

        # Set attributes
        self.program["a_position"] = gloo.VertexBuffer(positions)
        self.program["a_texcoord"] = gloo.VertexBuffer(texcoords)

        self.program["u_texture"] = gloo.Texture2D(load_crate())

        # Handle transformations
        self.init_transforms()

        self.apply_zoom()

        gloo.set_clear_color((1, 1, 1, 1))
        gloo.set_state(depth_test=True)

        self._timer = app.Timer("auto", connect=self.update_transforms)
        self._timer.start()

        self.show()
コード例 #9
0
    def __init__(self, **kwargs):
        app.Canvas.__init__(self, size=(400, 400), **kwargs)

        self.program = gloo.Program(VERT_CODE, FRAG_CODE)

        # Set attributes
        self.program['a_position'] = gloo.VertexBuffer(positions)
        self.program['a_texcoord'] = gloo.VertexBuffer(texcoords)

        self.program['u_texture'] = gloo.Texture2D(load_crate())

        # Handle transformations
        self.init_transforms()

        self.apply_zoom()

        gloo.set_clear_color((1, 1, 1, 1))
        gloo.set_state(depth_test=True)

        self._timer = app.Timer('auto', connect=self.update_transforms)
        self._timer.start()

        self.show()
コード例 #10
0
vb4 = scene.widgets.ViewBox(border_color='white', parent=canvas.scene)
scenes = vb1.scene, vb2.scene, vb3.scene, vb4.scene

# Put viewboxes in a grid
grid = canvas.central_widget.add_grid()
grid.padding = 6
grid.add_widget(vb1, 0, 0)
grid.add_widget(vb2, 0, 1)
grid.add_widget(vb3, 1, 0)
grid.add_widget(vb4, 1, 1)

# 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
コード例 #11
0
vb4 = scene.widgets.ViewBox(border_color='white', parent=canvas.scene)
scenes = vb1.scene, vb2.scene, vb3.scene, vb4.scene

# Put viewboxes in a grid
grid = canvas.central_widget.add_grid()
grid.padding = 6
grid.add_widget(vb1, 0, 0)
grid.add_widget(vb2, 0, 1)
grid.add_widget(vb3, 1, 0)
grid.add_widget(vb4, 1, 1)

# 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()

コード例 #12
0
    }
   
    //Gamma correction
     fragColor.xyz=pow(fragColor.xyz, vec3(1.4));
     gl_FragColor = fragColor;
    
}

//void main(){} 
""");


import numpy as np

# Texture 1
im1 = io.load_crate()

# Texture with bumbs (to muliply with im1)
im2 = np.ones((20,20), 'float32')
im2[::3,::3] = 0.25 #0.5

# Texture with a plus sign (to subtract from im1)
im3 = np.zeros((30,30), 'float32')
im3[10,:] = 1.0
im3[:,10] = 1.0

# Create vetices and texture coords in two separate arrays.
# Note that combining both in one array (as in hello_quad2)
# results in better performance.
#positions = np.array([  [-0.8, -0.8, 0.0], [+0.7, -0.7, 0.0],                        [-0.7, +0.7, 0.0], [+0.8, +0.8, 0.0,] ], np.float32)
                        
コード例 #13
0
ファイル: perspective.py プロジェクト: gabyx/vispy
# -----------------------------------------------------------------------------
# Copyright (c) 2014, Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
import sys

from vispy import app, scene, io

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

grid = canvas.central_widget.add_grid()
grid.padding = 20

imdata = io.load_crate().astype('float32') / 255

views = []
images = []
for i in range(2):
    for j in range(2):
        v = grid.add_view(row=i, col=j, border_color='white')
        v.camera = 'turntable'
        v.camera.fov = 50
        v.camera.distance = 30
        #v.camera = 'panzoom'
        #v.camera.aspect = 1
        
        views.append(v)
        image = scene.visuals.Image(imdata, method='impostor', grid=(4, 4))
        image.transform = scene.STTransform(translate=(-12.8, -12.8),
コード例 #14
0
def main(quantity, radius, speed, max_x, max_y, min_x=0, min_y=0, loops = None):

    def collision(f_i, s_i):

        f_atom = atom_list[f_i]; s_atom = atom_list[s_i]
        dist = hypot((f_atom.x - s_atom.x), (f_atom.y - s_atom.y))

        if dist < radius * 2 and f_i != s_i:

            co = abs((s_atom.x - f_atom.x) / dist)
            si = abs((s_atom.y - f_atom.y) / dist)
            sphere_dist = radius - dist / 2

            f_atom.s = (f_atom.xs**2 + f_atom.ys**2)**0.5
            s_atom.s = (s_atom.xs**2 + s_atom.ys**2)**0.5

            if f_atom.x > s_atom.x:
                f_atom.xb += sphere_dist * si
                s_atom.xb -= sphere_dist * si
                f_atom.xs = si * s_atom.s
                s_atom.xs = -si * f_atom.s
            else:
                f_atom.xb -= sphere_dist * si
                s_atom.xb += sphere_dist * si
                f_atom.xs = -si * s_atom.s
                s_atom.xs = si * f_atom.s

            if f_atom.y > s_atom.y:
                f_atom.yb += sphere_dist * co
                s_atom.yb -= sphere_dist * co
                f_atom.ys = co * s_atom.s
                s_atom.ys = -co * f_atom.s
            else:
                f_atom.yb -= sphere_dist * co
                s_atom.yb += sphere_dist * co
                f_atom.ys = -co * s_atom.s
                s_atom.ys = co * f_atom.s

    def update_atoms():

        # Find collisions
        fcol_t = time.perf_counter()
        for (x, y) in non_empty_cells:

            other_atoms_i = grid[x][y] + grid[x][y-1] + grid[x+1][y-1] + grid[x+1][y] + grid[x+1][y+1]
            #~ other_atoms_i = (x for cell in (grid[x][y], grid[x][y-1], grid[x+1][y-1], grid[x+1][y], grid[x+1][y+1]) for x in cell)

            for atom_i in grid[x][y]:
                for other_atom_i in other_atoms_i:
                    collision(atom_i, other_atom_i)
        fcol_t = time.perf_counter() - fcol_t

        # Apply speed
        aplspd_t = time.perf_counter()
        for atom in atom_list:
            if atom.x - radius < min_x:
                atom.x = min_x + radius
                atom.xs *= -1
            elif atom.x + radius > max_x:
                atom.x = max_x - radius
                atom.xs *= -1

            if atom.y - radius < min_y:
                atom.y = min_y + radius
                atom.ys *= -1
            elif atom.y + radius > max_y:
                atom.y = max_y - radius
                atom.ys *= -1

            atom.x += atom.xs + atom.xb
            atom.y += atom.ys + atom.yb

            atom.xb = 0; atom.yb = 0
        aplspd_t = time.perf_counter() - aplspd_t

        # Update grid
        updgrd_t = time.perf_counter()
        for (x, y) in non_empty_cells.copy():

            for atom_i in grid[x][y].copy():

                nx, ny = int(atom_list[atom_i].x / diam), int(atom_list[atom_i].y / diam)

                if (nx, ny) != (x, y):
                    grid[x][y].remove(atom_i)
                    grid[nx][ny].append(atom_i)
                    if (nx, ny) not in non_empty_cells:
                        non_empty_cells.append((nx, ny))

            if len(grid[x][y]) == 0:
                non_empty_cells.remove((x, y))
        updgrd_t = time.perf_counter() - updgrd_t

        # Return time spent
        return fcol_t, aplspd_t, updgrd_t

    diam = radius * 2
    width = max_x - min_x
    height = max_y - min_y

    atom_list = []
    for i in range(quantity):
        angle = uniform(0, 2*pi)
        coeff = 1 #uniform(0.5,2)
        atom_list.append(atom(
            uniform(min_x + radius, max_x - radius),
            uniform(min_y + radius, max_y - radius),
            sin(angle) * speed * coeff,
            cos(angle) * speed * coeff))

    grid = []
    for x in range(int(width / diam) + 2):
        grid.append([])
        for y in range(int(height / diam) + 2):
            grid[-1].append([])

    non_empty_cells = []
    for i in range(len(atom_list)):
        x, y = int(atom_list[i].x / diam), int(atom_list[i].y / diam)
        grid[x][y].append(i)
        if (x, y) not in non_empty_cells:
            non_empty_cells.append((x, y))


    vertex = """
        attribute vec3 positions;
        attribute vec2 a_texcoord;
        uniform float radius;

        varying vec2 v_texcoord;

        void main(void)
        {
            gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
            gl_PointSize = 2.0*(radius);
            v_texcoord = a_texcoord;
        }
    """

    fragment = """
        uniform sampler2D texture;

        varying vec2 v_texcoord;

        void main(void)
        {
            float distance = length(vec2(0.5, 0.5) - gl_PointCoord);

            if (distance <= 0.5)
                //gl_FragColor = vec4(1, 1, 1, 1);
                gl_FragColor = texture2D(texture, v_texcoord);
            else
                discard;
        }
    """

    #~ im = np.full((1,1), 0.5, 'float32')
    im = io.load_crate()

    positions_1 = np.array([  [-1, -1, 0.0], [+1, -1, 0.0],
                        [-1, +1, 0.0], [+1, +1, 0.0,] ], np.float32)
    texcoords_1 = np.array([  [1.0, 1.0], [0.0, 1.0],
                        [1.0, 0.0], [0.0, 0.0]], np.float32)

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


    program = Program(vertex, fragment)

    program['texture'] = Texture2D(im)
    program['radius'] = radius
    program['a_texcoord'] = texcoords
    program['positions_1'] = positions_1
    program['texcoords_1']= texcoords_1


    c = app.Canvas(keys='interactive', size=(width, height))



    @c.connect
    def on_draw(event):

        #~ nonlocal loops
        runtime = update_atoms()
        #~ if loops != None:
            #~ update_times.append(runtime)
            #~ loops -= 1
            #~ if loops == 0:
                #~ fcol_t, aplspd_t, updgrd_t = [sum(times) / len(times) for times in zip(*update_times)]
                #~ print(fcol_t, aplspd_t, updgrd_t)
        positions = [[(atom.x - width / 2) / width * 2, (atom.y - height / 2) / height * 2, 0] for atom in atom_list]

        program['positions'] = positions
        gloo.clear()
        program.draw('points')
        c.update()

    @c.connect
    def on_resize(event):
        gloo.set_viewport(0, 0, *event.size)

    c.show()
    app.run()
コード例 #15
0
ファイル: one_cam_two_scenes.py プロジェクト: ringw/vispy
canvas = scene.SceneCanvas(keys="interactive")
canvas.size = 800, 600
canvas.show()

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

# Create the image
im1 = io.load_crate().astype("float32") / 255
# Make gray, smooth, and take derivatives: edge enhancement
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
# view.camera.rect = (-10, -10, image.size[0]+20, image.size[1]+20)