def loadNumpy(inobj): import numpy as np if isinstance(inobj, str): data = np.load(inobj, allow_pickle=True, encoding='latin1').flatten()[0] else: data = inobj def loadcommon(obj, d): keys = d.keys() if 'time' in keys: obj.time(d['time']) if 'transform' in keys and len(d['transform']) == 4: vm = vtk.vtkMatrix4x4() for i in [0, 1, 2, 3]: for j in [0, 1, 2, 3]: vm.SetElement(i, j, d['transform'][i,j]) obj.setTransform(vm) elif 'position' in keys: obj.pos(d['position']) if hasattr(obj, 'GetProperty'): prp = obj.GetProperty() if 'ambient' in keys: prp.SetAmbient(d['ambient']) if 'diffuse' in keys: prp.SetDiffuse(d['diffuse']) ################## def _buildactor(d): vertices = d['points'] cells = None lines = None keys = d.keys() if 'cells' in keys: cells = d['cells'] if 'lines' in keys: lines = d['lines'] poly = utils.buildPolyData(vertices, cells, lines) act = Actor(poly) loadcommon(act, d) act.mapper.ScalarVisibilityOff() if 'celldata' in keys: for csc, cscname in d['celldata']: act.addCellScalars(csc, cscname) if not 'normal' in cscname.lower(): act.scalars(cscname) # activate if 'pointdata' in keys: for psc, pscname in d['pointdata']: act.addPointScalars(psc, pscname) if not 'normal' in pscname.lower(): act.scalars(pscname) # activate prp = act.GetProperty() if 'specular' in keys: prp.SetSpecular(d['specular']) if 'specularpower' in keys: prp.SetSpecularPower(d['specularpower']) if 'specularcolor' in keys: prp.SetSpecularColor(d['specularcolor']) if 'shading' in keys: prp.SetInterpolation(d['shading']) if 'alpha' in keys: prp.SetOpacity(d['alpha']) if 'opacity' in keys: prp.SetOpacity(d['opacity']) # synomym if 'pointsize' in keys and d['pointsize']: prp.SetPointSize(d['pointsize']) if 'texture' in keys and d['texture']: act.texture(d['texture']) if 'linewidth' in keys and d['linewidth']: act.lineWidth(d['linewidth']) if 'linecolor' in keys and d['linecolor']: act.lineColor(d['linecolor']) if 'representation' in keys: prp.SetRepresentation(d['representation']) if 'color' in keys and d['color']: act.color(d['color']) if 'backColor' in keys and d['backColor']: act.backColor(d['backColor']) if 'activedata' in keys and d['activedata'] is not None: act.mapper.ScalarVisibilityOn() if d['activedata'][0] == 'celldata': poly.GetCellData().SetActiveScalars(d['activedata'][1]) if d['activedata'][0] == 'pointdata': poly.GetPointData().SetActiveScalars(d['activedata'][1]) return act ################## objs = [] for d in data: #print('loadNumpy type is:', d['type']) if 'mesh' == d['type']: objs.append(_buildactor(d)) elif 'assembly' == d['type']: assacts = [] for ad in d['actors']: assacts.append(_buildactor(ad)) asse = Assembly(assacts) loadcommon(asse, d) objs.append(asse) elif 'image' == d['type']: shp = d['shape'][1], d['shape'][0] arr0 = d['array'] rcv = arr0[:,0].reshape(shp) gcv = arr0[:,1].reshape(shp) bcv = arr0[:,2].reshape(shp) arr = np.array([rcv, gcv, bcv]) arr = np.swapaxes(arr, 0, 2) vimg = Picture(arr) loadcommon(vimg, d) objs.append(vimg) elif 'volume' == d['type']: vol = Volume(d['array']) loadcommon(vol, d) vol.jittering(d['jittering']) vol.mode(d['mode']) vol.color(d['color']) vol.alpha(d['alpha']) vol.alphaGradient(d['alphagrad']) objs.append(vol) if len(objs) == 1: return objs[0] elif len(objs) == 0: return None else: return objs
def _load_file(filename, c, alpha, threshold, spacing, unpack): fl = filename.lower() ################################################################# other formats: if fl.endswith(".xml") or fl.endswith(".xml.gz") or fl.endswith(".xdmf"): # Fenics tetrahedral file actor = loadDolfin(filename) elif fl.endswith(".neutral") or fl.endswith(".neu"): # neutral tetrahedral file actor = loadNeutral(filename) elif fl.endswith(".gmsh"): # gmesh file actor = loadGmesh(filename) elif fl.endswith(".pcd"): # PCL point-cloud format actor = loadPCD(filename) actor.GetProperty().SetPointSize(2) elif fl.endswith(".off"): actor = loadOFF(filename) elif fl.endswith(".3ds"): # 3ds format actor = load3DS(filename) elif fl.endswith(".wrl"): importer = vtk.vtkVRMLImporter() importer.SetFileName(filename) importer.Read() importer.Update() actors = importer.GetRenderer().GetActors() #vtkActorCollection actors.InitTraversal() wacts = [] for i in range(actors.GetNumberOfItems()): act = actors.GetNextActor() wacts.append(act) actor = Assembly(wacts) ################################################################# volumetric: elif fl.endswith(".tif") or fl.endswith(".slc") or fl.endswith(".vti") \ or fl.endswith(".mhd") or fl.endswith(".nrrd") or fl.endswith(".nii") \ or fl.endswith(".dem"): img = loadImageData(filename, spacing) if threshold is False: if c is None and alpha == 1: c = ['b','lb','lg','y','r'] # good for blackboard background alpha = (0.0, 0.0, 0.2, 0.4, 0.8, 1) actor = Volume(img, c, alpha) else: actor = Volume(img).isosurface(threshold=threshold) actor.color(c).alpha(alpha) ################################################################# 2D images: elif fl.endswith(".png") or fl.endswith(".jpg") or fl.endswith(".bmp") or fl.endswith(".jpeg"): if ".png" in fl: picr = vtk.vtkPNGReader() elif ".jpg" in fl or ".jpeg" in fl: picr = vtk.vtkJPEGReader() elif ".bmp" in fl: picr = vtk.vtkBMPReader() picr.SetFileName(filename) picr.Update() actor = Picture() # object derived from vtk.vtkImageActor() actor.SetInputData(picr.GetOutput()) if alpha is None: alpha = 1 actor.SetOpacity(alpha) ################################################################# multiblock: elif fl.endswith(".vtm") or fl.endswith(".vtmb"): read = vtk.vtkXMLMultiBlockDataReader() read.SetFileName(filename) read.Update() mb = read.GetOutput() if unpack: acts = [] for i in range(mb.GetNumberOfBlocks()): b = mb.GetBlock(i) if isinstance(b, (vtk.vtkPolyData, vtk.vtkImageData, vtk.vtkUnstructuredGrid, vtk.vtkStructuredGrid, vtk.vtkRectilinearGrid)): acts.append(b) return acts else: return mb ################################################################# numpy: elif fl.endswith(".npy"): acts = loadNumpy(filename) if unpack == False: return Assembly(acts) return acts elif fl.endswith(".geojson") or fl.endswith(".geojson.gz"): return loadGeoJSON(fl) ################################################################# polygonal mesh: else: if fl.endswith(".vtk"): # read all legacy vtk types #output can be: # PolyData, StructuredGrid, StructuredPoints, UnstructuredGrid, RectilinearGrid reader = vtk.vtkDataSetReader() reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.ReadAllFieldsOn() reader.ReadAllNormalsOn() reader.ReadAllColorScalarsOn() elif fl.endswith(".ply"): reader = vtk.vtkPLYReader() elif fl.endswith(".obj"): reader = vtk.vtkOBJReader() elif fl.endswith(".stl"): reader = vtk.vtkSTLReader() elif fl.endswith(".byu") or fl.endswith(".g"): reader = vtk.vtkBYUReader() elif fl.endswith(".foam"): # OpenFoam reader = vtk.vtkOpenFOAMReader() elif fl.endswith(".pvd"): reader = vtk.vtkXMLGenericDataObjectReader() elif fl.endswith(".vtp"): reader = vtk.vtkXMLPolyDataReader() elif fl.endswith(".vts"): reader = vtk.vtkXMLStructuredGridReader() elif fl.endswith(".vtu"): reader = vtk.vtkXMLUnstructuredGridReader() elif fl.endswith(".vtr"): reader = vtk.vtkXMLRectilinearGridReader() elif fl.endswith(".pvtk"): reader = vtk.vtkPDataSetReader() elif fl.endswith(".pvtr"): reader = vtk.vtkXMLPRectilinearGridReader() elif fl.endswith("pvtu"): reader = vtk.vtkXMLPUnstructuredGridReader() elif fl.endswith(".txt") or fl.endswith(".xyz"): reader = vtk.vtkParticleReader() # (format is x, y, z, scalar) elif fl.endswith(".facet"): reader = vtk.vtkFacetReader() else: return None reader.SetFileName(filename) reader.Update() routput = reader.GetOutput() if not routput: colors.printc("~noentry Unable to load", filename, c=1) return None actor = Actor(routput, c, alpha) if fl.endswith(".txt") or fl.endswith(".xyz"): actor.GetProperty().SetPointSize(4) actor.filename = filename return actor
def load(inputobj, c=None, alpha=1, threshold=False, spacing=(), unpack=True): """ Load ``Actor`` and ``Volume`` from file. The output will depend on the file extension. See examples below. :param c: color in RGB format, hex, symbol or name :param alpha: transparency/opacity of the polygonal data. For volumetric data `(tiff, slc, vti etc..)`: :param list c: can be a list of any length of colors. This list represents the color transfer function values equally spaced along the range of the volumetric scalar. :param list alpha: can be a list of any length of tranparencies. This list represents the transparency transfer function values equally spaced along the range of the volumetric scalar. :param float threshold: value to draw the isosurface, False by default to return a ``Volume``. If set to True will return an ``Actor`` with automatic choice of the isosurfacing threshold. :param list spacing: specify the voxel spacing in the three dimensions :param bool unpack: only for multiblock data, if True returns a flat list of objects. :Examples: .. code-block:: python from vtkplotter import datadir, load, show # Return an Actor g = load(datadir+'250.vtk') show(g) # Return a list of 2 Actors g = load([datadir+'250.vtk', datadir+'270.vtk']) show(g) # Return a list of actors by reading all files in a directory # (if directory contains DICOM files then a Volume is returned) g = load(datadir+'timecourse1d/') show(g) # Return a Volume. Color/Opacity transfer functions can be specified too. g = load(datadir+'embryo.slc') g.c(['y','lb','w']).alpha((0.0, 0.4, 0.9, 1)) show(g) # Return an Actor from a SLC volume with automatic thresholding g = load(datadir+'embryo.slc', threshold=True) show(g) """ acts = [] if utils.isSequence(inputobj): flist = inputobj else: import glob flist = sorted(glob.glob(inputobj)) for fod in flist: if os.path.isfile(fod): ### it's a file a = _load_file(fod, c, alpha, threshold, spacing, unpack) acts.append(a) elif os.path.isdir(fod):### it's a directory or DICOM flist = os.listdir(fod) if '.dcm' in flist[0]: ### it's DICOM reader = vtk.vtkDICOMImageReader() reader.SetDirectoryName(fod) reader.Update() image = reader.GetOutput() if len(spacing) == 3: image.SetSpacing(spacing[0], spacing[1], spacing[2]) if threshold is False: if c is None and alpha == 1: c = ['b','lb','lg','y','r'] # good for blackboard background alpha = (0.0, 0.0, 0.2, 0.4, 0.8, 1) #c = ['lb','db','dg','dr'] # good for white backgr #alpha = (0.0, 0.0, 0.2, 0.6, 0.8, 1) actor = Volume(image, c, alpha) else: actor = Volume(image).isosurface(threshold=threshold) actor.color(c).alpha(alpha) acts.append(actor) else: ### it's a normal directory utils.humansort(flist) for ifile in flist: a = _load_file(fod+'/'+ifile, c, alpha, threshold, spacing, unpack) acts.append(a) else: colors.printc("~times Error in load(): cannot find", fod, c=1) if len(acts) == 1: if not acts[0]: colors.printc("~times Error in load(): cannot load", inputobj, c=1) settings.collectable_actors.append(acts[0]) return acts[0] elif len(acts) == 0: colors.printc("~times Error in load(): cannot load", inputobj, c=1) return None else: settings.collectable_actors += acts return acts
# Perform other simple mathematical operation between 3d images. # Possible operations are: +, -, /, 1/x, sin, cos, exp, log, abs, **2, sqrt, # min, max, atan, atan2, median, mag, dot, gradient, divergence, laplacian. # Alphas defines the opacity transfer function in the scalar range. # from vtkplotter import Plotter, vtkio from vtkplotter.analysis import imageOperation from vtkplotter.actors import Volume vp = Plotter(N=8, axes=4) img0 = vtkio.loadImageData('data/embryo.slc') # vtkImageData object v0 = Volume(img0, c=0) # build a vtk.vtkVolume derived object vp.show(v0, at=0) img1 = imageOperation(img0, 'gradient') img1 = imageOperation(img1, '+', 92.0) v1 = Volume(img1, c=1, alphas=[0, 1, 0, 0, 0]) vp.show(v1, at=1) img2 = imageOperation(img0, 'divergence') v2 = Volume(img2, c=2) vp.show(v2, at=2) img3 = imageOperation(img0, 'laplacian') v3 = Volume(img3, c=3, alphas=[0, 1, 0, 0, 1]) vp.show(v3, at=3) img4 = imageOperation(img0, 'median') v4 = Volume(img4, c=4) vp.show(v4, at=4)
scals = np.abs(coords[:, 2]) # let the scalar be the z of point itself fact = 1. / (bins - 1) # conversion factor btw the 2 ranges vp = Plotter(verbose=0) vp.ztitle = 'z == scalar value' cloud = vp.points(coords) # fill the vtkImageData object pb = ProgressBar(0, bins, c=4) for iz in pb.range(): pb.print() for iy in range(bins): for ix in range(bins): pt = vector(ix, iy, iz) * fact closestPointsIDs = cloud.closestPoint(pt, N=5, returnIds=True) num, den = 0, 0 for i in closestPointsIDs: # work out RBF manually on N points invdist = 1 / (mag2(coords[i] - pt) + 1e-06) num += scals[i] * invdist den += invdist img.SetScalarComponentFromFloat(ix, iy, iz, 0, num / den) #vp.write(img, 'imgcube.tif') # or .vti # set colors and transparencies along the scalar range vol = Volume(img, c=['r', 'g', 'b'], alphas=[0.4, 0.8]) #vtkVolume act = vp.points(coords / fact) vp.show([vol, act], viewup='z')
# Work with vtkVolume objects and surfaces. # from vtkplotter import vtkio, Plotter from vtkplotter.actors import Volume vp = Plotter() # Load a 3D voxel dataset (returns a vtkImageData object): img = vtkio.loadImageData('data/embryo.slc', spacing=[1, 1, 1]) # Build a vtkVolume object. # A set of transparency values - of any length - can be passed # to define the opacity transfer function in the range of the scalar. # E.g.: setting alphas=[0, 0, 0, 1, 0, 0, 0] would make visible # only voxels with value close to 98.5 (see print output). vol = Volume(img, c='green', alphas=[0, 0.4, 0.9, 1]) # vtkVolume # can relocate volume in space: #vol.scale(0.3).pos([10,100,0]).rotate(90, axis=[0,1,1]) sph = vp.sphere(pos=[100, 100, 100], r=20) # add a dummy surface vp.show([vol, sph], zoom=1.4) # show both vtkVolume and vtkActor
def scan(wannabeacts): scannedacts = [] if not utils.isSequence(wannabeacts): wannabeacts = [wannabeacts] for a in wannabeacts: # scan content of list if isinstance(a, vtk.vtkActor): scannedacts.append(a) if hasattr(a, 'trail' ) and a.trail and not a.trail in self.actors: scannedacts.append(a.trail) elif isinstance(a, vtk.vtkAssembly): scannedacts.append(a) if a.trail and not a.trail in self.actors: scannedacts.append(a.trail) elif isinstance(a, vtk.vtkActor2D): if isinstance(a, vtk.vtkCornerAnnotation): for a2 in settings.collectable_actors: if isinstance(a2, vtk.vtkCornerAnnotation): if at in a2.renderedAt: # remove old message self.removeActor(a2) scannedacts.append(a) elif isinstance(a, vtk.vtkImageActor): scannedacts.append(a) elif isinstance(a, vtk.vtkVolume): scannedacts.append(a) elif isinstance(a, vtk.vtkImageData): scannedacts.append(Volume(a)) elif isinstance(a, vtk.vtkPolyData): scannedacts.append(Actor(a, c, alpha, wire, bc)) elif isinstance(a, str): # assume a filepath was given out = vtkio.load(a, c, alpha, wire, bc) if isinstance(out, str): colors.printc("~times File not found:", out, c=1) scannedacts.append(None) else: scannedacts.append(out) elif "dolfin" in str(type(a)): # assume a dolfin.Mesh object from vtkplotter.dolfin import MeshActor out = MeshActor(a, c=c, alpha=alpha, wire=True, bc=bc) scannedacts.append(out) elif a is None: pass elif isinstance(a, vtk.vtkUnstructuredGrid): gf = vtk.vtkGeometryFilter() gf.SetInputData(a) gf.Update() scannedacts.append( Actor(gf.GetOutput(), c, alpha, wire, bc)) elif isinstance(a, vtk.vtkStructuredGrid): gf = vtk.vtkGeometryFilter() gf.SetInputData(a) gf.Update() scannedacts.append( Actor(gf.GetOutput(), c, alpha, wire, bc)) elif isinstance(a, vtk.vtkRectilinearGrid): gf = vtk.vtkRectilinearGridGeometryFilter() gf.SetInputData(a) gf.Update() scannedacts.append( Actor(gf.GetOutput(), c, alpha, wire, bc)) elif isinstance(a, vtk.vtkMultiBlockDataSet): for i in range(a.GetNumberOfBlocks()): b = a.GetBlock(i) if isinstance(b, vtk.vtkPolyData): scannedacts.append(Actor(b, c, alpha, wire, bc)) elif isinstance(b, vtk.vtkImageData): scannedacts.append(Volume(b)) else: colors.printc("~!? Cannot understand input in show():", type(a), c=1) scannedacts.append(None) return scannedacts
# Using normal vtk commands to load a xml vti file # then use vtkplotter to show the resulting 3d image. # import vtk # Create the reader for the data. reader = vtk.vtkXMLImageDataReader() reader.SetFileName('data/vase.vti') reader.Update() img = reader.GetOutput() # specify the data array in the file to process #img.GetPointData().SetActiveAttribute('SLCImage', 0) ################################# from vtkplotter.actors import Volume # can set colors and transparencies along the scalar range vol = Volume(img, c=['gray', 'fuchsia', 'dg', (0, 0, 1)], alphas=[0.1, 0.2, 0.3, 0.8]) from vtkplotter import load, show # load command returns an isosurface (vtkActor) of the 3d image iso = load('data/vase.vti', threshold=140).wire(True).alpha(0.1) # show command creates and returns an instance of class Plotter show([vol, iso])