pp.append(0,0,0); pp.append(0,1,0); pp.append(1,2,0); pp.append(0,2,1) # Create all solids box = vv.solidBox((0,0,0)) sphere = vv.solidSphere((3,0,0)) cone = vv.solidCone((6,0,0)) pyramid = vv.solidCone((9,0,0), N=4) # a cone with 4 faces is a pyramid cylinder = vv.solidCylinder((0,3,0),(1,1,2)) ring = vv.solidRing((3,3,0)) teapot = vv.solidTeapot((6,3,0)) line = vv.solidLine(pp+Point(9,3,0), radius = 0.2) # Let's put a face on that cylinder # This works because 2D texture coordinates are automatically generated for # the sphere, cone, cylinder and ring. im = vv.imread('astronaut.png') cylinder.SetTexture(im) # Make the ring green ring.faceColor = 'g' # Make the sphere dull sphere.specular = 0 sphere.diffuse = 0.4 # Show lines in yellow pyramid pyramid.faceColor = 'y' pyramid.edgeShading = 'plain' # Colormap example N = cone._vertices.shape[0]
verticesPerFace=4) # if translation is not None: m.translation = translation if scaling is not None: m.scaling = scaling if direction is not None: m.direction = direction if rotation is not None: m.rotation = rotation # Set flat shading? if N < 8 or M < 8: m.faceShading = 'flat' # Adjust axes if axesAdjust: if axes.daspectAuto is None: axes.daspectAuto = False axes.cameraType = '3d' axes.SetLimits() # Done axes.Draw() return m if __name__ == '__main__': m = vv.solidCone(N=12) m.SetTexture(vv.imread('astronaut.png'))
m = vv.Mesh(axes, vertices, faces, values=texcoords, verticesPerFace=4) # Should we apply a texture? if c is not None and c.ndim==3: m.SetTexture(c) # Adjust axes if axesAdjust: if axes.daspectAuto is None: axes.daspectAuto = False axes.cameraType = '3d' axes.SetLimits() # Return axes.Draw() return m if __name__ == "__main__": # Read image and smooth a bit lena = vv.imread('lena.png').astype(np.float32) im = lena.copy() im[1:,:,:] = lena[:-1,:,:] im[:-1,:,:] += lena[1:,:,:] im[:,:-1,:] += lena[:,1:,:] im[:,1:,:] += lena[:,:-1,:] im /= 4 # Surf m = vv.surf(im[:,:,0], im)
#!/usr/bin/env python import numpy as np import visvis as vv # Read image and crop astro = vv.imread('astronaut.png').astype(np.float32) astro = astro[100:-100, 100:-100, :] # Smooth a bit im = astro.copy() im[1:, :, :] = astro[:-1, :, :] im[:-1, :, :] += astro[1:, :, :] im[:, :-1, :] += astro[:, 1:, :] im[:, 1:, :] += astro[:, :-1, :] im /= 4 # Prepare figure vv.figure() # Without color, with colormap a1 = vv.subplot(121) m1 = vv.surf(im[:, :, 0]) m1.colormap = vv.CM_HOT vv.title('With colormap') # With color a2 = vv.subplot(122) m2 = vv.surf(im[:, :, 0], im) vv.title('With original texture')
parser = argparse.ArgumentParser(description='Visualise the 3D volume') parser.add_argument('--image', dest='image', help="The background image to display") parser.add_argument('--volume', dest='volume', help="The volume to render") parser.add_argument('--texture', dest='texture', help="Show textured mesh NOT YET IMPLEMENTED") args = parser.parse_args() vol = np.fromfile(args.volume, dtype=np.int8) # vol = vol.reshape((200, 192, 192)) im = vv.imread(args.image) t = vv.imshow(im) t.interpolate = True # interpolate pixels # volshow will use volshow3 and rendering the isosurface if OpenGL # version is >= 2.0. Otherwise, it will show slices with bars that you # can move (much less useful). volRGB = np.stack(((vol > 1) * im[:, :, 0], (vol > 1) * im[:, :, 1], (vol > 1) * im[:, :, 2]), axis=3) v = vv.volshow(volRGB, renderStyle='iso') v.transformations[1].sz = 0.5 # Z was twice as deep during training l0 = vv.gca()
if axes is None: axes = vv.gca() # Create mesh m = vv.OrientableMesh(axes, vertices, indices, normals, texcords, 4) # if translation is not None: m.translation = translation if scaling is not None: m.scaling = scaling if direction is not None: m.direction = direction if rotation is not None: m.rotation = rotation # Adjust axes if axesAdjust: if axes.daspectAuto is None: axes.daspectAuto = False axes.cameraType = '3d' axes.SetLimits() # Done axes.Draw() return m if __name__ == '__main__': m = vv.solidSphere(scaling=(1, 1, 1.5), direction=(1, 1, 3)) m.SetTexture(vv.imread('lena.png'))
#!/usr/bin/env python import visvis as vv # Create figure and make it wider than the default fig = vv.figure() fig.position.w = 700 # Create first axes a1 = vv.subplot(121) # Display an image im = vv.imread('astronaut.png') # returns a numpy array texture2d = vv.imshow(im) texture2d.interpolate = True # if False the pixels are visible when zooming in # Display two lines (values obtained via vv.ginput()) x = [182, 180, 161, 153, 191, 237, 293, 300, 272, 267, 254] y = [145, 131, 112, 59, 29, 14, 48, 91, 136, 137, 172] line1 = vv.plot(x, y, ms='.', mw=4, lw=2) # x = [507, 498, 483, 438, 364, 299, 278, 280] y = [483, 452, 389, 349, 347, 393, 448, 508] line2 = vv.plot(x, y, ms='s', mw=4, lw=2) # The appearance of the line objects can be set in their # constructor, or by using their properties line1.lc, line1.mc = 'g', 'b' line2.lc, line2.mc = 'y', 'r' # Display a legend a1.legend = "Astronaut's face", "Astronaut's helmet"
#!/usr/bin/env python import visvis as vv app = vv.use() # Get green channel of lena image im = vv.imread('astronaut.png')[:, :, 1] # Make 4 subplots with different colormaps cmaps = [vv.CM_GRAY, vv.CM_JET, vv.CM_SUMMER, vv.CM_HOT] for i in range(4): a = vv.subplot(2, 2, i + 1) t = vv.imshow(im, clim=(0, 255)) a.axis.visible = 0 t.colormap = cmaps[i] vv.colorbar() app.Run()
# -*- coding: utf-8 -*- # Copyright (C) 2012-2017, Almar Klein # # Visvis is distributed under the terms of the (new) BSD License. # The full license can be found in 'license.txt'. import visvis as vv def isocontour(im, isovalue=None): """ isocontour(im, isovalue=None) Uses scikit-image to calculate the iso contours for the given 2D image. If isovalue is not given or None, a value between the min and max of the image is used. Returns a pointset in which each two subsequent points form a line piece. This van be best visualized using "vv.plot(result, ls='+')". """ from visvis.utils.iso import isocontour as _isocontour return _isocontour(im, isovalue) if __name__ == '__main__': vv.plot(isocontour(vv.imread('astronaut.png')[:, :, 1]), ls='+', lw=3)
#!/usr/bin/env python import visvis as vv # Create figure and make it wider than the default fig = vv.figure() fig.position.w = 700 # Create first axes a1 = vv.subplot(121) # Display an image im = vv.imread('lena.png') # returns a numpy array texture2d = vv.imshow(im) texture2d.interpolate = True # if False the pixels are visible when zooming in # Display two lines (values obtained via vv.ginput()) x = [220, 258, 308, 336, 356, 341, 318, 311, 253, 225, 220] y = [287, 247, 212, 201, 253, 318, 364, 385, 382, 358, 287] line1 = vv.plot(x, y, ms='.', mw=4, lw=2) # x = [237, 284, 326, 352, 381, 175, 195, 217, 232, 237] y = [385, 386, 394, 413, 507, 507, 476, 441, 399, 385] line2 = vv.plot(x, y, ms='s', mw=4, lw=2) # The appearance of the line objects can be set in their # constructor, or by using their properties line1.lc, line1.mc = 'g', 'b' line2.lc, line2.mc = 'y', 'r' # Display a legend
def test_im_read_write(): import visvis as vv im = vv.imread('astronaut.png') assert im.shape == (512, 512, 3) vv.imwrite(os.path.expanduser('~/astronaut2.png'), im)
bottom right is a mesh obtained using the isosurface function. They look a lot the same... """ import visvis as vv import numpy as np import time from visvis.utils.iso import isosurface, isocontour from visvis.utils import iso if __name__ == '__main__': # Get image SELECT = 0 if SELECT == 0: im = vv.imread('lena.png')[:, :, 0].astype('float32') elif SELECT == 1: im = np.zeros((64, 64), 'float32') im[20:50, 30:40] = 1.0 im[25:50, 40] = 0.6 im[30:40, 20:50] = 1.0 # Get contours t0 = time.time() for i in range(100): pp = isocontour(im) print('finding contours took %1.0f ms' % (100 * (time.time() - t0))) # Create test volume SELECT = 3 if SELECT == 0:
#!/usr/bin/env python """ This example illustrates how to create an isocontour from an image and display it over the contour. The contour consists of a pointset in which each 2 subsequent points describe a linepiece. This code relies on scikit-image. For a possibly more useful representation of the contour, see skimage.measure.find_contours. """ import visvis as vv im = vv.imread('imageio:chelsea.png')[:, :, 1] pp = vv.isocontour(im) vv.figure(1) vv.clf() vv.imshow(im) vv.plot(pp, ls='+', lw=2) vv.title('Isocontour') app = vv.use() app.Run()
uval.sort(key=firstItem) #array.sort(key = lambda x:x[1]) #l = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']] #l.sort(key=lambda x: x[2]) print("uval sorted: ", uval) #sys.exit(1) app = vv.use() img_lst = [] for i in range(0, use_len): img_nm = "pat_dash%.5d.png" % lp_arr[i] print("nm= %s" % img_nm) img_lst.append(vv.imread(img_nm)) #sys.exit(1) #img = img[:-1,:-1] # make not-power-of-two (to test if video driver is capable) #print(img.shape) y0i = int(y0) y1i = int(y1)+1 x1i = int(x1)+1 vv.figure() a1 = vv.subplot(121) #im = vv.Aarray(im) im = vv.Aarray((y1i+y0i, use_len*x1i, 4)) # Cut in four pieces, but also change resolution using different step sizes
# Should we apply a texture? if c is not None and c.ndim == 3: m.SetTexture(c) else: m.clim = m.clim # trigger correct limits # Adjust axes if axesAdjust: if axes.daspectAuto is None: axes.daspectAuto = False axes.cameraType = '3d' axes.SetLimits() # Return axes.Draw() return m if __name__ == "__main__": # Read image and smooth a bit lena = vv.imread('lena.png').astype(np.float32) im = lena.copy() im[1:, :, :] = lena[:-1, :, :] im[:-1, :, :] += lena[1:, :, :] im[:, :-1, :] += lena[:, 1:, :] im[:, 1:, :] += lena[:, :-1, :] im /= 4 # Surf m = vv.surf(im[:, :, 0], im)
def fromImage(self, fileName, threshold): im = vv.imread(fileName) img = imToGS(im) binArray = (img < threshold).astype(np.int32) self.fromArray(binArray)
try: buildFile(fp, taglist, nframes=nframes, framesize=wh, fps=fps) except Exception: raise finally: fp.close() #print "build tags (%1.2f s)" % (time.time()-t1) tt = time.time()-t0 print "written %i frames to swf in %1.2f seconds (%1.0f ms/frame)" % ( len(images), tt, 1000*tt/len(images) ) if __name__ == "__main__": import visvis as vv im = np.zeros((200,200), dtype=np.uint8) im[10:30,:] = 100 im[:,80:120] = 255 im[-50:-40,:] = 50 im = vv.imread(r'D:\almar\projects\_p\smith.jpg') images = [im*i for i in np.arange(0.1,1,0.1)] delays = [1 for i in range(len(images))] delays[2]=3 delays[3]=5 writeSwf( 'test.swf', images, 5, 1, delays )
elif len(image.shape) == 3: if image.shape[2] in [3, 4]: pass # RGB or RGBA else: raise ValueError("Cannot write image: Too many values in third dim.") else: raise ValueError("Cannot write image: Invalid number of dimensions.") # check type -> convert if image.dtype.name == 'uint8': pass # ok elif image.dtype.name in ['float32', 'float64']: image = image.copy() image[image<0] = 0 image[image>1] = 1 image = (image*255).astype(np.uint8) else: image = image.astype(np.uint8) # write image if imageio: imageio.imsave(filename, image, format) elif PIL: pim = PIL.Image.fromarray(image) pim.save(filename, format) if __name__ == '__main__': im = vv.imread('lena.png') vv.imwrite('lena_new.jpg', im)
i['keyEvent'] = None else: ''' Wait until key pressed ''' while(time.time()-start_time < np.inf): vv.processEvents() keys = [x['keyEvent'] for x in self.open_windows if x['keyEvent'] is not None] time.sleep(.000001) if len(keys) > 0: break ''' Check for keys pressed ''' if len(keys) > 0: return keys.pop() else: return 0 if __name__=="__main__": w = VideoViewer() im = vv.imread('/Users/colin/Desktop/hog.png') w.imshow("Hi", np.eye(100, dtype=np.uint8), axis=True) w.imshow("im", im, axis=False) for j in range(100): key = w.waitAndUpdate(1000) w.imshow("im", im+j*5, axis=False) print key
""" Example demonstrating registering an image to another. Applicable using different registration algorithms, e.g. Gravity or Demons. This can also be used to play with the registration parameters. """ import pirt import visvis as vv import numpy as np # Get image im1 = vv.imread('astronaut.png')[:, :, 1].astype('float32') im1 = pirt.diffuse(im1, 1)[::2, ::2] / 255.0 # Deform image scale = im1.shape[0] * 0.4 rd = pirt.create_random_deformation(im1, 40, 40, mapping='backward', seed=1001) im2 = rd.apply_deformation(im1) # Add noise im1 += np.random.normal(0, 0.1, im1.shape) im2 += np.random.normal(0, 0.1, im1.shape) # Get figure vv.closeAll() fig = vv.figure(1) vv.clf() fig.position = 200, 100, 900, 500 # Init registration
verticesPerFace=4) # if translation is not None: m.translation = translation if scaling is not None: m.scaling = scaling if direction is not None: m.direction = direction if rotation is not None: m.rotation = rotation # Set flat shading? if N<8 or M<8: m.faceShading = 'flat' # Adjust axes if axesAdjust: if axes.daspectAuto is None: axes.daspectAuto = False axes.cameraType = '3d' axes.SetLimits() # Done axes.Draw() return m if __name__ == '__main__': m = vv.solidCone(N=12) m.SetTexture( vv.imread('lena.png') )
polypp = PointSet(2) for i in np.linspace(-1,1,100): polypp.append(i, polynom[0]*i**2 + polynom[1]*i + polynom[2]) # Visualize vv.subplot(121) vv.plot([-1,0,1],pp) vv.plot([t_max, t_max], [0,1], lc='r') vv.plot(polypp, lc='r') ## 2D # Input and result im = vv.imread('astronaut.png')[::,::,2].copy() Y,X = np.where(im==im.max()) Y,X = Y[0], X[0] im[Y-1,X] -= 20 # make more interesting :) mat = im[Y-1:Y+2, X-1:X+2] # Get result and scale mat ymin, ymax, surface = fitting.fit_lq2(mat, True) mat = Aarray(mat, sampling=(100, 100), origin=(50, 50)) # Visualize vv.subplot(122) vv.imshow(mat) m = vv.surf(surface) a = vv.gca() a.SetLimits()
for i in self.open_windows: i['keyEvent'] = None else: ''' Wait until key pressed ''' while (time.time() - start_time < np.inf): vv.processEvents() keys = [ x['keyEvent'] for x in self.open_windows if x['keyEvent'] is not None ] time.sleep(.000001) if len(keys) > 0: break ''' Check for keys pressed ''' if len(keys) > 0: return keys.pop() else: return 0 if __name__ == "__main__": w = VideoViewer() im = vv.imread('/Users/colin/Desktop/hog.png') w.imshow("Hi", np.eye(100, dtype=np.uint8), axis=True) w.imshow("im", im, axis=False) for j in range(100): key = w.waitAndUpdate(1000) w.imshow("im", im + j * 5, axis=False) print key
# Setup detecting closing of figure self._closed = False def callback(event): self._closed = True self._fig.eventClose.Bind(callback) while not self._closed: time.sleep(0.02) vv.processEvents() self.apply_deform() if __name__ == '__main__': d = DeformByHand(vv.imread('astronaut.png')[:,:,2].astype('float32')) WHAT = 'twist' if WHAT == 'twist': d._pp1.append(108.27, 416.57 ) d._pp1.append(330.78, 385.58 ) d._pp1.append(220.08, 393.32 ) d._pp1.append(406.06, 266.02 ) d._pp1.append(389.45, 186.31 ) d._pp1.append(347.38, 122.1 ) d._pp1.append(401.63, 332.44 ) d._pp1.append(290.92, 395.54 ) # d._pp2.append(249.96, 449.78 ) d._pp2.append(414.91, 333.55 )
bottom right is a mesh obtained using the isosurface function. They look a lot the same... """ import visvis as vv import numpy as np import time from visvis.utils.iso import isosurface, isocontour from visvis.utils import iso if __name__ == '__main__': # Get image SELECT = 0 if SELECT == 0: im = vv.imread('lena.png')[:,:,0].astype('float32') elif SELECT == 1: im = np.zeros((64,64), 'float32') im[20:50,30:40] = 1.0 im[25:50,40] = 0.6 im[30:40,20:50] = 1.0 # Get contours t0 = time.time() for i in range(100): pp = isocontour(im) print('finding contours took %1.0f ms' % (100*(time.time()-t0)) ) # Create test volume SELECT = 3
# if translation is not None: m.translation = translation if scaling is not None: m.scaling = scaling if direction is not None: m.direction = direction if rotation is not None: m.rotation = rotation # If necessary, use flat shading if N < 8 or M < 8: m.faceShading = "flat" # Adjust axes if axesAdjust: if axes.daspectAuto is None: axes.daspectAuto = False axes.cameraType = "3d" axes.SetLimits() # Done axes.Draw() return m if __name__ == "__main__": m1 = vv.solidRing((0, 0, 1), N=64, M=4, thickness=0.5) m2 = vv.solidRing((0, 0, 2), N=64, thickness=0.25) m1.SetTexture(vv.imread("lena.png"))
# Get images im1 = self._p1.get_scale(sigma) im2 = self._p2.get_scale(sigma) im3 = self._p3.get_scale(sigma) # Replace textures self._t1.SetData(im1) self._t2.SetData(im2) self._t3.SetData(im3) if __name__ == '__main__': import visvis as vv # Read image im = vv.imread('astronaut.png')[:, :, 1].astype(np.float32) im = Aarray(im)[::2, :] d = Demo2D3(im, 1.5) vv.use().Run() if 0: ## Diffusionkernel vs Gaussiankernel import pirt import visvis as vv sigma = 300 k1, t1 = pirt.diffusionkernel(sigma, returnt=True) k2, t2 = pirt.gaussiankernel(sigma, returnt=True)
m.scaling = scaling if direction is not None: m.direction = direction if rotation is not None: m.rotation = rotation # If necessary, use flat shading if N < 8 or M < 8: m.faceShading = 'flat' # Adjust axes if axesAdjust: if axes.daspectAuto is None: axes.daspectAuto = False axes.cameraType = '3d' axes.SetLimits() # Done axes.Draw() return m if __name__ == '__main__': import visvis as vv vv.figure() # Create rings m1 = solidRing((0, 0, 1), M=4) m2 = solidRing((0, 0, 2)) im = vv.imread('lena.png') m1.SetTexture(im)
cmd, val = arg.lower().split(' ') if cmd == '-a': absT = int(val) if cmd == '-r': relT = float(val) if cmd == '-t': resolution = int(val) if resolution is None: resolution = 128 supportedImageFormats = ['.jpg', '.png'] supportedMeshFormats = ['.stl', '.ply', '.off', '.obj'] ext = os.path.splitext(fileName)[-1] if ext.lower() in supportedImageFormats: im = vv.imread(fileName) imgArray = imToGS(im) if absT is None: absT = 5 * max(imgArray.shape) / 100 relT = 0.5 T = (np.max(imgArray) + np.min(imgArray))/2 imgArrayT = (imgArray < T).astype(np.uint8) vv.figure() ax1 = vv.subplot(121) ax2 = vv.subplot(122) t1 = vv.imshow(im, axes=ax1) t2 = vv.imshow(imgArray, axes=ax2) app = vv.use() app.Run() P = mcTSystem()
#!/usr/bin/env python import visvis as vv app = vv.use() # Get green channel of lena image im = vv.imread('lena.png')[:,:,1] # Make 4 subplots with different colormaps cmaps = [vv.CM_GRAY, vv.CM_JET, vv.CM_SUMMER, vv.CM_HOT] for i in range(4): a = vv.subplot(2,2,i+1) t = vv.imshow(im, clim=(0,255)) a.axis.visible = 0 t.colormap = cmaps[i] vv.colorbar() app.Run()
# Copyright (C) 2012, Almar Klein # # Visvis is distributed under the terms of the (new) BSD License. # The full license can be found in 'license.txt'. import visvis as vv def colorbar(axes=None): """ colorbar(axes=None) Attach a colorbar to the given axes (or the current axes if not given). The reference to the colorbar instance is returned. Also see the vv.ColormapEditor wibject. """ if axes is None: axes = vv.gca() return vv.Colorbar(axes) if __name__ == "__main__": # Create and show grayscale image, using a colormap im = vv.imread("lena.png")[:, :, 0] t = vv.imshow(im) t.colormap = vv.CM_COPPER # Show how the values map to colors vv.colorbar()