def __init__(self, param=None): """Main Window for holding the Vispy Canvas and the parameter control menu. """ QtWidgets.QMainWindow.__init__(self) self.resize(1067, 800) icon = load_data_file('wiggly_bar/spring.ico') self.setWindowIcon(QtGui.QIcon(icon)) self.setWindowTitle('Nonlinear Physical Model Simulation') self.parameter_object = SetupWidget(self) self.parameter_object.param = (param if param is not None else self.parameter_object.param) self.parameter_object.changed_parameter_sig.connect(self.update_view) self.view_box = WigglyBar(**self.parameter_object.param.props) self.view_box.create_native() self.view_box.native.setParent(self) splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal) splitter.addWidget(self.parameter_object) splitter.addWidget(self.view_box.native) self.setCentralWidget(splitter)
def load_galaxy_star_image(): fname = io.load_data_file('galaxy/star-particle.png') raw_image = io.read_png(fname) return raw_image
def __init__(self): app.Canvas.__init__(self, title='Molecular viewer', keys='interactive', size=(1200, 800)) self.ps = self.pixel_scale self.translate = 40 self.program = gloo.Program(vertex, fragment) self.view = translate((0, 0, -self.translate)) self.model = np.eye(4, dtype=np.float32) self.projection = np.eye(4, dtype=np.float32) self.apply_zoom() fname = load_data_file('molecular_viewer/micelle.npz') self.load_molecule(fname) self.load_data() self.theta = 0 self.phi = 0 gloo.set_state(depth_test=True, clear_color='black') self._timer = app.Timer('auto', connect=self.on_timer, start=True) self.show()
def __init__(self): self.program = gloo.Program(self.VERT_SHADER, self.FRAG_SHADER) brain = np.load( load_data_file('brain/brain.npz', force_download='2014-09-04')) data = brain['vertex_buffer'] faces = brain['index_buffer'] self.theta, self.phi = -80, 180 self.translate = 3 self.faces = gloo.IndexBuffer(faces) self.program.bind(gloo.VertexBuffer(data)) self.model = translate(np.eye(4), 0, 0, -5) self.program['model'] = self.model self.view = np.eye(4) self.program['view'] = self.view self.program['u_color'] = 1, 1, 1, 1 self.program['u_light_position'] = (1., 1., 1.) self.program['u_light_intensity'] = (1., 1., 1.) self.projection = np.eye(4) self.program['projection'] = self.projection
def __init__(self): self.program = gloo.Program(self.VERT_SHADER, self.FRAG_SHADER) brain = np.load(load_data_file('brain/brain.npz', force_download='2014-09-04')) data = brain['vertex_buffer'] faces = brain['index_buffer'] self.theta, self.phi = -80, 180 self.translate = 3 self.faces = gloo.IndexBuffer(faces) self.program.bind(gloo.VertexBuffer(data)) self.model = translate(np.eye(4), 0, 0, -5) self.program['model'] = self.model self.view = np.eye(4) self.program['view'] = self.view self.program['u_color'] = 1, 1, 1, 1 self.program['u_light_position'] = (1., 1., 1.) self.program['u_light_intensity'] = (1., 1., 1.) self.projection = np.eye(4) self.program['projection'] = self.projection
def __init__(self): visuals.Visual.__init__(self) # Create an interesting mesh shape for demonstration. fname = io.load_data_file('orig/triceratops.obj.gz') vertices, faces, normals, tex = io.read_mesh(fname) self._ibo = gloo.IndexBuffer(faces) self.program = visuals.shaders.ModularProgram(vertex_shader, fragment_shader) self.program.vert['position'] = gloo.VertexBuffer(vertices)
def __init__(self): visuals.Visual.__init__(self, vertex_shader, fragment_shader) # Create an interesting mesh shape for demonstration. fname = io.load_data_file('orig/triceratops.obj.gz') vertices, faces, normals, tex = io.read_mesh(fname) self._ibo = gloo.IndexBuffer(faces) self.shared_program.vert['position'] = gloo.VertexBuffer(vertices) # self.program.vert['normal'] = gloo.VertexBuffer(normals) self.set_gl_state('additive', cull_face=False) self._draw_mode = 'triangles' self._index_buffer = self._ibo
def _setup_textures(self, fname): data = imread(load_data_file('jfa/' + fname))[::-1].copy() self.texture_size = data.shape self.orig_tex = Texture2D(data, format='luminance', wrapping='repeat', interpolation='nearest') self.comp_texs = [] data = np.zeros(self.texture_size + (4,), np.float32) for _ in range(2): tex = Texture2D(data, format='rgba', wrapping='clamp_to_edge', interpolation='nearest') self.comp_texs.append(tex) self.fbo_to[0].color_buffer = self.comp_texs[0] self.fbo_to[1].color_buffer = self.comp_texs[1] for program in self.programs: program['texw'], program['texh'] = self.texture_size
def test_show_vispy(): """Some basic tests of show_vispy""" if has_matplotlib(): n = 200 t = np.arange(n) noise = np.random.RandomState(0).randn(n) # Need, image, markers, line, axes, figure plt.figure() ax = plt.subplot(211) ax.imshow(read_png(load_data_file('pyplot/logo.png'))) ax = plt.subplot(212) ax.plot(t, noise, 'ko-') plt.draw() canvases = plt.show() canvases[0].close() else: assert_raises(ImportError, plt.show)
def __init__(self): app.Canvas.__init__(self, title='Molecular viewer', keys='interactive') self.size = 1200, 800 self.translate = 40 self.program = gloo.Program(vertex, fragment) self.view = translate((0, 0, -self.translate)) self.model = np.eye(4, dtype=np.float32) self.projection = np.eye(4, dtype=np.float32) fname = load_data_file('molecular_viewer/micelle.npz') self.load_molecule(fname) self.load_data() self.theta = 0 self.phi = 0 self._timer = app.Timer('auto', connect=self.on_timer, start=True)
def _setup_textures(self, fname): img = Image.open(load_data_file('jfa/' + fname)) self.texture_size = tuple(img.size) data = np.array(img, np.ubyte)[::-1].copy() self.orig_tex = Texture2D(data, format='luminance') self.orig_tex.wrapping = 'repeat' self.orig_tex.interpolation = 'nearest' self.comp_texs = [] data = np.zeros(self.texture_size + (4,), np.float32) for _ in range(2): tex = Texture2D(data, format='rgba') tex.interpolation = 'nearest' tex.wrapping = 'clamp_to_edge' self.comp_texs.append(tex) self.fbo_to[0].color_buffer = self.comp_texs[0] self.fbo_to[1].color_buffer = self.comp_texs[1] for program in self.programs: program['texw'], program['texh'] = self.texture_size
def loadShapeTexture(filename, texID): """loadShapeTexture - load 8-bit shape texture data from a TGA file and set up the corresponding texture object.""" data, texw, texh = loadImage(load_data_file('jfa/' + filename)) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, texID) # Load image into texture gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_LUMINANCE, texw, texh, 0, gl.GL_LUMINANCE, gl.GL_UNSIGNED_BYTE, data) # This is the input image. We want unaltered 1-to-1 pixel values, # so specify nearest neighbor sampling to be sure. gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT) checkGLError() return texw, texh
def __init__(self): app.Canvas.__init__(self, title='Molecular viewer', keys='interactive') self.size = 1200, 800 self.program = gloo.Program(vertex, fragment) self.view = np.eye(4, dtype=np.float32) self.model = np.eye(4, dtype=np.float32) self.projection = np.eye(4, dtype=np.float32) self.translate = 40 translate(self.view, 0, 0, -self.translate) fname = load_data_file('molecular_viewer/micelle.npz') self.load_molecule(fname) self.load_data() self.theta = 0 self.phi = 0 self._timer = app.Timer('auto', connect=self.on_timer, start=True)
def get_test_image(): """Load an image from the demo-data repository if possible. Otherwise, just return a randomly generated image. """ from vispy.io import load_data_file, read_png try: return read_png(load_data_file('mona_lisa/mona_lisa_sm.png')) except Exception as exc: # fall back to random image print("Error loading demo image data: %r" % exc) # generate random image image = np.random.normal(size=(100, 100, 3)) image[20:80, 20:80] += 3. image[50] += 3. image[:, 50] += 3. image = ((image - image.min()) * (253. / (image.max() - image.min()))).astype(np.ubyte) return image
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()
def test_wavefront(): """Test wavefront reader""" fname_mesh = load_data_file('orig/triceratops.obj.gz') fname_out = op.join(temp_dir, 'temp.obj') mesh1 = read_mesh(fname_mesh) assert_raises(IOError, read_mesh, 'foo.obj') assert_raises(ValueError, read_mesh, op.abspath(__file__)) assert_raises(ValueError, write_mesh, fname_out, *mesh1, format='foo') write_mesh(fname_out, mesh1[0], mesh1[1], mesh1[2], mesh1[3]) assert_raises(IOError, write_mesh, fname_out, *mesh1) write_mesh(fname_out, *mesh1, overwrite=True) mesh2 = read_mesh(fname_out) assert_equal(len(mesh1), len(mesh2)) for m1, m2 in zip(mesh1, mesh2): if m1 is None: assert_equal(m2, None) else: assert_allclose(m1, m2, rtol=1e-5) # test our efficient normal calculation routine assert_allclose(mesh1[2], _slow_calculate_normals(mesh1[0], mesh1[1]), rtol=1e-7, atol=1e-7)
def get_image(): """Load an image from the demo-data repository if possible. Otherwise, just return a randomly generated image. """ from vispy.io import load_data_file, read_png try: return read_png(load_data_file('mona_lisa/mona_lisa_sm.png')) except Exception as exc: # fall back to random image print("Error loading demo image data: %r" % exc) # generate random image image = np.random.normal(size=(100, 100, 3)) image[20:80, 20:80] += 3. image[50] += 3. image[:, 50] += 3. image = ((image - image.min()) * (253. / (image.max() - image.min()))).astype(np.ubyte) return image
""" import sys from vispy import scene, app from vispy.visuals.filters import IsolineFilter from vispy.io import load_data_file, read_png canvas = scene.SceneCanvas(keys='interactive') canvas.size = 600, 800 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))
FRAG_CODE = """ uniform sampler2D u_texture; varying vec2 v_texcoord; void main() { float ty = v_texcoord.y; float tx = sin(ty*50.0)*0.01 + v_texcoord.x; gl_FragColor = texture2D(u_texture, vec2(tx, ty)); } """ # Read cube data positions, faces, normals, texcoords = \ read_mesh(load_data_file('orig/cube.obj')) colors = np.random.uniform(0, 1, positions.shape).astype('float32') faces_buffer = gloo.IndexBuffer(faces.astype(np.uint16)) class Canvas(app.Canvas): 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)
n = 200 freq = 10 fs = 100. t = np.arange(n) / fs tone = np.sin(2*np.pi*freq*t) noise = np.random.RandomState(0).randn(n) signal = tone + noise magnitude = np.abs(np.fft.fft(signal)) freqs = np.fft.fftfreq(n, 1. / fs) flim = n // 2 # Signal fig = plt.figure() ax = plt.subplot(311) ax.imshow(read_png(load_data_file('pyplot/logo.png'))) ax = plt.subplot(312) ax.plot(t, signal, 'k-') # Frequency content ax = plt.subplot(313) idx = np.argmax(magnitude[:flim]) ax.text(freqs[idx], magnitude[idx], 'Max: %s Hz' % freqs[idx], verticalalignment='top') ax.plot(freqs[:flim], magnitude[:flim], 'r-o') plt.draw() # NOTE: show() has currently been overwritten to convert to vispy format, so: # 1. It must be called to show the results, and
* WASD or arrow keys - move around * SPACE - brake * FC - move up-down * IJKL or mouse - look around """ from itertools import cycle import numpy as np from vispy import app, scene, io from vispy.color import get_colormaps, BaseColormap from vispy.visuals.transforms import STTransform # Read volume vol1 = np.load(io.load_data_file('volume/stent.npz'))['arr_0'] vol2 = np.load(io.load_data_file('brain/mri.npz'))['data'] vol2 = np.flipud(np.rollaxis(vol2, 1)) # Prepare canvas canvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True) canvas.measure_fps() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Create the volume visuals, only one is visible volume1 = scene.visuals.Volume(vol1, parent=view.scene, threshold=0.225) volume1.transform = scene.STTransform(translate=(64, 64, 0)) volume2 = scene.visuals.Volume(vol2, parent=view.scene, threshold=0.2) volume2.visible = False
n = 200 freq = 10 fs = 100. t = np.arange(n) / fs tone = np.sin(2 * np.pi * freq * t) noise = np.random.RandomState(0).randn(n) signal = tone + noise magnitude = np.abs(np.fft.fft(signal)) freqs = np.fft.fftfreq(n, 1. / fs) flim = n // 2 # Signal fig = plt.figure() ax = plt.subplot(311) ax.imshow(read_png(load_data_file('pyplot/logo.png'))) ax = plt.subplot(312) ax.plot(t, signal, 'k-') # Frequency content ax = plt.subplot(313) idx = np.argmax(magnitude[:flim]) ax.text(freqs[idx], magnitude[idx], 'Max: %s Hz' % freqs[idx], verticalalignment='top') ax.plot(freqs[:flim], magnitude[:flim], 'k-o') plt.draw()
void main() { gl_FragColor = textureCube(a_texture, v_texcoord); } """ vertices = np.array([[+1, +1, +1], [-1, +1, +1], [-1, -1, +1], [+1, -1, +1], [+1, -1, -1], [+1, +1, -1], [-1, +1, -1], [-1, -1, -1]]).astype(np.float32) faces = np.array([vertices[i] for i in [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 6, 7, 2, 1, 7, 4, 3, 2, 4, 7, 6, 5]]) indices = np.resize(np.array([0, 1, 2, 0, 2, 3], dtype=np.uint32), 36) indices += np.repeat(4 * np.arange(6, dtype=np.uint32), 6) texture = np.zeros((6, 1024, 1024, 3), dtype=np.float32) texture[2] = read_png(load_data_file("skybox/sky-left.png"))/255. texture[3] = read_png(load_data_file("skybox/sky-right.png"))/255. texture[0] = read_png(load_data_file("skybox/sky-front.png"))/255. texture[1] = read_png(load_data_file("skybox/sky-back.png"))/255. texture[4] = read_png(load_data_file("skybox/sky-up.png"))/255. texture[5] = read_png(load_data_file("skybox/sky-down.png"))/255. class Canvas(app.Canvas): def __init__(self): app.Canvas.__init__(self, size=(1024, 1024), title='Skybox example', keys='interactive') self.cubeSize = 10 self.pressed = False
Shading a Mesh ============== Show mesh filter usage for shading (lighting) a mesh and displaying a wireframe. """ import argparse from vispy import app, scene from vispy.io import read_mesh, load_data_file from vispy.scene.visuals import Mesh from vispy.scene import transforms from vispy.visuals.filters import ShadingFilter, WireframeFilter parser = argparse.ArgumentParser() default_mesh = load_data_file('orig/triceratops.obj.gz') parser.add_argument('--mesh', default=default_mesh) parser.add_argument('--shininess', default=100) parser.add_argument('--wireframe-width', default=1) args, _ = parser.parse_known_args() vertices, faces, normals, texcoords = read_mesh(args.mesh) canvas = scene.SceneCanvas(keys='interactive', bgcolor='white') view = canvas.central_widget.add_view() view.camera = 'arcball' view.camera.depth_value = 1e3 # Create a colored `MeshVisual`. mesh = Mesh(vertices, faces, color=(.5, .7, .5, 1))
* SPACE - brake * FC - move up-down * IJKL or mouse - look around """ from itertools import cycle import numpy as np from vispy import app, scene, io from vispy.scene import visuals import vispy.visuals as impl_visuals from vispy.color import get_colormaps, BaseColormap # Read volume vol1 = np.load(io.load_data_file('volume/stent.npz'))['arr_0'] vol2 = np.load(io.load_data_file('brain/mri.npz'))['data'] vol2 = np.flipud(np.rollaxis(vol2, 1)) # Prepare canvas canvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True) canvas.measure_fps() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Set whether we are emulating a 3D texture emulate_texture = False # Create the volume visuals, only one is visible volume1 = scene.visuals.Volume(vol1, parent=view.scene, threshold=0.225,
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # vispy: gallery 1 """ Plot various views of a structural MRI. """ import numpy as np from vispy import io, plot as vp fig = vp.Fig(bgcolor='k', size=(800, 800), show=False) vol_data = np.load(io.load_data_file('brain/mri.npz'))['data'] vol_data = np.flipud(np.rollaxis(vol_data, 1)) clim = [32, 192] vol_pw = fig[0, 0] # vol_pw.volume(vol_data, clim=clim) # vol_pw.view.camera.elevation = 30 # vol_pw.view.camera.azimuth = 30 # vol_pw.view.camera.scale_factor /= 1.5 shape = vol_data.shape fig[1, 0].image(vol_data[:, :, shape[2] // 2], cmap='grays', clim=clim, fg_color=(0.5, 0.5, 0.5, 1)) fig[0, 1].image(vol_data[:, shape[1] // 2, :], cmap='grays', clim=clim, fg_color=(0.5, 0.5, 0.5, 1)) img = fig[1, 0].image(vol_data[shape[0] // 2, :, :].T, cmap='grays', clim=clim, fg_color=(0.5, 0.5, 0.5, 1))
* 1: flip x dimension * 2: flip y dimension * 3: flip z dimension * 4: cycle through up-vectors * 5: cycle through cameras """ from itertools import cycle import numpy as np from vispy import app, scene, io from vispy.ext.six import next # Read volume vol1 = np.load(io.load_data_file('volume/stent.npz'))['arr_0'] # Prepare canvas canvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True) canvas.measure_fps() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Create the volume visuals, only one is visible volume1 = scene.visuals.Volume(vol1, parent=view.scene, threshold=0.5) #volume1.method = 'iso' volume1.threshold = 0.1 # Plot a line that shows where positive x is, with at the end a small # line pointing at positive y
* 1: flip x dimenstion * 2: flip y dimension * 3: flip z dimenstion * 4: cycle through up-vectors * 5: cycle through cameras """ from itertools import cycle import numpy as np from vispy import app, scene, io from vispy.ext.six import next # Read volume vol1 = np.load(io.load_data_file("volume/stent.npz"))["arr_0"] # Prepare canvas canvas = scene.SceneCanvas(keys="interactive", size=(800, 600), show=True) canvas.measure_fps() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Create the volume visuals, only one is visible volume1 = scene.visuals.Volume(vol1, parent=view.scene, threshold=0.5) # volume1.method = 'iso' volume1.threshold = 0.1 # Plot a line that shows where positive x is, with at the end a small # line pointing at positive y
# Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ 3D brain mesh viewer. """ from timeit import default_timer import numpy as np from vispy import gloo from vispy import app from vispy.util.transforms import perspective, translate, rotate from vispy.io import load_data_file brain = np.load(load_data_file("brain/brain.npz", force_download="2014-09-04")) data = brain["vertex_buffer"] faces = brain["index_buffer"] VERT_SHADER = """ #version 120 uniform mat4 u_model; uniform mat4 u_view; uniform mat4 u_projection; uniform vec4 u_color; attribute vec3 a_position; attribute vec3 a_normal; attribute vec4 a_color; varying vec3 v_position;
FRAG_CODE = """ uniform sampler2D u_texture; varying vec2 v_texcoord; void main() { float ty = v_texcoord.y; float tx = sin(ty*50.0)*0.01 + v_texcoord.x; gl_FragColor = texture2D(u_texture, vec2(tx, ty)); } """ # Read cube data positions, faces, normals, texcoords = \ read_mesh(load_data_file('orig/cube.obj')) colors = np.random.uniform(0, 1, positions.shape).astype('float32') faces_buffer = gloo.IndexBuffer(faces.astype(np.uint16)) class Canvas(app.Canvas): 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)
FRAG_CODE = """ uniform sampler2D u_texture; varying vec2 v_texcoord; void main() { float ty = v_texcoord.y; float tx = sin(ty*50.0)*0.01 + v_texcoord.x; gl_FragColor = texture2D(u_texture, vec2(tx, ty)); } """ # Read cube data positions, faces, normals, texcoords = read_mesh(load_data_file("orig/cube.obj")) colors = np.random.uniform(0, 1, positions.shape).astype("float32") faces_buffer = gloo.IndexBuffer(faces.astype(np.uint16)) class Canvas(app.Canvas): 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)
# Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ 3D brain mesh viewer. """ from timeit import default_timer import numpy as np from vispy import gloo from vispy import app from vispy.util.transforms import perspective, translate, rotate from vispy.io import load_data_file brain = np.load(load_data_file('brain/brain.npz', force_download='2014-09-04')) data = brain['vertex_buffer'] faces = brain['index_buffer'] VERT_SHADER = """ #version 120 uniform mat4 u_model; uniform mat4 u_view; uniform mat4 u_projection; uniform vec4 u_color; attribute vec3 a_position; attribute vec3 a_normal; attribute vec4 a_color; varying vec3 v_position;
# -*- coding: utf-8 -*- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ Plot data with different styles """ import numpy as np from vispy import plot as vp from vispy.io import load_data_file data = np.load(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) line = fig[0, 0].plot((x, y), symbol='o', width=3, title='I/V Curve', xlabel='Current (pA)', ylabel='Membrane Potential (mV)') grid = vp.visuals.GridLines(color=(0, 0, 0, 0.5)) grid.set_gl_state('translucent') fig[0, 0].view.add(grid) if __name__ == '__main__': fig.show(run=True)
import numpy as np from vispy import app, scene from vispy.io import imread, load_data_file, read_mesh from vispy.scene.visuals import Mesh from vispy.scene import transforms from vispy.visuals.filters import TextureFilter parser = argparse.ArgumentParser() parser.add_argument('--shading', default='smooth', choices=['none', 'flat', 'smooth'], help="shading mode") args, _ = parser.parse_known_args() mesh_path = load_data_file('spot/spot.obj.gz') texture_path = load_data_file('spot/spot.png') vertices, faces, normals, texcoords = read_mesh(mesh_path) texture = np.flipud(imread(texture_path)) canvas = scene.SceneCanvas(keys='interactive', bgcolor='white', size=(800, 600)) view = canvas.central_widget.add_view() view.camera = 'arcball' # Adapt the depth to the scale of the mesh to avoid rendering artefacts. view.camera.depth_value = 10 * (vertices.max() - vertices.min()) shading = None if args.shading == 'none' else args.shading mesh = Mesh(vertices, faces, shading=shading, color='white')
# vispy: gallery 2 # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ 3D brain mesh viewer. """ from timeit import default_timer import numpy as np from vispy import gloo from vispy import app from vispy.util.transforms import perspective, translate, rotate from vispy.io import load_data_file brain = np.load(load_data_file('brain/brain.npz', force_download='2014-09-04')) data = brain['vertex_buffer'] faces = brain['index_buffer'] VERT_SHADER = """ #version 120 uniform mat4 u_model; uniform mat4 u_view; uniform mat4 u_projection; uniform vec4 u_color; attribute vec3 a_position; attribute vec3 a_normal; attribute vec4 a_color; varying vec3 v_position;
import numpy as np import vispy.plot as vp from vispy.color import get_colormap # load example data from vispy.io import load_data_file data = np.load(load_data_file('electrophys/iv_curve.npz'))['arr_0'] data *= 1000 # V -> mV dt = 1e-4 # this data is sampled at 10 kHz # create figure with plot fig = vp.Fig() plt = fig[0, 0] plt._configure_2d() plt.title.text = 'Current Clamp Recording' plt.ylabel.text = 'Membrane Potential (mV)' plt.xlabel.text = 'Time (ms)' selected = None # plot data cmap = get_colormap('hsl', value=0.5) colors = cmap.map(np.linspace(0.1, 0.9, data.shape[0])) t = np.arange(data.shape[1]) * (dt * 1000) for i, y in enumerate(data): line = plt.plot((t, y), color=colors[i]) line.interactive = True line.unfreeze() # make it so we can add a new property to the instance line.data_index = i line.freeze()
# Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ 3D brain mesh viewer. """ from timeit import default_timer import numpy as np from vispy import gloo from vispy import app from vispy.util.transforms import perspective, translate, rotate from vispy.io import load_data_file brain = np.load(load_data_file('brain/brain.npz')) data = brain['vertex_buffer'] faces = brain['index_buffer'] VERT_SHADER = """ #version 120 uniform mat4 u_model; uniform mat4 u_view; uniform mat4 u_projection; uniform vec4 u_color; attribute vec3 a_position; attribute vec3 a_normal; attribute vec4 a_color; varying vec3 v_position;
margin=25) # Line3 view (aggretate) view5 = grid.add_view(row=2, col=1, col_span=1, bgcolor=(1,0,1,alpha), border_color=(1,0,1), margin=10) # TBD view6 = grid.add_view(row=2, col=2, col_span=1, bgcolor=(1,1,1,alpha), border_color=(1,1,1), margin=10) # TBD view7 = grid.add_view(row=2, col=3, col_span=1, bgcolor=(1,1,0,alpha), border_color=(1,1,0), margin=10) ##################### Put img on one view1 ##################### img_data = read_png(load_data_file('mona_lisa/mona_lisa_sm.png')) print img_data.shape image = scene.Image(img_data, parent=view1.scene) view1.camera = scene.PanZoomCamera(aspect=1) view1.camera.flip = (0,1,0) view1.camera.set_range() # important ##################### Volume to another view2 ##################### vol = np.load(load_data_file('brain/mri.npz'))['data'] vol = np.flipud(np.swapaxes(vol, 0, 1)) print vol.shape volume = scene.Volume(vol, parent=view2.scene, threshold=0.225, emulate_texture=True) # volume.transform = scene.STTransform(translate=(0, 0, 200)) # scene.visuals.XYZAxis(parent=view2.scene) view2.camera = scene.TurntableCamera(parent=view2.scene)
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- """ Example of simple mesh plotting and manipulation. """ import sys import numpy as np from vispy.io import load_data_file import vispy.plot as vp fname = load_data_file('orig/triceratops.obj.gz') canvas = vp.mesh(fname=fname, azimuth=-0, elevation=90, distance=2) vertex_colors = np.random.rand(canvas.mesh.mesh_data.n_vertices, 3) ** 2 canvas.mesh.mesh_data.set_vertex_colors(vertex_colors) if __name__ == '__main__': canvas.show() if sys.flags.interactive == 0: canvas.app.run()
break if __name__ == "__main__": import coloredlogs logging.getLogger("tifffile").setLevel(logging.ERROR) logging.getLogger("matplotlib").setLevel(logging.WARNING) coloredlogs.install(level="DEBUG", fmt="%(asctime)s %(levelname)s %(message)s", datefmt="%H:%M:%S") from vispy import io vol = np.load(io.load_data_file("brain/mri.npz"))["data"] print(vol.dtype) """ import imageio vol = imageio.volread('20181019_expanded_hippo/1-Pos_002_005.tif') """ import cupy as cp vol = cp.asarray(vol) from utoolbox.exposure import auto_contrast vol = auto_contrast(vol) vol = cp.asnumpy(vol) vol = np.swapaxes(vol, 0, 1) print(vol.dtype)
""" import sys from vispy import scene, app from vispy.visuals.filters import IsolineFilter from vispy.io import load_data_file, read_png canvas = scene.SceneCanvas(keys='interactive') canvas.size = 600, 800 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' %
""" Surface normals wireframe ========================= Display a 3D mesh with normals and wireframe """ from vispy.io import read_mesh, load_data_file import napari vert, faces, _, _ = read_mesh(load_data_file('orig/triceratops.obj.gz')) # put the mesh right side up, scale it up (napari#3477) and fix faces handedness vert *= -100 faces = faces[:, ::-1] viewer = napari.Viewer(ndisplay=3) surface = viewer.add_surface(data=(vert, faces)) # enable normals and wireframe surface.normals.face.visible = True surface.normals.vertex.visible = True surface.wireframe.visible = True if __name__ == '__main__': napari.run()
# # Colormaps. # cmap='grays'; clim=(-2, 2) # # Get visual nodes ready. # visual_nodes = volume_slices(volume, # cmaps=cmap, clims=clim, # # x_pos=32, y_pos=25, z_pos=93) # x_pos=[370, 170, 570, 770], y_pos=810, z_pos=120) # xyz_axis = XYZAxis() # colorbar = Colorbar(cmap=cmap, clim=clim, label_str='Seismic Amplitude', # label_size=8, tick_size=6) # Test 2: brain CT data. from vispy import io volume = np.load(io.load_data_file('brain/mri.npz'))['data'] volume = volume.transpose(2, 0, 1)[:, :, ::-1] axis_scales = (1, 1, 1) # isotropoic axes visual_nodes = volume_slices(volume, x_pos=100, y_pos=128, z_pos=30, seismic_coord_system=False) xyz_axis = XYZAxis(seismic_coord_system=False) colorbar = Colorbar(cmap='grays', clim=(volume.min(), volume.max()), label_str='Amplitude', label_size=8, tick_size=6) # Run the canvas. canvas = SeismicCanvas(title='Simple Demo', visual_nodes=visual_nodes, xyz_axis=xyz_axis,
def __init__(self): app.Canvas.__init__(self, keys='interactive', size=(800, 600)) brain = np.load(load_data_file('brain/brain.npz', force_download='2014-09-04')) #brain1 = scipy.io.loadmat('NewBESATri.mat') brain2 = brain1['t'] from numpy import genfromtxt my_data = genfromtxt('BESACOORD61.csv', delimiter=',') dataTest = brain['vertex_buffer'] color = dataTest['a_color'] color = color[750:1500] facesTest = brain['index_buffer'] n = 750 ps = 100 data = np.zeros(n, [('a_position', np.float32, 3), ('a_normal', np.float32, 3), ('a_color', np.float32, 3)]) #('a_size', np.float32, 1)]) import scipy.spatial tri = scipy.spatial.Delaunay(my_data) # points: np.array() of 3d points convex = tri.convex_hull indices = tri.simplices vertices = my_data[indices] data['a_position'] = my_data data['a_color'] = np.random.uniform(0, 1, (n, 3)) faces = brain2 faces = faces-1 vertices = my_data norm = np.zeros( vertices.shape, dtype=vertices.dtype ) #Create an indexed view into the vertex array using the array of three indices for triangles tris = vertices[faces] #Calculate the normal for all the triangles, by taking the cross product of the vectors v1-v0, and v2-v0 in each triangle n = np.cross( tris[::,1 ] - tris[::,0] , tris[::,2 ] - tris[::,0] ) # n is now an array of normals per triangle. The length of each normal is dependent the vertices, # we need to normalize these, so that our next step weights each normal equally. lens = np.sqrt( n[:,0]**2 + n[:,1]**2 + n[:,2]**2 ) n[:,0] /= lens n[:,1] /= lens n[:,2] /= lens norm[ faces[:,0] ] += n norm[ faces[:,1] ] += n norm[ faces[:,2] ] += n ''' Normalize a numpy array of 3 component vectors shape=(n,3) ''' lens = np.sqrt( norm[:,0]**2 + norm[:,1]**2 + norm[:,2]**2 ) norm[:,0] /= lens norm[:,1] /= lens norm[:,2] /= lens data['a_normal'] = norm #np.random.uniform(0, 1.0, (n, 3)) #10, 3, 3 #data['a_size'] = np.random.uniform(5*ps, 10*ps, n) u_linewidth = 1.0 u_antialias = 1.0 brain2 = np.uint32(brain2) convex = np.uint32(convex) data = data faces = brain2-1 #data = dataTest #faces = facesTest self.meshes = [] self.rotation = MatrixTransform() # Generate some data to work with global mdata mdata = create_sphere(20, 40, 1.0) #mdata['_faces'] =faces #mdata['_vertices']=data # Mesh with pre-indexed vertices, uniform color meshData=vispy.geometry.MeshData(vertices=data['a_position'], faces=None, edges=None, vertex_colors=None, face_colors=None) meshData._vertices = data['a_position'] meshData._faces = faces #meshData._face_colors = data['a_color'] #meshData._vertex_colors = data['a_color'] self.meshes.append(visuals.MeshVisual(meshdata=meshData, color='b')) #for mesh in self.meshes: # mesh.draw() # Mesh with pre-indexed vertices, per-face color # Because vertices are pre-indexed, we get a different color # every time a vertex is visited, resulting in sharp color # differences between edges. tris = vertices[faces] verts = data['a_position'] #mdata.get_vertices(indexed='faces') nf = 1496#verts.size//9 fcolor = np.ones((nf, 3, 4), dtype=np.float32) fcolor[..., 0] = np.linspace(1, 0, nf)[:, np.newaxis] fcolor[..., 1] = np.random.normal(size=nf)[:, np.newaxis] fcolor[..., 2] = np.linspace(0, 1, nf)[:, np.newaxis] #fcolor = data['a_color'] mesh = visuals.MeshVisual(vertices=tris, face_colors=fcolor) self.meshes.append(mesh) # Mesh with unindexed vertices, per-vertex color # Because vertices are unindexed, we get the same color # every time a vertex is visited, resulting in no color differences # between edges. #verts = mdata.get_vertices() faces = faces #mdata.get_faces() nv = verts.size//3 vcolor = np.ones((nv, 4), dtype=np.float32) vcolor[:, 0] = np.linspace(.6, .6, nv) vcolor[:, 1] = np.random.normal(size=nv) vcolor[:, 2] = np.linspace(0.6, .6, nv) self.meshes.append(visuals.MeshVisual(verts, faces, vcolor)) self.meshes.append(visuals.MeshVisual(verts, faces, vcolor, shading='flat')) # self.meshes.append(visuals.MeshVisual(verts, faces, vcolor, shading='smooth')) # Lay out meshes in a grid grid = (1, 1) s = 300. / max(grid) #s = 500 for i, mesh in enumerate(self.meshes): x = 800. * (i % grid[0]) / grid[0] / grid[0] - 2 y = 800. * (i // grid[1]) / grid[1] / grid[1] + 2 transform = ChainTransform([STTransform(translate=(x, y), scale=(s, s, s)), self.rotation]) mesh.transform = transform mesh.transforms.scene_transform = STTransform(scale=(.01, .01, .00001)) self.show() self.timer = app.Timer(connect=self.rotate) self.timer.start(0.00016)
gl_FragColor = textureCube(a_texture, v_texcoord); } """ vertices = np.array([[+1, +1, +1], [-1, +1, +1], [-1, -1, +1], [+1, -1, +1], [+1, -1, -1], [+1, +1, -1], [-1, +1, -1], [-1, -1, -1]]).astype(np.float32) faces = np.array([ vertices[i] for i in [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 6, 7, 2, 1, 7, 4, 3, 2, 4, 7, 6, 5] ]) indices = np.resize(np.array([0, 1, 2, 0, 2, 3], dtype=np.uint32), 36) indices += np.repeat(4 * np.arange(6, dtype=np.uint32), 6) texture = np.zeros((6, 1024, 1024, 3), dtype=np.float32) texture[2] = read_png(load_data_file("skybox/sky-left.png")) / 255. texture[3] = read_png(load_data_file("skybox/sky-right.png")) / 255. texture[0] = read_png(load_data_file("skybox/sky-front.png")) / 255. texture[1] = read_png(load_data_file("skybox/sky-back.png")) / 255. texture[4] = read_png(load_data_file("skybox/sky-up.png")) / 255. texture[5] = read_png(load_data_file("skybox/sky-down.png")) / 255. class Canvas(app.Canvas): def __init__(self): app.Canvas.__init__(self, size=(1024, 1024), title='Skybox example', keys='interactive') self.cubeSize = 10
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- """ Example of simple mesh plotting and manipulation. """ import sys import numpy as np from vispy.io import load_data_file import vispy.plot as vp fname = load_data_file('orig/triceratops.obj.gz') canvas = vp.mesh(fname=fname, azimuth=-0, elevation=90, distance=2) vertex_colors = np.random.rand(canvas.mesh.mesh_data.n_vertices, 3)**2 canvas.mesh.mesh_data.set_vertex_colors(vertex_colors) if __name__ == '__main__': canvas.show() if sys.flags.interactive == 0: canvas.app.run()