def __init__(self, ref_particles, test_particles, particle_type=None): self._test_particles = test_particles self._ref_particles = ref_particles self._orientation_vec = None self._ref_locator = vtk.vtkPointLocator() self._ref_locator.SetDataSet(self._ref_particles) self._ref_locator.BuildLocator() self._test_locator = vtk.vtkPointLocator() self._test_locator.SetDataSet(self._test_particles) self._test_locator.BuildLocator() self._dist_thresh = None self._angle_thresh = None self._scale_fraction_thresh = None if particle_type is not None: assert particle_type == 'vessel' or particle_type == 'airway' or \ particle_type == 'fissure', "Unrecognized particle type" if particle_type is 'vessel': self._orientation_vec = 'hevec0' elif particle_type is 'airway': self._orientation_vec = 'hevec2' else: self._orientation_vec = 'hevec1' else: raise ValueError('Must specify a particle type') self._initialize_thresholds()
def projectPoints(self, sourceMesh, targetMesh, originalPoints, projectedPoints, rayLength): sourcePolydata = sourceMesh.GetPolyData() targetPolydata = targetMesh.GetPolyData() #set up locater for intersection with normal vector rays obbTree = vtk.vtkOBBTree() obbTree.SetDataSet(targetPolydata) obbTree.BuildLocator() #set up point locator for finding surface normals and closest point pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(sourcePolydata) pointLocator.BuildLocator() targetPointLocator = vtk.vtkPointLocator() targetPointLocator.SetDataSet(targetPolydata) targetPointLocator.BuildLocator() #get surface normal from each landmark point rayDirection=[0,0,0] normalArray = sourcePolydata.GetPointData().GetArray("Normals") if(not normalArray): normalFilter=vtk.vtkPolyDataNormals() normalFilter.ComputePointNormalsOn() normalFilter.SetInputData(sourcePolydata) normalFilter.Update() normalArray = normalFilter.GetOutput().GetPointData().GetArray("Normals") if(not normalArray): print("Error: no normal array") for index in range(originalPoints.GetNumberOfMarkups()): originalPoint=[0,0,0] originalPoints.GetMarkupPoint(0,index,originalPoint) # get ray direction from closest normal closestPointId = pointLocator.FindClosestPoint(originalPoint) rayDirection = normalArray.GetTuple(closestPointId) rayEndPoint=[0,0,0] for dim in range(len(rayEndPoint)): rayEndPoint[dim] = originalPoint[dim] + rayDirection[dim]* rayLength intersectionIds=vtk.vtkIdList() intersectionPoints=vtk.vtkPoints() obbTree.IntersectWithLine(originalPoint,rayEndPoint,intersectionPoints,intersectionIds) #if there are intersections, update the point to most external one. if intersectionPoints.GetNumberOfPoints() > 0: exteriorPoint = intersectionPoints.GetPoint(intersectionPoints.GetNumberOfPoints()-1) projectedPoints.AddFiducialFromArray(exteriorPoint) #if there are no intersections, reverse the normal vector else: for dim in range(len(rayEndPoint)): rayEndPoint[dim] = originalPoint[dim] + rayDirection[dim]* -rayLength obbTree.IntersectWithLine(originalPoint,rayEndPoint,intersectionPoints,intersectionIds) if intersectionPoints.GetNumberOfPoints()>0: exteriorPoint = intersectionPoints.GetPoint(0) projectedPoints.AddFiducialFromArray(exteriorPoint) #if none in reverse direction, use closest mesh point else: closestPointId = targetPointLocator.FindClosestPoint(originalPoint) rayOrigin = targetPolydata.GetPoint(closestPointId) projectedPoints.AddFiducialFromArray(rayOrigin) return True
def ExtractPatchesIds(parentCl, clipPts): clipIds = [] numberOfPoints = 0 if (clipPts.GetNumberOfPoints() == 2): upstreamPoint = clipPts.GetPoint(0) downstreamPoint = clipPts.GetPoint(1) for j in range(parentCl.GetNumberOfCells()): cellLine = ExtractSingleLine(parentCl, j) locator = vtk.vtkPointLocator() locator.SetDataSet(cellLine) locator.BuildLocator() upstreamId = locator.FindClosestPoint(upstreamPoint) downstreamId = locator.FindClosestPoint(downstreamPoint) if j == 0: clipIds.append(upstreamId) clipIds.append(downstreamId) numberOfPoints += upstreamId + 1 numberOfPoints += cellLine.GetNumberOfPoints() - downstreamId else: clipIds.append(downstreamId) numberOfPoints += cellLine.GetNumberOfPoints() - downstreamId if (clipPts.GetNumberOfPoints() == 3): commonPoint = clipPts.GetPoint(0) dau1Point = clipPts.GetPoint(1) dau2Point = clipPts.GetPoint(2) for j in range(parentCl.GetNumberOfCells()): cellLine = ExtractSingleLine(parentCl, j) locator = vtk.vtkPointLocator() locator.SetDataSet(cellLine) locator.BuildLocator() if j == 0: upstreamId = locator.FindClosestPoint(commonPoint) downstreamId = locator.FindClosestPoint(dau1Point) clipIds.append(upstreamId) clipIds.append(downstreamId) numberOfPoints += upstreamId + 1 numberOfPoints += cellLine.GetNumberOfPoints() - downstreamId else: downstreamId = locator.FindClosestPoint(dau2Point) clipIds.append(downstreamId) numberOfPoints += cellLine.GetNumberOfPoints() - downstreamId return clipIds, numberOfPoints
def ExtractPatchesIds(parentCl,clipPts): clipIds = [] numberOfPoints = 0 if (clipPts.GetNumberOfPoints() == 2): upstreamPoint = clipPts.GetPoint(0) downstreamPoint = clipPts.GetPoint(1) for j in range(parentCl.GetNumberOfCells()): cellLine = ExtractSingleLine(parentCl,j) locator = vtk.vtkPointLocator() locator.SetDataSet(cellLine) locator.BuildLocator() upstreamId = locator.FindClosestPoint(upstreamPoint) downstreamId = locator.FindClosestPoint(downstreamPoint) if j==0: clipIds.append(upstreamId) clipIds.append(downstreamId) numberOfPoints += upstreamId+1 numberOfPoints += cellLine.GetNumberOfPoints()-downstreamId else: clipIds.append(downstreamId) numberOfPoints += cellLine.GetNumberOfPoints()-downstreamId if (clipPts.GetNumberOfPoints() == 3): commonPoint = clipPts.GetPoint(0) dau1Point = clipPts.GetPoint(1) dau2Point = clipPts.GetPoint(2) for j in range(parentCl.GetNumberOfCells()): cellLine = ExtractSingleLine(parentCl,j) locator = vtk.vtkPointLocator() locator.SetDataSet(cellLine) locator.BuildLocator() if j==0: upstreamId = locator.FindClosestPoint(commonPoint) downstreamId = locator.FindClosestPoint(dau1Point) clipIds.append(upstreamId) clipIds.append(downstreamId) numberOfPoints += upstreamId+1 numberOfPoints += cellLine.GetNumberOfPoints()-downstreamId else: downstreamId = locator.FindClosestPoint(dau2Point) clipIds.append(downstreamId) numberOfPoints += cellLine.GetNumberOfPoints()-downstreamId return clipIds,numberOfPoints
def ProbeData(self, coordinates, name): """Interpolate field values at these coordinates.""" # Initialise locator locator = vtk.vtkPointLocator() locator.SetDataSet(self.ugrid) locator.SetTolerance(10.0) locator.Update() # Initialise probe points = vtk.vtkPoints() points.SetDataTypeToDouble() ilen, jlen = coordinates.shape for i in range(ilen): points.InsertNextPoint(coordinates[i][0], coordinates[i][1], coordinates[i][2]) polydata = vtk.vtkPolyData() polydata.SetPoints(points) probe = vtk.vtkProbeFilter() probe.SetInput(polydata) probe.SetSource(self.ugrid) probe.Update() # Generate a list invalidNodes, containing a map from invalid nodes in the # result to their closest nodes in the input valid_ids = probe.GetValidPoints() valid_loc = 0 invalidNodes = [] for i in range(ilen): if valid_ids.GetTuple1(valid_loc) == i: valid_loc += 1 else: nearest = locator.FindClosestPoint([coordinates[i][0], coordinates[i][1], coordinates[i][2]]) invalidNodes.append((i, nearest)) # Get final updated values pointdata=probe.GetOutput().GetPointData() vtkdata=pointdata.GetArray(name) nc=vtkdata.GetNumberOfComponents() nt=vtkdata.GetNumberOfTuples() array = arr([vtkdata.GetValue(i) for i in range(nt * nc)]) # Fix the point data at invalid nodes if len(invalidNodes) > 0: try: oldField = self.ugrid.GetPointData().GetArray(name) components = oldField.GetNumberOfComponents() except: try: oldField = self.ugrid.GetCellData().GetArray(name) components = oldField.GetNumberOfComponents() except: raise Exception("ERROR: couldn't find point or cell field data with name "+name+" in file "+self.filename+".") for invalidNode, nearest in invalidNodes: for comp in range(nc): array[invalidNode * nc + comp] = oldField.GetValue(nearest * nc + comp) valShape = self.GetField(name)[0].shape array.shape = tuple([nt] + list(valShape)) return array
def stitchEdges(self, input, curve1, curve2): locator = vtk.vtkPointLocator() locator.SetDataSet(input) locator.BuildLocator() output = vtk.vtkPolyData() output.DeepCopy(input) polys = output.GetPolys() for i in range(curve1.GetNumberOfPoints() - 1): p1A = locator.FindClosestPoint(curve1.GetPoint(i)) p1B = locator.FindClosestPoint(curve1.GetPoint(i + 1)) p2A = locator.FindClosestPoint(curve2.GetPoint(i)) p2B = locator.FindClosestPoint(curve2.GetPoint(i + 1)) triangle1 = vtk.vtkIdList() triangle1.InsertNextId(p1A) triangle1.InsertNextId(p1B) triangle1.InsertNextId(p2A) polys.InsertNextCell(triangle1) triangle2 = vtk.vtkIdList() triangle2.InsertNextId(p1B) triangle2.InsertNextId(p2B) triangle2.InsertNextId(p2A) polys.InsertNextCell(triangle2) return output
def __init__(self, ugrid, coordinates): # Initialise locator locator = vtk.vtkPointLocator() locator.SetDataSet(ugrid) locator.SetTolerance(10.0) locator.Update() # Initialise probe points = vtk.vtkPoints() points.SetDataTypeToDouble() ilen, jlen = coordinates.shape for i in range(ilen): points.InsertNextPoint(coordinates[i][0], coordinates[i][1], coordinates[i][2]) polydata = vtk.vtkPolyData() polydata.SetPoints(points) self.probe = vtk.vtkProbeFilter() self.probe.SetInput(polydata) self.probe.SetSource(ugrid) self.probe.Update() # Generate a list invalidNodes, containing a map from invalid nodes in the # result to their closest nodes in the input valid_ids = self.probe.GetValidPoints() valid_loc = 0 self.invalidNodes = [] for i in range(ilen): if valid_ids.GetTuple1(valid_loc) == i: valid_loc += 1 else: nearest = locator.FindClosestPoint([coordinates[i][0], coordinates[i][1], coordinates[i][2]]) self.invalidNodes.append((i, nearest)) self.ugrid = ugrid
def __init__(self, target_mesh): self.point_locator = vtk.vtkPointLocator() self.point_locator.SetDataSet(target_mesh) self.point_locator.BuildLocator() self.cell_locator = vtk.vtkCellLocator() self.cell_locator.SetDataSet(target_mesh) self.cell_locator.SetTolerance(0.0001) self.cell_locator.BuildLocator() edge_filter = vtk.vtkFeatureEdges() edge_filter.SetInputData(target_mesh) edge_filter.BoundaryEdgesOn() edge_filter.FeatureEdgesOn() edge_filter.SetFeatureAngle(90) edge_filter.ManifoldEdgesOff() edge_filter.NonManifoldEdgesOff() edge_filter.Update() edge_points = edge_filter.GetOutput().GetPoints() self.edge_point_ids = [] for i in range(edge_points.GetNumberOfPoints()): point_id = self.point_locator.FindClosestPoint( edge_points.GetPoint(i)) self.edge_point_ids.append(point_id)
def __init__(self, number_of_cells_per_side_=1, unit_cell_size_=200): molar.pdb.Pdb.__init__(self) self.surface_density = SURFACE_DENSITY self.step_num = int(32) self.marching_cubes = vtk.vtkMarchingCubes() self.poly_data = vtk.vtkPolyData() self.data = vtk.vtkDataObject() self.unit_cell_size = unit_cell_size_ self.form = "G" self.number_of_cells_per_side = number_of_cells_per_side_ self.cerebroside = False self.Update() self.units = [] self.units_transed = [] self.points = vtk.vtkPoints() #for visualization self.attempt = 0 self.collisioncounter = 0 self.total_area = 0 self.total_pair = 0 for f in FILES: self.units.append(molar.pdb.Pdb()) self.units[-1].ReadFile(PATH + f) for f in FILES: self.units_transed.append(molar.pdb.Pdb()) self.units_transed[-1].ReadFile(PATH + f) self.units_transed[-1].RotateX(180) self.pointlocator = vtk.vtkPointLocator() self.pointlocator.Initialize() self.pointlocator.SetDataSet(vtk.vtkPolyData()) self.pointlocator.InitPointInsertion( vtk.vtkPoints(), [0, unit_cell_size_, 0, unit_cell_size_, 0, unit_cell_size_])
def ProbeData(self, coordinates, name): """Interpolate field values at these coordinates.""" # Initialise locator locator = vtk.vtkPointLocator() locator.SetDataSet(self.ugrid) locator.SetTolerance(10.0) locator.Update() # Initialise probe points = vtk.vtkPoints() points.SetDataTypeToDouble() ilen, jlen = coordinates.shape for i in range(ilen): points.InsertNextPoint(coordinates[i][0], coordinates[i][1], coordinates[i][2]) polydata = vtk.vtkPolyData() polydata.SetPoints(points) probe = vtk.vtkProbeFilter() probe.SetInputData(polydata) probe.setSourceData(self.ugrid) probe.Update() # Generate a list invalidNodes, containing a map from invalid nodes in the # result to their closest nodes in the input valid_ids = probe.GetValidPoints() valid_loc = 0 invalidNodes = [] for i in range(ilen): if valid_ids.GetTuple1(valid_loc) == i: valid_loc += 1 else: nearest = locator.FindClosestPoint([coordinates[i][0], coordinates[i][1], coordinates[i][2]]) invalidNodes.append((i, nearest)) # Get final updated values pointdata=probe.GetOutput().GetPointData() vtkdata=pointdata.GetArray(name) nc=vtkdata.GetNumberOfComponents() nt=vtkdata.GetNumberOfTuples() array = arr([vtkdata.GetValue(i) for i in range(nt * nc)]) # Fix the point data at invalid nodes if len(invalidNodes) > 0: try: oldField = self.ugrid.GetPointData().GetArray(name) components = oldField.GetNumberOfComponents() except: try: oldField = self.ugrid.GetCellData().GetArray(name) components = oldField.GetNumberOfComponents() except: raise Exception("ERROR: couldn't find point or cell field data with name "+name+" in file "+self.filename+".") for invalidNode, nearest in invalidNodes: for comp in range(nc): array[invalidNode * nc + comp] = oldField.GetValue(nearest * nc + comp) valShape = self.GetField(name)[0].shape array.shape = tuple([nt] + list(valShape)) return array
def test_point_in_locator(): """ Tests that point locator can find the nearest point in a bunch of polydata. """ locators = [] for x_ord in range(-5, 6, 5): for y_ord in range(-5, 6, 5): for z_ord in range(-5, 6, 5): model = VTKCylinderModel(1.0, 0.5, (1.0, 1.0, 1.0), "name", 0.0, (1.0, 0.0, 0.0), 88, True, 1.0) transform_vector = (1.0, 0.0, 0.0, float(x_ord), 0.0, 1.0, 0.0, float(y_ord), 0.0, 0.0, 1.0, float(z_ord), 0.0, 0.0, 0.0, 1.0) transform = vtk.vtkTransform() transform.SetMatrix(transform_vector) transform_filter = vtk.vtkTransformPolyDataFilter() transform_filter.SetTransform(transform) source_new = vtk.vtkPolyData() transform_filter.SetInputData(model.source) transform_filter.SetOutput(source_new) transform_filter.Update() locator = vtk.vtkPointLocator() locator.SetDataSet(source_new) locator.Update() locators.append(locator) point_in, distance = point_in_locator((0.0, 0.0, 0.0), locators, 7.0) assert point_in == 13 numpy.testing.assert_almost_equal(distance, 0.5, 6)
def openSurfaceAtPoint(self, polyData, seed): ''' Returns a new surface with an opening at the given seed. ''' someradius = 1.0 pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(polyData) pointLocator.BuildLocator() # find the closest point next to the seed on the surface # id = pointLocator.FindClosestPoint(int(seed[0]),int(seed[1]),int(seed[2])) id = pointLocator.FindClosestPoint(seed) # the seed is now guaranteed on the surface seed = polyData.GetPoint(id) sphere = vtk.vtkSphere() sphere.SetCenter(seed[0], seed[1], seed[2]) sphere.SetRadius(someradius) clip = vtk.vtkClipPolyData() clip.SetInputData(polyData) clip.SetClipFunction(sphere) clip.Update() outPolyData = vtk.vtkPolyData() outPolyData.DeepCopy(clip.GetOutput()) return outPolyData
def _the_callback(mesh, idx): if mesh is None: return point = mesh.points[idx] if self._last_picked_idx is None: self.picked_geodesic = pyvista.PolyData(point) else: surface = mesh.extract_surface().triangulate() locator = vtk.vtkPointLocator() locator.SetDataSet(surface) locator.BuildLocator() start_idx = locator.FindClosestPoint( mesh.points[self._last_picked_idx]) end_idx = locator.FindClosestPoint(point) self.picked_geodesic = self.picked_geodesic + surface.geodesic( start_idx, end_idx) self._last_picked_idx = idx self.add_mesh(self.picked_geodesic, color=color, name='_picked_path', line_width=line_width, point_size=point_size, reset_camera=False, **kwargs) if hasattr(callback, '__call__'): callback(self.picked_geodesic) return
def __init__(self, grid, valname, ts, tn, wghtpowval, pointset, shp_has_geo='False', XCOL='', YCOL='', ZCOL=''): self.cl, self.grid = grid.getGrid() self.valname = valname self.ts = ts self.tn = tn self.wghtpowval = wghtpowval self.rmax = self.ts if self.ts > self.tn else self.tn self.ptsfile = pointset self.gpdata = gpd.read_file(self.ptsfile) self.shp_has_geo = shp_has_geo self.xcol = XCOL self.ycol = YCOL self.zcol = ZCOL self.xpt = np.empty(0, dtype=np.double) self.ypt = np.empty(0, dtype=np.double) self.zpt = np.empty(0, dtype=np.double) self.numpts = 0 self.ptlocator = vtk.vtkPointLocator() self.interpval = np.empty(0, dtype=np.double) self.defval = 0 self.__initialize_pts()
def RemappedVtu(inputVtu, targetVtu): """ Remap (via probing) the input vtu onto the mesh of the target vtu """ coordinates = targetVtu.GetLocations() ### The following is lifted from vtu.ProbeData in tools/vtktools.py (with ### self -> inputVtu and invalid node remapping rather than repositioning) # Initialise locator locator = vtk.vtkPointLocator() locator.SetDataSet(inputVtu.ugrid) locator.SetTolerance(10.0) locator.Update() # Initialise probe points = vtk.vtkPoints() ilen, jlen = coordinates.shape for i in range(ilen): points.InsertNextPoint(coordinates[i][0], coordinates[i][1], coordinates[i][2]) polydata = vtk.vtkPolyData() polydata.SetPoints(points) probe = vtk.vtkProbeFilter() if vtk.vtkVersion.GetVTKMajorVersion() <= 5: probe.SetInput(polydata) probe.SetSource(inputVtu.ugrid) else: probe.SetInputData(polydata) probe.SetSourceData(inputVtu.ugrid) probe.Update() # Generate a list invalidNodes, containing a map from invalid nodes in the # result to their closest nodes in the input valid_ids = probe.GetValidPoints() valid_loc = 0 invalidNodes = [] for i in range(ilen): if valid_ids.GetTuple1(valid_loc) == i: valid_loc += 1 else: nearest = locator.FindClosestPoint([coordinates[i][0], coordinates[i][1], coordinates[i][2]]) invalidNodes.append((i, nearest)) ### End of code from vtktools.py # Construct output result = vtu() result.ugrid = PolyDataToUnstructuredGrid(probe.GetOutput()) # Add the cells result.ugrid.SetCells(targetVtu.ugrid.GetCellTypesArray(), targetVtu.ugrid.GetCellLocationsArray(), targetVtu.ugrid.GetCells()) # Fix the point data at invalid nodes if len(invalidNodes) > 0: for i in range(inputVtu.ugrid.GetPointData().GetNumberOfArrays()): oldField = inputVtu.ugrid.GetPointData().GetArray(i) newField = result.ugrid.GetPointData().GetArray(i) components = oldField.GetNumberOfComponents() for invalidNode, nearest in invalidNodes: for comp in range(components): newField.SetValue(invalidNode * components + comp, oldField.GetValue(nearest * components + comp)) return result
def DigestPdb(self): """ add atoms too self and 8 neighboring cubes. points except for water ### """ self.pdb_water_head = pdb.Pdb() ## used for visualizations self.pdb_water_head.AddMolecule() if self.pdb.cryst: self.cryst = self.pdb.cryst print "unit cell size: ", self.cryst else: print "Please provide the unit-cell size in self.cryst" num_atoms = self.pdb.NumOfAtoms() c = 0 self.points_periodic = vtk.vtkPoints() self.points = vtk.vtkPoints() print "Digesting the input pdb ..." for atom in self.pdb: if atom.name.replace(" ","") not in ["W","WF","ROH","H1","H2","H3"] and\ ( atom.GetMolNameGMX()[0]!="G" or atom.name.replace(" ","") not in ["C1","C2","C3"] ) : self.points.InsertNextPoint(atom.pos) for q in [-self.cryst[0], 0, self.cryst[0]]: for p in [-self.cryst[1], 0, self.cryst[1]]: for r in [-self.cryst[2], 0, self.cryst[2]]: pos_aux = atom.pos + np.array([q, p, r]) self.points_periodic.InsertNextPoint(pos_aux) self.pdb_water_head.molecules[-1].AddAtom(atom.line) c += 1 pdb.update_progress(float(c) / num_atoms) print "\n" self.polydata = vtk.vtkPolyData() self.polydata.SetPoints(self.points_periodic) ### initialize pointlocator ### self.pointlocator = vtk.vtkPointLocator() self.pointlocator.SetDataSet(self.polydata) self.pointlocator.SetNumberOfPointsPerBucket(10) self.pointlocator.BuildLocator()
def DigestGro(self): """ same as DigestPdb but for gro files """ self.Atom_Select() self.pdb_water_head = False self.cryst = self.univ.dimensions[0:3] num_atoms = len(self.selected_atoms) c = 0 self.points_periodic = vtk.vtkPoints() self.points = vtk.vtkPoints() print "Digesting the input gro ..." for atom in self.selected_atoms: self.points.InsertNextPoint(atom.position) for q in [-self.cryst[0], 0, self.cryst[0]]: for p in [-self.cryst[1], 0, self.cryst[1]]: for r in [-self.cryst[2], 0, self.cryst[2]]: pos_aux = atom.position + np.array([q, p, r]) self.points_periodic.InsertNextPoint(pos_aux) c += 1 pdb.update_progress(float(c) / num_atoms) print "\n" self.polydata = vtk.vtkPolyData() self.polydata.SetPoints(self.points_periodic) ### initialize pointlocator ### self.pointlocator = vtk.vtkPointLocator() self.pointlocator.SetDataSet(self.polydata) self.pointlocator.SetNumberOfPointsPerBucket(10) self.pointlocator.BuildLocator()
def smoothMLS1D(actor, f=0.2, showNLines=0): ''' Smooth actor or points with a Moving Least Squares variant. The list actor.variances contain the residue calculated for each point. Input actor's polydata is modified. f, smoothing factor - typical range s [0,2] showNLines, build an actor showing the fitting line for N random points ''' coords = vu.coordinates(actor) ncoords = len(coords) Ncp = int(ncoords * f / 10) nshow = int(ncoords) if showNLines: ndiv = int(nshow / showNLines) if Ncp < 3: vc.printc('Please choose a higher fraction than ' + str(f), 1) Ncp = 3 poly = vu.polydata(actor, True) vpts = poly.GetPoints() locator = vtk.vtkPointLocator() locator.SetDataSet(poly) locator.BuildLocator() vtklist = vtk.vtkIdList() variances, newline, acts = [], [], [] for i, p in enumerate(coords): locator.FindClosestNPoints(Ncp, p, vtklist) points = [] for j in range(vtklist.GetNumberOfIds()): trgp = [0, 0, 0] vpts.GetPoint(vtklist.GetId(j), trgp) points.append(trgp) if len(points) < 2: continue points = np.array(points) pointsmean = points.mean(axis=0) # plane center uu, dd, vv = np.linalg.svd(points - pointsmean) newp = np.dot(p - pointsmean, vv[0]) * vv[0] + pointsmean variances.append(dd[1] + dd[2]) newline.append(newp) if showNLines and not i % ndiv: fline = fitLine(points, lw=4, alpha=1) # fitting plane iapts = vs.points(points) # blue points acts += [fline, iapts] for i in range(ncoords): vpts.SetPoint(i, newline[i]) if showNLines: apts = vs.points(newline, c='r 0.6', r=2) ass = vu.makeAssembly([apts] + acts) return ass #NB: a demo actor is returned setattr(actor, 'variances', np.array(variances)) return actor #NB: original actor is modified
def region_grow(geo, seed_points, seed_ids, logger, n_max=99): # initialize output arrays array_ids = -1 * np.ones(geo.GetNumberOfPoints(), dtype=int) array_rad = np.zeros(geo.GetNumberOfPoints()) array_dist = -1 * np.ones(geo.GetNumberOfPoints(), dtype=int) array_ids[seed_points] = seed_ids # initialize ids cids_all = set() pids_all = set(seed_points.tolist()) pids_new = set(seed_points.tolist()) # get points pts = v2n(geo.GetPoints().GetData()) # loop until region stops growing or reaches maximum number of iterations i = 0 while len(pids_new) > 0 and i < n_max: # update pids_old = pids_new # print progress print_str = 'Iteration ' + str(i) print_str += '\tNew points ' + str(len(pids_old)) + ' ' print_str += '\tTotal points ' + str(len(pids_all)) logger.info(print_str) # grow region one step pids_new = grow(geo, array_ids, pids_old, pids_all, cids_all) # convert to array pids_old_arr = list(pids_old) # create point locator with old wave front points = vtk.vtkPoints() points.Initialize() for i_old in pids_old: points.InsertNextPoint(geo.GetPoint(i_old)) dataset = vtk.vtkPolyData() dataset.SetPoints(points) locator = vtk.vtkPointLocator() locator.Initialize() locator.SetDataSet(dataset) locator.BuildLocator() # find closest point in new wave front for i_new in pids_new: i_old = pids_old_arr[locator.FindClosestPoint(geo.GetPoint(i_new))] array_ids[i_new] = array_ids[i_old] array_rad[i_new] = array_rad[i_old] + np.linalg.norm(pts[i_new] - pts[i_old]) array_dist[i_new] = i # count grow iterations i += 1 return array_ids, array_dist + 1, array_rad
def cutPolySurface(dataSet, point, normal): ''' Cut a surface with a plane, and return an ordered list of points around the circumference of the resulting curve. The cut must result in a closed loop, and if the cut produces multiple sub-curves the closest one is returned. Args: :dataSet: (vtkPolyData): surface dataset :point: origin of the cutplane :normal: normal of the cutplane Returns: :np.array: List of positions around the cicumference of the cut Raises: RuntimeError: If the cut results in a non-closed loop being formed ''' # Generate surface cutcurve plane = vtk.vtkPlane() plane.SetOrigin(point[0], point[1], point[2]) plane.SetNormal(normal[0], normal[1], normal[2]) cutter = vtk.vtkCutter() cutter.SetInputData(dataSet) cutter.SetCutFunction(plane) cutter.Update() # Get cut line edges cutData = cutter.GetOutput() edges = [] cutLines = cutData.GetLines() cutLines.InitTraversal() idList = vtk.vtkIdList() while cutLines.GetNextCell(idList) == 1: edges.append((idList.GetId(0), idList.GetId(1))) # Gather all points by traversing the edge graph starting # from the point closest to the centerline point locator = vtk.vtkPointLocator() locator.SetDataSet(cutData) locator.BuildLocator() startPtId = locator.FindClosestPoint(point) pointIds = [startPtId] while True: # Find the edge that starts at the latest point pred = (v[1] for v in edges if v[0] == pointIds[-1]) currentPtId = pred.next() # Check if we've returned to the start point if currentPtId == startPtId: break pointIds.append(currentPtId) else: # if no break occured raise RuntimeError('The cut curve does not form a closed loop') cutCurve = dsa.WrapDataObject(cutData) return cutCurve.Points[pointIds]
def __init__(self, target_point): self.__target_point = np.array([target_point[0], target_point[1], target_point[2]]) self.__points = vtk.vtkPolyData() self.__points.SetPoints(vtk.vtkPoints()) self.__point_locator = vtk.vtkPointLocator() self.__point_locator.SetDataSet(self.__points)
def CalculateDistance(mito_surface_name, cell_surface_name): #Open the surface of Mito SurfaceMito = LegacyVTKReader(FileNames=[mito_surface_name]) SurfaceMito = GetActiveSource() SurfaceMito = servermanager.Fetch(SurfaceMito) #Open the surface of Cell SurfaceCell = LegacyVTKReader(FileNames=[cell_surface_name]) SurfaceCell = GetActiveSource() SurfaceCell = servermanager.Fetch(SurfaceCell) #Get the bounds of the cell(xmin,xmax,ymin,ymax,zmin,zmax) bounds = [0] * 6 SurfaceCell.GetBounds(bounds) #Creating the point locator LocatorMito = vtk.vtkPointLocator() LocatorMito.SetDataSet(SurfaceMito) LocatorMito.BuildLocator() #Vector to store the distance from foci to mito Distances = [] #Now you can calculate the distance between the #foci (x,y,z) and the Surface: for randomNumber in range(100): x = random.uniform(bounds[0], bounds[1]) y = random.uniform(bounds[2], bounds[3]) z = random.uniform(bounds[4], bounds[5]) selectEnclosedPointsCell = vtk.vtkSelectEnclosedPoints() selectEnclosedPointsCell.Initialize(SurfaceCell) insideCell = selectEnclosedPointsCell.IsInsideSurface(x, y, z) #Check to see if the random foci is inside the cell if insideCell: selectEnclosedPointsMito = vtk.vtkSelectEnclosedPoints() selectEnclosedPointsMito.Initialize(SurfaceMito) insideMito = selectEnclosedPointsMito.IsInsideSurface(x, y, z) #Check to see if the random foci is inside the mitochroniral if insideMito: continue else: r = [x, y, z] ptId = LocatorMito.FindClosestPoint(r) u = SurfaceMito.GetPoints().GetPoint(ptId) distance = math.sqrt((r[0] - u[0])**2 + (r[1] - u[1])**2 + (r[2] - u[2])**2) Distances.append(distance) else: continue Delete(GetActiveSource()) del SurfaceMito del SurfaceCell #del LocatorCell del LocatorMito return Distances
def getClosestPointIndex(self, fidNode, inputPolyData, landmarkID): landmarkCoord = numpy.zeros(3) fidNode.GetNthFiducialPosition(landmarkID, landmarkCoord) pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(inputPolyData) pointLocator.AutomaticOn() pointLocator.BuildLocator() indexClosestPoint = pointLocator.FindClosestPoint(landmarkCoord) return indexClosestPoint
def projectCurveToSurface(self, inputCurve, inputModel1, inputModel2): outputPoints = vtk.vtkPoints() locator = vtk.vtkPointLocator() locator.SetDataSet(inputModel1) locator.BuildLocator() for i in range(inputCurve.GetNumberOfPoints()): pointId = locator.FindClosestPoint(inputCurve.GetPoint(i)) outputPoints.InsertNextPoint(inputModel2.GetPoint(pointId)) return outputPoints
def getPointLocator(mesh, verbose=0): myVTK.myPrint(verbose, "*** getPointLocator ***") point_locator = vtk.vtkPointLocator() point_locator.SetDataSet(mesh) point_locator.Update() return point_locator
def transfer_gtlabels(surface, target, arrayname): """Project labels in array with arrayname from surface to target.""" # labels regionslabels = getregionslabels() indexes = ['pv1', 'pv2', 'pv3', 'pv4', 'laa'] # cleaning target = cleanpolydata(target) numberofpoints = target.GetNumberOfPoints() # create array gtlabelsarray = vtk.vtkDoubleArray() gtlabelsarray.SetName(arrayname) gtlabelsarray.SetNumberOfTuples(numberofpoints) target.GetPointData().AddArray(gtlabelsarray) # initialize with body label gtlabelsarray.FillComponent(0, regionslabels['body']) # get labels from surface gtlabelsurface = surface.GetPointData().GetArray(arrayname) # initiate locator locator = vtk.vtkPointLocator() locator.SetDataSet(surface) locator.BuildLocator() # go through each point of target surface for i in range(numberofpoints): # determine closest point on surface point = target.GetPoint(i) closestpointid = locator.FindClosestPoint(point) # get label of point value = gtlabelsurface.GetValue(closestpointid) # assign label to target point gtlabelsarray.SetValue(i, value) # check that there is only one region per pv/laa label for index in indexes: # for each region, check if there are other regions on the surface # with the same label. If so, keep largest region # and relabel small regions to body label target = filldisconnectedregion(target, arrayname, regionslabels[index], regionslabels['body']) # for each region, fill small patches (i.e. body label) # with corresponding region label target = fillpatch(target, arrayname, regionslabels[index], regionslabels['body']) # relabel isolated points in the body with vein label (e.g. close to ostia) target = fillpatch(target, arrayname, regionslabels['body'], regionslabels['body']) return target
def createISORegionOverlay(self, curveNode): """ :param curve: The curve that the overlay will be created from (vtkMRMLMarkupsCurveNode) """ polyData = curveNode.GetShortestDistanceSurfaceNode().GetPolyData() if polyData is None: #TODO return transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputData(polyData) modelToWorldTransform = vtk.vtkGeneralTransform() slicer.vtkMRMLTransformNode.GetTransformBetweenNodes( curveNode.GetShortestDistanceSurfaceNode().GetParentTransformNode( ), None, modelToWorldTransform) transformFilter.SetTransform(modelToWorldTransform) transformFilter.Update() polyData = transformFilter.GetOutput() pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(transformFilter.GetOutput()) pointLocator.BuildLocator() curvePoints = curveNode.GetCurvePointsWorld() isoRegionsArrayName = "ISO-Regions" pointData = polyData.GetPointData() isoRegionsArray = pointData.GetArray(isoRegionsArrayName) if isoRegionsArray is None: isoRegionsArray = vtk.vtkIdTypeArray() isoRegionsArray.SetName(isoRegionsArrayName) isoRegionsArray.SetNumberOfValues(polyData.GetNumberOfPoints()) isoRegionsArray.Fill(-1) curveNode.GetShortestDistanceSurfaceNode().AddPointScalars( isoRegionsArray) visitedPoints = [] previousISORegion = [] for regionIndex in range(7): currentISORegion = [] if regionIndex == 0: for i in range(curvePoints.GetNumberOfPoints()): curvePoint_World = curvePoints.GetPoint(i) currentISORegion.append( pointLocator.FindClosestPoint(curvePoint_World)) else: currentISORegion = self.getAdjacentPoints( polyData, previousISORegion) for isoPointID in currentISORegion: if isoPointID in visitedPoints: continue isoRegionsArray.SetValue(isoPointID, regionIndex) visitedPoints += currentISORegion previousISORegion = currentISORegion
def __init__(self, inp): dataset = vtk.vtkPolyData() dataset.SetPoints(inp.GetPoints()) locator = vtk.vtkPointLocator() locator.Initialize() locator.SetDataSet(dataset) locator.BuildLocator() self.locator = locator
def sliceClosestModel(self, point): originalModel = None # set up plane normal = np.array([ float(self.sliceLogic.GetSliceNode().GetName() == name) for name in ['Yellow', 'Green', 'Red'] ]) plane = vtk.vtkPlane() plane.SetOrigin(point) # point in plane plane.SetNormal(normal) # set up cutter cutter = vtk.vtkCutter() cutter.SetCutFunction(plane) cutter.SetGenerateCutScalars(0) cutter.Update() # init point locator and output pointsLocator = vtk.vtkPointLocator() globalMinDistance = 1000 outPolyData = vtk.vtkPolyData() # iterate over models in scene nModels = slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLModelNode') for i in range(nModels): model = slicer.mrmlScene.GetNthNodeByClass(i, 'vtkMRMLModelNode') polyData = model.GetPolyData() if model.GetDisplayNode() and model.GetDisplayNode().GetVisibility( ) and polyData.GetNumberOfCells() > 1 and model.GetName( ) != 'auxSphereModel': # model visible and cells available cutter.SetInputData(polyData) cutter.Update() cutterOutput = cutter.GetOutput() if cutterOutput.GetNumberOfCells( ): # model intersects with plane # get distance from input point to closest point in model pointsLocator.SetDataSet(cutterOutput) pointsLocator.BuildLocator() closestPoint = cutterOutput.GetPoint( pointsLocator.FindClosestPoint(point)) localMinDistance = vtk.vtkMath().Distance2BetweenPoints( closestPoint, point) if localMinDistance < globalMinDistance: # new min outPolyData.DeepCopy(cutterOutput) globalMinDistance = localMinDistance originalModel = model # return in case no model found if not originalModel: return False, False # generate output triangulator = vtk.vtkContourTriangulator() triangulator.SetInputData(outPolyData) triangulator.Update() slicedModel = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLModelNode') slicedModel.SetAndObservePolyData(triangulator.GetOutput()) slicedModel.CreateDefaultDisplayNodes() slicedModel.GetDisplayNode().SetVisibility(0) return slicedModel, originalModel
def getPointLocator( mesh, verbose=0): mypy.my_print(verbose, "*** getPointLocator ***") point_locator = vtk.vtkPointLocator() point_locator.SetDataSet(mesh) point_locator.Update() return point_locator
def getClosestVerticesForFiducials(modelNode, markupsFiducialNode): closestVertices = [] pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(modelNode.GetPolyData()) for fiducialIndex in range(markupsFiducialNode.GetNumberOfFiducials()): fiducialPos = [0] * 3 markupsFiducialNode.GetNthFiducialPosition(fiducialIndex, fiducialPos) closestVertexIndex = pointLocator.FindClosestPoint(fiducialPos) if closestVertexIndex >= 0: closestVertices.append(closestVertexIndex) return closestVertices
def __init__(self, inp): if isinstance(inp, str): geo = read_geo(inp) inp = geo.GetOutput() dataset = vtk.vtkPolyData() dataset.SetPoints(inp.GetPoints()) locator = vtk.vtkPointLocator() locator.Initialize() locator.SetDataSet(dataset) locator.BuildLocator() self.locator = locator
def populate_models(config): """ Loads vtk models from a directory and returns a list of vtk actors and associated vtkPointLocators :param: configuration, should contain a target value :param: model_to_world: 4x4 matrix, of dtype float32 :return: locators :return: actors :raises: KeyError if target not in config """ models = [] if "target" not in config: raise KeyError("Config must contain target key") path_name = config.get("target") loader = VTKSurfaceModelDirectoryLoader(path_name) models = loader.models locators = [] model_to_world = _set_model_to_world(config) transform = vtk.vtkTransform() transform.SetMatrix(np2vtk(model_to_world)) for model in models: print(model.source.GetCenter()) transformer = vtk.vtkTransformPolyDataFilter() transformer.SetTransform(transform) transformer.SetInputData(model.source) target = vtk.vtkPolyData() transformer.SetOutput(target) transformer.Update() model.source = target transformer.SetInputConnection(model.normals.GetOutputPort()) model.mapper = vtk.vtkPolyDataMapper() model.mapper.SetInputConnection(transformer.GetOutputPort()) model.mapper.Update() model.actor.SetMapper(model.mapper) print("after trans", model.source.GetCenter()) point_locator = vtk.vtkPointLocator() point_locator.SetDataSet(model.source) point_locator.Update() locators.append(point_locator) return models, locators
def closestPoint(actor, pt, N=1, radius=None, returnIds=False): """ Find the closest point on a polydata given an other point. The appropriate locator is built on the fly and cached for speed. If N>1, return a list of N ordered closest points. If radius is given, get all points within. """ poly = polydata(actor, True) if N > 1 or radius: plocexists = hasattr(actor, 'point_locator') if not plocexists or (plocexists and actor.point_locator is None): point_locator = vtk.vtkPointLocator() point_locator.SetDataSet(poly) point_locator.BuildLocator() setattr(actor, 'point_locator', point_locator) vtklist = vtk.vtkIdList() if N > 1: actor.point_locator.FindClosestNPoints(N, pt, vtklist) else: actor.point_locator.FindPointsWithinRadius(radius, pt, vtklist) if returnIds: return [ int(vtklist.GetId(k)) for k in range(vtklist.GetNumberOfIds()) ] else: trgp = [] for i in range(vtklist.GetNumberOfIds()): trgp_ = [0, 0, 0] vi = vtklist.GetId(i) poly.GetPoints().GetPoint(vi, trgp_) trgp.append(trgp_) return np.array(trgp) clocexists = hasattr(actor, 'cell_locator') if not clocexists or (clocexists and actor.cell_locator is None): cell_locator = vtk.vtkCellLocator() cell_locator.SetDataSet(poly) cell_locator.BuildLocator() setattr(actor, 'cell_locator', cell_locator) trgp = [0, 0, 0] cid = vtk.mutable(0) dist2 = vtk.mutable(0) subid = vtk.mutable(0) actor.cell_locator.FindClosestPoint(pt, trgp, cid, subid, dist2) if returnIds: return int(cid) else: return np.array(trgp)
def Execute(self): if not self._Surface: self.PrintError( 'vmtkPointListSeedSelector Error: Surface not set.') return if not self.SourcePoints: self.PrintError( 'vmtkPointListSeedSelector Error: SourcePoints not set.') return if not self.TargetPoints: self.PrintError( 'vmtkPointListSeedSelector Error: TargetPoints not set.') return self._SourceSeedIds.Initialize() self._TargetSeedIds.Initialize() if len(self.SourcePoints) % 3 != 0: self.PrintError( 'vmtkPointListSeedSelector Error: SourcePoints not made up of triplets.' ) return if len(self.TargetPoints) % 3 != 0: self.PrintError( 'vmtkPointListSeedSelector Error: TargetPoints not made up of triplets.' ) return pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(self._Surface) pointLocator.BuildLocator() for i in range(len(self.SourcePoints) / 3): point = [ self.SourcePoints[3 * i + 0], self.SourcePoints[3 * i + 1], self.SourcePoints[3 * i + 2] ] id = pointLocator.FindClosestPoint(point) self._SourceSeedIds.InsertNextId(id) for i in range(len(self.TargetPoints) / 3): point = [ self.TargetPoints[3 * i + 0], self.TargetPoints[3 * i + 1], self.TargetPoints[3 * i + 2] ] id = pointLocator.FindClosestPoint(point) self._TargetSeedIds.InsertNextId(id)
def FindSeeds(surfaceSrc, inletPt, outletPts): """Given a vtkAlgorithm and a list of Inlets and Outlets, return the point IDs of the closest points to the inlets and outlets (as a vtkIdList). """ surfaceSrc.Update() ptFinder = vtk.vtkPointLocator() ptFinder.SetDataSet(surfaceSrc.GetOutput()) inletPtIds = vtk.vtkIdList() inletPtIds.InsertNextId(ptFinder.FindClosestPoint(inletPt)) outletPtIds = vtk.vtkIdList() for outletPt in outletPts: outletPtIds.InsertNextId(ptFinder.FindClosestPoint(outletPt)) continue return inletPtIds, outletPtIds
def calculateDistancesToSurface(self, polydata, imgdata, objects, surfaceCOM): """ Calculate the distance to surface for the given set of objects """ if not polydata: print "Failed to read polydata" return [], [] locator = vtk.vtkPointLocator() locator.SetDataSet(polydata) locator.BuildLocator() distances = [] comDistances = [] cx, cy, cz = surfaceCOM objVoxelSizes = self.segmentedSource.getVoxelSize() objVoxelSizes = [x*1000000 for x in objVoxelSizes] surfVoxelSizes = self.polyDataSource.getVoxelSize() surfVoxelSizes = [x*1000000 for x in surfVoxelSizes] cxReal = cx * surfVoxelSizes[0] cyReal = cy * surfVoxelSizes[1] czReal = cz * surfVoxelSizes[2] xs, ys, zs = imgdata.GetSpacing() for obj in objects: x, y, z = obj.getCenterOfMass() xReal = x * objVoxelSizes[0] yReal = y * objVoxelSizes[1] zReal = z * objVoxelSizes[2] comDistances.append(obj.distance3D(xReal,yReal,zReal,cxReal,cyReal,czReal)) xPoint = x * xs yPoint = y * ys zPoint = z * zs dist = 0 objid = locator.FindClosestPoint((xPoint, yPoint, zPoint)) x2,y2,z2 = polydata.GetPoint(objid) x2 /= xs y2 /= ys z2 /= zs pos1 = x,y,z pos2 = x2,y2,z2 x, y, z = [pos1[i] * objVoxelSizes[i] for i in range(0,3)] x2, y2, z2 = [pos2[i] * surfVoxelSizes[i] for i in range(0,3)] dist = obj.distance3D(x,y,z,x2,y2,z2) distances.append(dist) return distances, comDistances
def closest_point(mesh, vector, radius = None): locator = vtk.vtkPointLocator() ugrid = read_ugrid(mesh) locator.SetDataSet(ugrid) vector = map(float, vector) assert len(vector) == 3 if radius is None: index = locator.FindClosestPoint(vector) else: a = vtk.mutable(0.0) index = locator.FindClosestPointWithinRadius(radius, vector, a) point = ugrid.GetPoint(index) distance = math.sqrt(sum(starmap(lambda a, b: (b-a)**2, zip(vector, point)))) return {'index': index, 'point': point, 'dist': distance}
def transfer_labels(surface,ref,arrayname,value): # initiate point locator locator = vtk.vtkPointLocator() locator.SetDataSet(surface) locator.BuildLocator() # get array from surface array = surface.GetPointData().GetArray(arrayname) # go through each point of ref surface, determine closest point on surface, for i in range(ref.GetNumberOfPoints()): point = ref.GetPoint(i) closestpoint_id = locator.FindClosestPoint(point) array.SetValue(closestpoint_id, value) surface.GetPoints().Modified() return surface
def FindClippingPointOnParentArtery(centerlines,parentCenterlines,toll): divergingPointID = -1 divergingPoint = [0.0,0.0,0.0] divergingPointMISR = -1 clippingPointID = -1 clippingPoint = [0.0,0.0,0.0] cell0PointIds = vtk.vtkIdList() cell1PointIds = vtk.vtkIdList() centerlines.GetCellPoints(0,cell0PointIds) #this is the cl that goes through the aneurysm centerlines.GetCellPoints(1,cell1PointIds) for i in range(0,min(cell0PointIds.GetNumberOfIds(),cell1PointIds.GetNumberOfIds())): cell0Point = centerlines.GetPoint(cell0PointIds.GetId(i)) cell1Point = centerlines.GetPoint(cell1PointIds.GetId(i)) distanceBetweenPoints = math.sqrt(vtk.vtkMath.Distance2BetweenPoints(cell0Point,cell1Point)) if (distanceBetweenPoints>toll): divergingPointID = cell1PointIds.GetId(i) divergingPoint = centerlines.GetPoint(cell1PointIds.GetId(i)) divergingPointMISR = centerlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell1PointIds.GetId(i)) break MISphere = vtk.vtkSphere() MISphere.SetCenter(divergingPoint) MISphere.SetRadius(divergingPointMISR) tempPoint = [0.0,0.0,0.0] for i in range(divergingPointID,0,-1): value = MISphere.EvaluateFunction(centerlines.GetPoint(i)) if (value>=0.0): tempPoint = centerlines.GetPoint(i) break locator = vtk.vtkPointLocator() locator.SetDataSet(parentCenterlines) locator.BuildLocator() clippingPointID = locator.FindClosestPoint(tempPoint) clippingPoint = parentCenterlines.GetPoint(clippingPointID) return clippingPoint,divergingPoint
def projectLandmarkOnSurface(self, inputModelID, markupsNodeID): markupsNode = slicer.mrmlScene.GetNodeByID(markupsNodeID) polyData = slicer.mrmlScene.GetNodeByID(inputModelID).GetPolyData() pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(polyData) pointLocator.AutomaticOn() pointLocator.BuildLocator() for i in range(0, markupsNode.GetNumberOfMarkups()): landmarkID = markupsNode.GetNthMarkupID(i) landmarkIndex = markupsNode.GetMarkupIndexByID(landmarkID) print " ------------------------ getClosestPointIndex ------------------------ " landmarkCoord = [-1, -1, -1] markupsNode.GetNthFiducialPosition(landmarkIndex, landmarkCoord) indexClosestPoint = pointLocator.FindClosestPoint(landmarkCoord) print " closest Point:", indexClosestPoint, " Coord", landmarkCoord print " ------------------------ replaceLandmark ------------------------ " polyData.GetPoints().GetPoint(indexClosestPoint, landmarkCoord) markupsNode.SetNthFiducialPosition(landmarkIndex, landmarkCoord[0], landmarkCoord[1], landmarkCoord[2])
def Execute(self): if not self._Surface: self.PrintError('vmtkPointListSeedSelector Error: Surface not set.') return if not self.SourcePoints: self.PrintError('vmtkPointListSeedSelector Error: SourcePoints not set.') return if not self.TargetPoints: self.PrintError('vmtkPointListSeedSelector Error: TargetPoints not set.') return self._SourceSeedIds.Initialize() self._TargetSeedIds.Initialize() if len(self.SourcePoints) % 3 != 0: self.PrintError('vmtkPointListSeedSelector Error: SourcePoints not made up of triplets.') return if len(self.TargetPoints) % 3 != 0: self.PrintError('vmtkPointListSeedSelector Error: TargetPoints not made up of triplets.') return pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(self._Surface) pointLocator.BuildLocator() for i in range(len(self.SourcePoints)/3): point = [self.SourcePoints[3*i+0],self.SourcePoints[3*i+1],self.SourcePoints[3*i+2]] id = pointLocator.FindClosestPoint(point) self._SourceSeedIds.InsertNextId(id) for i in range(len(self.TargetPoints)/3): point = [self.TargetPoints[3*i+0],self.TargetPoints[3*i+1],self.TargetPoints[3*i+2]] id = pointLocator.FindClosestPoint(point) self._TargetSeedIds.InsertNextId(id)
def start(self, preview=False): logging.debug("Starting Centerline Computation..") # first we need the nodes currentModelNode = self.inputModelNodeSelector.currentNode() currentSeedsNode = self.seedFiducialsNodeSelector.currentNode() currentOutputModelNode = self.outputModelNodeSelector.currentNode() currentEndPointsMarkupsNode = self.outputEndPointsNodeSelector.currentNode() currentVoronoiModelNode = self.voronoiModelNodeSelector.currentNode() if not currentModelNode: # we need a input volume node logging.error("Input model node required") return False if not currentSeedsNode: # we need a seeds node logging.error("Input seeds node required") return False if not currentOutputModelNode or currentOutputModelNode.GetID() == currentModelNode.GetID(): # we need a current model node, the display node is created later newModelNode = slicer.mrmlScene.CreateNodeByClass("vtkMRMLModelNode") newModelNode.UnRegister(None) newModelNode.SetName(slicer.mrmlScene.GetUniqueNameByString(self.outputModelNodeSelector.baseName)) currentOutputModelNode = slicer.mrmlScene.AddNode(newModelNode) currentOutputModelNode.CreateDefaultDisplayNodes() self.outputModelNodeSelector.setCurrentNode(currentOutputModelNode) if not currentEndPointsMarkupsNode or currentEndPointsMarkupsNode.GetID() == currentSeedsNode.GetID(): # we need a current seed node, the display node is created later currentEndPointsMarkupsNode = slicer.mrmlScene.GetNodeByID(slicer.modules.markups.logic().AddNewFiducialNode("Centerline endpoints")) self.outputEndPointsNodeSelector.setCurrentNode(currentEndPointsMarkupsNode) # the output models preparedModel = vtk.vtkPolyData() model = vtk.vtkPolyData() network = vtk.vtkPolyData() voronoi = vtk.vtkPolyData() currentCoordinatesRAS = [0, 0, 0] # grab the current coordinates currentSeedsNode.GetNthFiducialPosition(0,currentCoordinatesRAS) # prepare the model preparedModel.DeepCopy(self.logic.prepareModel(currentModelNode.GetPolyData())) # decimate the model (only for network extraction) model.DeepCopy(self.logic.decimateSurface(preparedModel)) # open the model at the seed (only for network extraction) model.DeepCopy(self.logic.openSurfaceAtPoint(model, currentCoordinatesRAS)) # extract Network network.DeepCopy(self.logic.extractNetwork(model)) # # # not preview mode: real computation! if not preview: # here we start the actual centerline computation which is mathematically more robust and accurate but takes longer than the network extraction # clip surface at endpoints identified by the network extraction tupel = self.logic.clipSurfaceAtEndPoints(network, currentModelNode.GetPolyData()) clippedSurface = tupel[0] endpoints = tupel[1] # now find the one endpoint which is closest to the seed and use it as the source point for centerline computation # all other endpoints are the target points sourcePoint = [0, 0, 0] # the following arrays have the same indexes and are synchronized at all times distancesToSeed = [] targetPoints = [] # we now need to loop through the endpoints two times # first loop is to detect the endpoint resulting in the tiny hole we poked in the surface # this is very close to our seed but not the correct sourcePoint for i in range(endpoints.GetNumberOfPoints()): currentPoint = endpoints.GetPoint(i) # get the euclidean distance currentDistanceToSeed = math.sqrt(math.pow((currentPoint[0] - currentCoordinatesRAS[0]), 2) + math.pow((currentPoint[1] - currentCoordinatesRAS[1]), 2) + math.pow((currentPoint[2] - currentCoordinatesRAS[2]), 2)) targetPoints.append(currentPoint) distancesToSeed.append(currentDistanceToSeed) # now we have a list of distances with the corresponding points # the index with the most minimal distance is the holePoint, we want to ignore it # the index with the second minimal distance is the point closest to the seed, we want to set it as sourcepoint # all other points are the targetpoints # get the index of the holePoint, which we want to remove from our endPoints holePointIndex = distancesToSeed.index(min(distancesToSeed)) # .. and remove it distancesToSeed.pop(holePointIndex) targetPoints.pop(holePointIndex) # now find the sourcepoint sourcePointIndex = distancesToSeed.index(min(distancesToSeed)) # .. and remove it after saving it as the sourcePoint sourcePoint = targetPoints[sourcePointIndex] distancesToSeed.pop(sourcePointIndex) targetPoints.pop(sourcePointIndex) # again, at this point we have a) the sourcePoint and b) a list of real targetPoints # now create the sourceIdList and targetIdList for the actual centerline computation sourceIdList = vtk.vtkIdList() targetIdList = vtk.vtkIdList() pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(preparedModel) pointLocator.BuildLocator() # locate the source on the surface sourceId = pointLocator.FindClosestPoint(sourcePoint) sourceIdList.InsertNextId(sourceId) currentEndPointsMarkupsNode.GetDisplayNode().SetTextScale(0) currentEndPointsMarkupsNode.RemoveAllMarkups() currentEndPointsMarkupsNode.AddFiducialFromArray(sourcePoint) # locate the endpoints on the surface for p in targetPoints: fid = currentEndPointsMarkupsNode.AddFiducialFromArray(p) currentEndPointsMarkupsNode.SetNthFiducialSelected(fid,False) id = pointLocator.FindClosestPoint(p) targetIdList.InsertNextId(id) tupel = self.logic.computeCenterlines(preparedModel, sourceIdList, targetIdList) network.DeepCopy(tupel[0]) voronoi.DeepCopy(tupel[1]) currentOutputModelNode.SetAndObservePolyData(network) # Make model node semi-transparent to make centerline inside visible currentModelNode.CreateDefaultDisplayNodes() currentModelDisplayNode = currentModelNode.GetDisplayNode() currentModelDisplayNode.SetOpacity(0.4) if currentVoronoiModelNode: # Configure the displayNode to show the centerline and Voronoi model currentOutputModelNode.CreateDefaultDisplayNodes() currentOutputModelDisplayNode = currentOutputModelNode.GetDisplayNode() currentOutputModelDisplayNode.SetColor(0.0, 0.0, 0.4) # red currentOutputModelDisplayNode.SetBackfaceCulling(0) currentOutputModelDisplayNode.SetSliceIntersectionVisibility(0) currentOutputModelDisplayNode.SetVisibility(1) currentOutputModelDisplayNode.SetOpacity(1.0) # only update the voronoi node if we are not in preview mode if currentVoronoiModelNode and not preview: currentVoronoiModelNode.SetAndObservePolyData(voronoi) currentVoronoiModelNode.CreateDefaultDisplayNodes() currentVoronoiModelDisplayNode = currentVoronoiModelNode.GetDisplayNode() # always configure the displayNode to show the model currentVoronoiModelDisplayNode.SetScalarVisibility(1) currentVoronoiModelDisplayNode.SetBackfaceCulling(0) currentVoronoiModelDisplayNode.SetActiveScalarName("Radius") currentVoronoiModelDisplayNode.SetAndObserveColorNodeID(slicer.mrmlScene.GetNodesByName("Labels").GetItemAsObject(0).GetID()) currentVoronoiModelDisplayNode.SetSliceIntersectionVisibility(0) currentVoronoiModelDisplayNode.SetVisibility(1) currentVoronoiModelDisplayNode.SetOpacity(0.5) logging.debug("End of Centerline Computation..") return True
(p1[1]-p2[1])**2 + (p1[2]-p2[2])**2) def load_polydata(filename): reader = vtk.vtkPolyDataReader() reader.SetFileName(filename) reader.Update() return reader.GetOutput() xy_res, z_res = float(sys.argv[2]), float(sys.argv[3]) raw_pipeline = load_polydata(sys.argv[4]) hq_pipeline = load_polydata(sys.argv[5]) lq_pipeline = load_polydata(sys.argv[6]) hq_locator = vtk.vtkPointLocator() hq_locator.SetDataSet(hq_pipeline) hq_locator.BuildLocator() lq_locator = vtk.vtkPointLocator() lq_locator.SetDataSet(lq_pipeline) lq_locator.BuildLocator() hq_points_results = [] lq_points_results = [] for i in range(raw_pipeline.GetPoints().GetNumberOfPoints()): raw_point = raw_pipeline.GetPoints().GetPoint(i) hq_point_idx = hq_locator.FindClosestPoint(raw_pipeline.GetPoints().GetPoint(i)) hq_point = hq_pipeline.GetPoints().GetPoint(hq_point_idx)
mesh = rdm.GetOutput() # In[33]: rdp = vtk.vtkPLYReader() rdp.SetFileName(points_filename) rdp.Update() pts = rdp.GetOutput() # In[34]: loc = vtk.vtkPointLocator() loc.SetDataSet(mesh) loc.BuildLocator() #subdivide the index array (not continuous) indices = list(range(pts.GetNumberOfPoints())) ranges = [indices[i::Ncpu] for i in range(Ncpu)] print(f'Number of inidces:{len(indices)}, number of ranges:{len(ranges)}\n') index_range = ranges[rank] #this range will be used on this node activation_ptids = [] #local storage for activation point ids #extract the neighbors on each nodes
def execute(self): readerV=vtk.vtkPolyDataReader() readerV.SetFileName(self.vascular_file) readerA=vtk.vtkPolyDataReader() readerA.SetFileName(self.airway_file) readerV.Update() vessel=readerV.GetOutput() readerA.Update() airway=readerA.GetOutput() array_a =dict(); array_v =dict(); for ff in ("scale", "hevec0", "hevec1", "hevec2", "h0", "h1", "h2"): tmp=airway.GetFieldData().GetArray(ff) if isinstance(tmp,vtk.vtkDataArray) == False: tmp=airway.GetPointData().GetArray(ff) array_a[ff]=tmp for ff in ("scale", "hevec0", "hevec1", "hevec2", "h0", "h1", "h2"): tmp=vessel.GetFieldData().GetArray(ff) if isinstance(tmp,vtk.vtkDataArray) == False: tmp=vessel.GetPointData().GetArray(ff) array_v[ff]=tmp pL=vtk.vtkPointLocator() pL.SetDataSet(vessel) pL.BuildLocator() idList=vtk.vtkIdList() na = airway.GetNumberOfPoints() a_radius=list() v_radius=list() csa = np.arange(0,40,0.05) rad = np.sqrt(csa/math.pi) bden = np.zeros(csa.size) cden = np.zeros(csa.size) print "Number of Airway Points "+str(na) print "Number of Vessel Points "+str(vessel.GetNumberOfPoints()) for kk in xrange(na): a_p=airway.GetPoint(kk) pL.FindClosestNPoints(20,a_p,idList) a_s=array_a["scale"].GetValue(kk) a_v=array_a["hevec2"].GetTuple3(kk) a_r=self.airway_radius_from_sigma(a_s) for kk2 in xrange(idList.GetNumberOfIds()): #Get info about point test_id=idList.GetId(kk2) v_p=vessel.GetPoint(test_id) v_s=array_v["scale"].GetValue(test_id) v_v=array_v["hevec0"].GetTuple3(test_id) v_r=self.vessel_radius_from_sigma(v_s) distance = LA.norm(np.array(v_p)-np.array(a_p)) angle1 = math.acos(abs(sum(np.array(v_v)*np.array(a_v)))) vv = LA.norm(np.array(v_v)+np.array(a_v)) foo = abs(1/(vv*distance) * sum ( (np.array(v_v)+np.array(a_v)) * (np.array(v_p)-np.array(a_p)))) angle2 = math.acos( foo ) #Test conditions about point # distance < th if ( (distance < self.distance_th-self.distance_decay*kk2) & (angle1 < self.angle1_th) & (angle2 > self.angle2_th) & (a_s/v_s < self.scale_ratio_th) & (v_s/a_s < self.scale_ratio_th) & (a_r > 1.0) & (v_r>0.6)): #a_r=1.2 a_radius.append(a_r) #v_r=1.0 v_radius.append(v_r) a_radius = np.array(a_radius,dtype=float) v_radius = np.array(v_radius,dtype=float) #bron_array =((a_radius**2)/(v_radius**2)) #accept_mask = self.reject_outliers_mask(bron_array) #print np.mean(a_radius2) accept_a_mask=(np.abs(a_radius - np.mean(a_radius)) < 4 * np.std(a_radius)) accept_v_mask=(np.abs(v_radius - np.mean(v_radius)) < 4 * np.std(v_radius)) #accept_a_mask = self.reject_outliers_mask(a_radius2) #accept_v_mask = self.reject_outliers_mask(v_radius2) a_radius=a_radius[np.logical_and(accept_a_mask,accept_v_mask)] v_radius=v_radius[np.logical_and(accept_a_mask,accept_v_mask)] for a_r,v_r in zip(a_radius,v_radius): bden += 1/(math.sqrt(2*math.pi)*self.sigma) * a_r/v_r *np.exp(-(csa-math.pi*(v_r)**2)**2/(2*self.sigma**2)) cden += 1/(math.sqrt(2*math.pi)*self.sigma) * np.exp(-(csa-math.pi*(v_r)**2)**2/(2*self.sigma**2)) #This is how you can do it using a kde method in scipy print "Number of computing points "+str(len(a_radius)) csa_samples = math.pi*(v_radius**2) kcden = kde.gaussian_kde(csa_samples) #cden = kcden(csa) bden = bden/(float(len(a_radius))) cden = cden/(float(len(a_radius))) cden[cden<np.spacing(1e10)]=np.spacing(1e10) bron = bden/cden print kcden.factor #bden[cden<0.01]=0 if self.plot == True: fig=plt.figure() ax1=fig.add_subplot(211) ax1.plot(rad,bron) ax1.grid(True) plt.ylabel('Airway Radius / Vessel Radius') ax2=fig.add_subplot(212,sharex=ax1) ax2.plot(rad,cden) ax2.grid(True) plt.xlabel('Vessel Radius (mm)') plt.ylabel('CSA Density') #ax=fig.add_subplot(223) #ax.plot(rad,kcden(csa)) #ax=fig.add_subplot(224) #ax.scatter(v_radius,np.array(a_radius)/np.array(v_radius)) fig.savefig(self.output_prefix+'_bronchiectasisPlot.png',dpi=180) #print np.mean(sum(ba/ca[ba/ca>1])) #Compute phenotypes and save result # Mean Bronchiectasis Phenotpyes ser=list() col=list() col.append('CID') ser.append(os.path.split(self.output_prefix)[1]) col.append('NPoints') ser.append(len(a_radius)) #Compute distribution of ratio with CSA foo = np.array(a_radius)/np.array(v_radius) col.append('meanRatio') ser.append(np.mean(foo[foo>0])) col.append('stdRatio') ser.append(np.std(foo[foo>0])) for th in (0,5,10,20,30): mb=np.mean(bron[csa>th]) col.append('meanBgt'+str(th)) stdb = np.std(bron[csa>th]) col.append('stdBgt'+str(th)) ser.append(mb) ser.append(stdb) # Integral Bronchiectasis Phenotpyes delta=(csa[2]-csa[1]) for th in (0,5,10,20,30): int_val = bron[np.logical_and((bron-1)>0,csa>th)]-1 intb = delta*np.sum(int_val) /(delta * np.sum(csa>th) ) col.append('intBgt'+str(th)) ser.append(intb) # Percentage of bronchiectasis for th in (0,5,10,20,30): perc= 100*np.sum(np.logical_and((bron-1)>0,csa>th))/np.sum(csa>th) col.append('Bpercgt'+str(th)) ser.append(perc) # Integral of CSA density function to have a reference for th in (0,5,10,20,30): int_val = cden[csa>th] intc = delta*np.sum(int_val) col.append('intCSAgt'+str(th)) ser.append(intc) df=pd.DataFrame(np.array(ser).reshape([1,len(ser)]),columns=col) df.to_csv(self.output_prefix+'_bronchiectasisPhenotypes.csv')
def getHyperbolicPlaneTiling( schlafli1, schlafli2, num_levels): '''Returns a vtkPolyData of the Schlafli tiling {schlafli1,schlafli2} out to num_levels deep around the central cell.''' # define the central cell edge_length = 1.0 num_vertices = schlafli1 vertex_coords = [] r1 = getPolygonRadius( edge_length, schlafli1 ); for i in range(num_vertices): angle = ( i + 0.5 ) * 2.0 * math.pi / schlafli1 vertex_coords += [ ( r1 * math.cos( angle ), r1 * math.sin( angle ), 0.0 ) ] face = range(num_vertices) # define the mirror spheres num_spheres = num_vertices R,d = getInversionCircleForPlaneTiling( edge_length, schlafli1, schlafli2 ) sphere_centers = [] for i in range(num_vertices): n = av( vertex_coords[i], vertex_coords[(i+1)%num_vertices] ) nl = mag( n ) sphere_centers += [ mul( n, d / nl ) ] append = vtk.vtkAppendPolyData() point_locator = vtk.vtkPointLocator() locator_points = vtk.vtkPoints() bounds = [-10,10,-10,10,-10,10] point_locator.InitPointInsertion(locator_points,bounds) for depth in range(num_levels+1): for sphere_list in itertools.product(range(num_spheres),repeat=depth): # make a cell by reflecting the starting cell in the order listed points = vtk.vtkPoints() centroid = (0,0,0) for iV in range(num_vertices): p = vertex_coords[iV] for iSphere in sphere_list: p = sphereInversion( p, sphere_centers[iSphere], R ) points.InsertNextPoint( p ) centroid = add( centroid, p ) # only add this cell if we haven't seen this centroid before centroid = mul( centroid, 1.0 / num_vertices ) if point_locator.IsInsertedPoint( centroid ) < 0: pd = vtk.vtkPolyData() cells = vtk.vtkCellArray() cells.InsertNextCell( len(face) ) for v in face: cells.InsertCellPoint( v ) pd.SetPoints( points ) pd.SetPolys( cells ) if vtk.vtkVersion.GetVTKMajorVersion() >= 6: append.AddInputData( pd ) else: append.AddInput( pd ) point_locator.InsertNextPoint( centroid ) # merge duplicate points cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection( append.GetOutputPort() ) cleaner.SetTolerance(0.0001) cleaner.Update() return cleaner.GetOutput()
def Execute(self): if self.Surface == None: self.PrintError('Error: no Surface.') if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.SeedSelector = vmtkPickPointSeedSelector() self.SeedSelector.vmtkRenderer = self.vmtkRenderer self.SeedSelector.Script = self self.SeedSelector.SetSurface(self.Surface) self.SeedSelector.InputInfo = self.InputInfo self.SeedSelector.InputText = self.InputText self.SeedSelector.OutputText = self.OutputText self.SeedSelector.PrintError = self.PrintError self.SeedSelector.PrintLog = self.PrintLog self.SeedSelector.Execute() mainBodySeedIds = self.SeedSelector.GetSourceSeedIds() mainBodySeedId = mainBodySeedIds.GetId(0) mainBodyPoint = self.Surface.GetPoint(mainBodySeedId) clipSeedIds = self.SeedSelector.GetTargetSeedIds() surfaceCleaner = vtk.vtkCleanPolyData() surfaceCleaner.SetInputData(self.Surface) surfaceCleaner.Update() surfaceTriangulator = vtk.vtkTriangleFilter() surfaceTriangulator.SetInputConnection(surfaceCleaner.GetOutputPort()) surfaceTriangulator.PassLinesOff() surfaceTriangulator.PassVertsOff() surfaceTriangulator.Update() clippedSurface = surfaceTriangulator.GetOutput() for i in range(clipSeedIds.GetNumberOfIds()): seedId = clipSeedIds.GetId(i) locator = vtk.vtkPointLocator() locator.SetDataSet(clippedSurface) locator.BuildLocator() seedPoint = self.Surface.GetPoint(seedId) seedPointId = locator.FindClosestPoint(seedPoint) planeEstimator = vtkvmtk.vtkvmtkPolyDataNormalPlaneEstimator() planeEstimator.SetInputData(clippedSurface) planeEstimator.SetOriginPointId(seedPointId) planeEstimator.Update() plane = vtk.vtkPlane() plane.SetOrigin(planeEstimator.GetOrigin()) plane.SetNormal(planeEstimator.GetNormal()) seamFilter = vtkvmtk.vtkvmtkTopologicalSeamFilter() seamFilter.SetInputData(clippedSurface) seamFilter.SetClosestPoint(seedPoint) seamFilter.SetSeamScalarsArrayName("SeamScalars") seamFilter.SetSeamFunction(plane) clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(seamFilter.GetOutputPort()) clipper.GenerateClipScalarsOff() clipper.GenerateClippedOutputOn() connectivity = vtk.vtkPolyDataConnectivityFilter() connectivity.SetInputConnection(clipper.GetOutputPort()) connectivity.SetExtractionModeToClosestPointRegion() connectivity.SetClosestPoint(mainBodyPoint) surfaceCleaner = vtk.vtkCleanPolyData() surfaceCleaner.SetInputConnection(connectivity.GetOutputPort()) surfaceCleaner.Update() surfaceTriangulator = vtk.vtkTriangleFilter() surfaceTriangulator.SetInputConnection(surfaceCleaner.GetOutputPort()) surfaceTriangulator.PassLinesOff() surfaceTriangulator.PassVertsOff() surfaceTriangulator.Update() #clippedSurface = vtk.vtkPolyData() #clippedSurface.DeepCopy(surfaceTriangulator.GetOutput()) clippedSurface = surfaceTriangulator.GetOutput() self.Surface = clippedSurface if self.OwnRenderer: self.vmtkRenderer.Deallocate()
def addVoxels( ugrid, verbose=1): myVTK.myPrint(verbose, "*** addVoxels ***") n_points = ugrid.GetPoints().GetNumberOfPoints() seed_point = int(n_points/2) point_locator = myVTK.getPointLocator(ugrid) n_closest_points = 100 closest_points = vtk.vtkIdList() point_locator.FindClosestNPoints( n_closest_points, ugrid.GetPoint(seed_point), closest_points) P0 = numpy.array(ugrid.GetPoint(closest_points.GetId(0))) #print "P0 = " + str(P0) P1 = numpy.array(ugrid.GetPoint(closest_points.GetId(1))) #print "P1 = " + str(P1) X = P1-P0 dX = numpy.linalg.norm(X) X /= dX #print "X = " + str(X) #print "dX = " + str(dX) for k_point in xrange(2, n_closest_points): #print "k_point = " + str(k_point) P2 = numpy.array(ugrid.GetPoint(closest_points.GetId(k_point))) Y = P2-P0 dY = numpy.linalg.norm(Y) Y /= dY #print "P2 = " + str(P2) #print "Y = " + str(Y) #print "dY = " + str(dY) #print "numpy.dot(Y, X) = " + str(numpy.dot(Y, X)) if (abs(numpy.dot(Y, X)) < 0.001): Y = P2-P0 dY = numpy.linalg.norm(Y) Y /= dY break #print "Y = " + str(Y) #print "dY = " + str(dY) Z = numpy.cross(X, Y) dZ_list = [] for k_point in xrange(2, n_closest_points): #print "k_point = " + str(k_point) P3 = numpy.array(ugrid.GetPoint(closest_points.GetId(k_point))) ZZ = P3-P0 dZ = numpy.linalg.norm(ZZ) ZZ /= dZ #print "P3 = " + str(P3) #print "ZZ = " + str(ZZ) #print "dZ = " + str(dZ) #print "numpy.dot(ZZ, Z) = " + str(numpy.dot(ZZ, Z)) if (abs(numpy.dot(ZZ, Z)) > 0.999): dZ_list.append(dZ) dZ = min(dZ_list) #print "Z = " + str(Z) #print "dZ = " + str(dZ) #print "numpy.dot(Y, X) = " + str(numpy.dot(Y, X)) #print "numpy.dot(Z, X) = " + str(numpy.dot(Z, X)) #print "numpy.dot(Z, Y) = " + str(numpy.dot(Z, Y)) points = vtk.vtkPoints() point_locator = vtk.vtkPointLocator() point_locator.InitPointInsertion(points, ugrid.GetBounds()) radius = min(dX, dY, dZ)/2 cell = vtk.vtkHexahedron() cell_array = vtk.vtkCellArray() for k_point in xrange(n_points): P = numpy.array(ugrid.GetPoint(k_point)) point_ids = [] for pm_Z in [-1,+1]: for pm_Y in [-1,+1]: if (pm_Y == -1): pm_X_list = [-1,+1] elif (pm_Y == +1): pm_X_list = [+1,-1] for pm_X in pm_X_list: PP = P + pm_Z * (dZ/2) * Z + pm_Y * (dY/2) * Y + pm_X * (dX/2) * X if (points.GetNumberOfPoints() == 0): point_id = point_locator.InsertNextPoint(PP) else: point_id = point_locator.FindClosestInsertedPoint(PP) dist = numpy.linalg.norm(points.GetPoint(point_id)-PP) if (dist > radius): point_id = point_locator.InsertNextPoint(PP) #point_id = point_locator.IsInsertedPoint(PP) #if (point_id == -1): #point_id = point_locator.InsertNextPoint(PP) point_ids.append(point_id) for i in xrange(8): cell.GetPointIds().SetId(i, point_ids[i]) cell_array.InsertNextCell(cell) new_ugrid = vtk.vtkUnstructuredGrid() new_ugrid.SetPoints(points) new_ugrid.SetCells(vtk.VTK_HEXAHEDRON, cell_array) n_arrays = ugrid.GetPointData().GetNumberOfArrays() for k_array in xrange(n_arrays): new_ugrid.GetCellData().AddArray(ugrid.GetPointData().GetArray(k_array)) return new_ugrid
def Right(self,a,b): self.splineExists = 1 # build locator self.locator = vtk.vtkPointLocator() self.locator.SetDataSet( self.spline.GetVtkPolyData() )
def GetClosestProfilePoint(self,worldPoint, spline): pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet( spline.GetVtkPolyData() ) return pointLocator.FindClosestPoint( worldPoint )
def VoronoiDiagramInterpolation(interpolationcellid,id0,id1,voronoiDataset0,voronoiDataset1,centerlines,direction): print 'Interpolating cells ',id0,id1 cellLine = ExtractLine(interpolationcellid,centerlines) startPoint = clippingPoints.GetPoint(id0) endPoint = clippingPoints.GetPoint(id1) startId = cellLine.FindPoint(startPoint) endId = cellLine.FindPoint(endPoint) if (direction == 1): gapStartId = startId + 1 gapEndId = endId - 1 arrivalId = gapEndId + 1 endSavingInterval = gapEndId + 1 step = 1 else: gapStartId = startId - 1 gapEndId = endId + 1 arrivalId = gapEndId - 1 endSavingInterval = gapEndId - 1 step = -1 numberOfGapPoints = int(math.fabs(gapEndId - gapStartId)) + 1 numberOfInterpolationPoints = voronoiDataset0.GetNumberOfPoints() numberOfCenterlinesPoints = cellLine.GetNumberOfPoints() numberOfAddedPoints = numberOfGapPoints*numberOfInterpolationPoints print 'from id ',gapStartId,'to id ',gapEndId,'; number of points added ',numberOfAddedPoints finalNewVoronoiPoints = vtk.vtkPoints() cellArray = vtk.vtkCellArray() finalRadiusArray = vtk.vtkDoubleArray() finalRadiusArray.SetNumberOfComponents(1) finalRadiusArray.SetNumberOfTuples(numberOfAddedPoints) finalRadiusArray.SetName(radiusArrayName) finalRadiusArray.FillComponent(0,0.0) count = 0 for i in range(numberOfInterpolationPoints): voronoiPoint = voronoiDataset0.GetPoint(i) voronoiPointRadius = voronoiDataset0.GetPointData().GetArray(radiusArrayName).GetTuple1(i) centerlinePointLocator = vtk.vtkPointLocator() centerlinePointLocator.SetDataSet(cellLine) centerlinePointLocator.BuildLocator() closestPointId = centerlinePointLocator.FindClosestPoint(voronoiPoint) closestPoint = cellLine.GetPoint(closestPointId) voronoiVector = [0.0,0.0,0.0] voronoiVector[0] = voronoiPoint[0] - closestPoint[0] voronoiVector[1] = voronoiPoint[1] - closestPoint[1] voronoiVector[2] = voronoiPoint[2] - closestPoint[2] voronoiVectorNorm = vtk.vtkMath.Norm(voronoiVector) rotationAngle = ComputeVoronoiVectorToCenterlineAngle(closestPointId,voronoiVector,cellLine) PTPoints = vtk.vtkPoints() for j in range(closestPointId,arrivalId,step): localtangent = [0.0,0.0,0.0] localnormal = [0.0,0.0,0.0] newVoronoiVector = [0.0,0.0,0.0] newVoronoiPoint = [0.0,0.0,0.0] transform = vtk.vtkTransform() point0 = [0.0,0.0,0.0] point0 = cellLine.GetPoint(j) if (j<numberOfCenterlinesPoints-1): point1 = [0.0,0.0,0.0] cellLine.GetPoint(j+1,point1) localtangent[0] += point1[0] - point0[0] localtangent[1] += point1[1] - point0[1] localtangent[2] += point1[2] - point0[2] if (j>0): point2 = [0.0,0.0,0.0] cellLine.GetPoint(j-1,point2) localtangent[0] += point0[0] - point2[0] localtangent[1] += point0[1] - point2[1] localtangent[2] += point0[2] - point2[2] localnormal = cellLine.GetPointData().GetArray(parallelTransportNormalsArrayName).GetTuple3(j) localnormaldot = vtk.vtkMath.Dot(localtangent,localnormal) localtangent[0] -= localnormaldot*localnormal[0] localtangent[1] -= localnormaldot*localnormal[1] localtangent[2] -= localnormaldot*localnormal[2] vtk.vtkMath.Normalize(localtangent) transform.RotateWXYZ(rotationAngle,localtangent) transform.TransformNormal(localnormal,newVoronoiVector) vtk.vtkMath.Normalize(newVoronoiVector) newVoronoiPoint[0] = point0[0] + voronoiVectorNorm*newVoronoiVector[0] newVoronoiPoint[1] = point0[1] + voronoiVectorNorm*newVoronoiVector[1] newVoronoiPoint[2] = point0[2] + voronoiVectorNorm*newVoronoiVector[2] PTPoints.InsertNextPoint(newVoronoiPoint) numberOfPTPoints = PTPoints.GetNumberOfPoints() lastPTPoint = PTPoints.GetPoint(PTPoints.GetNumberOfPoints()-1) voronoiPointLocator = vtk.vtkPointLocator() voronoiPointLocator.SetDataSet(voronoiDataset1) voronoiPointLocator.BuildLocator() arrivalVoronoiPointId = voronoiPointLocator.FindClosestPoint(lastPTPoint) arrivalVoronoiPoint = voronoiDataset1.GetPoint(arrivalVoronoiPointId) arrivalVoronoiPointRadius = voronoiDataset1.GetPointData().GetArray(radiusArrayName).GetTuple1(arrivalVoronoiPointId) arrivalCenterlinePointLocator = vtk.vtkPointLocator() arrivalCenterlinePointLocator.SetDataSet(cellLine) arrivalCenterlinePointLocator.BuildLocator() arrivalCenterlineClosestPointId = arrivalCenterlinePointLocator.FindClosestPoint(arrivalVoronoiPoint) arrivalCenterlineClosestPoint = cellLine.GetPoint(arrivalCenterlineClosestPointId) arrivalVoronoiVector = [0.0,0.0,0.0] arrivalVoronoiVector[0] = arrivalVoronoiPoint[0] - arrivalCenterlineClosestPoint[0] arrivalVoronoiVector[1] = arrivalVoronoiPoint[1] - arrivalCenterlineClosestPoint[1] arrivalVoronoiVector[2] = arrivalVoronoiPoint[2] - arrivalCenterlineClosestPoint[2] arrivalVoronoiVectorNorm = vtk.vtkMath.Norm(arrivalVoronoiVector) radiusArray = ComputeSpline(voronoiPointRadius,arrivalVoronoiPointRadius,numberOfPTPoints) vectorNormArray = ComputeSpline(voronoiVectorNorm,arrivalVoronoiVectorNorm, numberOfPTPoints) if (direction==1): pointsToGap = gapStartId - closestPointId else: pointsToGap = closestPointId - gapStartId pointId = pointsToGap for k in range(gapStartId,endSavingInterval,step): ptpoint = PTPoints.GetPoint(pointsToGap) clpoint = cellLine.GetPoint(k) vector = [0.0,0.0,0.0] vector[0] = ptpoint[0] - clpoint[0] vector[1] = ptpoint[1] - clpoint[1] vector[2] = ptpoint[2] - clpoint[2] vtk.vtkMath.Normalize(vector) norm = vectorNormArray.GetTuple1(pointsToGap) newvector = [0.0,0.0,0.0] newvector[0] = norm*vector[0] newvector[1] = norm*vector[1] newvector[2] = norm*vector[2] newpoint = [0.0,0.0,0.0] newpoint[0] = clpoint[0] + newvector[0] newpoint[1] = clpoint[1] + newvector[1] newpoint[2] = clpoint[2] + newvector[2] finalNewVoronoiPoints.InsertNextPoint(newpoint) cellArray.InsertNextCell(1) cellArray.InsertCellPoint(count) finalRadiusArray.SetTuple1(count,radiusArray.GetTuple1(pointsToGap)) pointsToGap +=1 count +=1 return finalNewVoronoiPoints,finalRadiusArray
def findclosestpoint(polydata, refpoint): """Returns pointid of point on polydata closest to refpoint.""" locator = vtk.vtkPointLocator() locator.SetDataSet(polydata) locator.BuildLocator() return locator.FindClosestPoint(refpoint)
def Execute(self): if self.Surface == None: self.PrintError('Error: no Surface.') triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInput(self.Surface) triangleFilter.Update() self.Surface = triangleFilter.GetOutput() if self.Loop == None: self.PrintError('Error: no Loop.') select = vtk.vtkImplicitSelectionLoop() select.SetLoop(self.Loop.GetPoints()) normal = [0.0,0.0,0.0] centroid = [0.0,0.0,0.0] vtk.vtkPolygon().ComputeNormal(self.Loop.GetPoints(),normal) #compute centroid and check normals p = [0.0,0.0,0.0] for i in range (self.Loop.GetNumberOfPoints()): p = self.Loop.GetPoint(i) centroid[0] += p[0] centroid[1] += p[1] centroid[2] += p[2] centroid[0] = centroid[0] / self.Loop.GetNumberOfPoints() centroid[1] = centroid[1] / self.Loop.GetNumberOfPoints() centroid[2] = centroid[2] / self.Loop.GetNumberOfPoints() print "loop centroid", centroid locator = vtk.vtkPointLocator() locator.SetDataSet(self.Surface) locator.AutomaticOn() locator.BuildLocator() idsurface = locator.FindClosestPoint(centroid) if (self.Surface.GetPointData().GetNormals() == None): normalsFilter = vmtkscripts.vmtkSurfaceNormals() normalsFilter.Surface = self.Surface normalsFilter.NormalsArrayName = 'Normals' normalsFilter.Execute() self.Surface = normalsFilter.Surface normalsurface = [0.0,0.0,0.0] self.Surface.GetPointData().GetNormals().GetTuple(idsurface,normalsurface) print "loop normal: ", normal print "surface normal inside the loop: ", normalsurface check = vtk.vtkMath.Dot(normalsurface,normal) if check < 0: normal[0] = - normal[0] normal[1] = - normal[1] normal[2] = - normal[2] #compute plane proj = float(vtk.vtkMath.Dot(self.Loop.GetPoint(0),normal)) point = [0.0,0.0,0.0] self.Loop.GetPoint(0,point) for i in range (self.Loop.GetNumberOfPoints()): tmp = vtk.vtkMath.Dot(self.Loop.GetPoint(i),normal) if tmp < proj: proj = tmp self.Loop.GetPoint(i,point) origin = [0.0,0.0,0.0] origin[0] = point[0] #- normal[0] origin[1] = point[1] #- normal[1] origin[2] = point[2] #- normal[2] plane=vtk.vtkPlane() plane.SetNormal(normal[0],normal[1],normal[2]) plane.SetOrigin(origin[0],origin[1],origin[2]) #set bool Bool = vtk.vtkImplicitBoolean() Bool.SetOperationTypeToDifference() Bool.AddFunction(select) Bool.AddFunction(plane) clipper=vtk.vtkClipPolyData() clipper.SetInput(self.Surface) clipper.SetClipFunction(Bool) clipper.GenerateClippedOutputOn() clipper.InsideOutOff() clipper.Update() self.Surface = clipper.GetOutput()
def createData(self, currentTimepoint): """ Create a test dataset within the parameters defined """ x,y,z = self.parameters["X"], self.parameters["Y"], self.parameters["Z"] if self.modified: print "Creating the time series data" self.createTimeSeries() if self.parameters["CreateAll"]: n = min(self.parameters["CacheAmount"], self.parameters["Time"]) for i in range(0, n): if i == currentTimepoint: print "Won't create timepoint %d, it'll be last"%i continue self.createData(i) print "\n\nGenerating timepoint %d"%currentTimepoint if currentTimepoint in self.imageCache: print "Returning cached image" return self.imageCache[currentTimepoint] print "Allocating image" if self.parameters["CreateNoise"]: print "Creating background noise" noiseSource = vtk.vtkImageNoiseSource() noiseSource.SetWholeExtent(0,x-1,0,y-1,0,z-1) noiseSource.SetMinimum(self.parameters["BackgroundNoiseMin"]) noiseSource.SetMaximum(self.parameters["BackgroundNoiseMax"]) castFilter = vtk.vtkImageCast() castFilter.SetOutputScalarTypeToUnsignedChar() castFilter.SetInputConnection(noiseSource.GetOutputPort()) information = vtk.vtkImageChangeInformation() information.SetInputConnection(castFilter.GetOutputPort()) information.SetOutputSpacing(self.spacing) image = information.GetOutput() image.Update() else: image = vtk.vtkImageData() image.SetScalarTypeToUnsignedChar() x,y,z = self.parameters["X"], self.parameters["Y"], self.parameters["Z"] image.SetDimensions((x,y,z)) image.AllocateScalars() image.SetSpacing(self.spacing) print "Initializing image" for iz in range(0,z): for iy in range(0,y): for ix in range(0,x): image.SetScalarComponentFromDouble(ix,iy,iz,0,0) if self.parameters["CreateNoise"]: noisePercentage = self.parameters["ShotNoiseAmount"] noiseAmount = (noisePercentage/100.0) * (x*y*z) print "Creating shot noise" else: noiseAmount = 0 shotNoiseMin = self.parameters["ShotNoiseMin"] shotNoiseMax = self.parameters["ShotNoiseMax"] shotNoiseDistr = self.parameters["ShotNoiseDistribution"] while noiseAmount > 0: rx,ry,rz = random.randint(0,x-1), random.randint(0,y-1), random.randint(0,z-1) shotInt = self.generateDistributionValue(shotNoiseDistr, shotNoiseMin, shotNoiseMax) image.SetScalarComponentFromDouble(rx,ry,rz,0,shotInt) noiseAmount -= 1 #shiftx, shifty, shiftz = self.shifts[currentTimepoint] print "Creating objects",currentTimepoint for oIter, (objN, (rx,ry,rz), size, objInt) in enumerate(self.objects[currentTimepoint]): #rx += shiftx #ry += shifty #rz += shiftz (rx,ry,rz), realSize, intList, voxelList = self.createObjectAt(image, rx,ry,rz, size, objInt) objMean, objStd, objStdErr = lib.Math.meanstdeverr(intList) # Change possible new size and com to object self.objects[currentTimepoint][oIter] = (objN, (rx,ry,rz), realSize, (objMean, objStdErr), voxelList) if self.parameters["ObjectsCreateSource"]: locator = vtk.vtkOBBTree() locator.SetDataSet(self.polydata) locator.BuildLocator() pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(self.polydata) pointLocator.BuildLocator() objPolyTP = [] for objN, (cx, cy, cz), size, meanInt, voxelList in self.objects[currentTimepoint]: cxs = cx * self.spacing[0] cys = cy * self.spacing[1] czs = cz * self.spacing[2] locatorInside = locator.InsideOrOutside((cxs,cys,czs)) if locatorInside == -1: inside = 1 else: inside = 0 percVoxelsInside = 0.0 numIn = 0 for (vx,vy,vz) in voxelList: vxs = vx * self.spacing[0] vys = vy * self.spacing[1] vzs = vz * self.spacing[2] locatorInside = locator.InsideOrOutside((vxs,vys,vzs)) if locatorInside == -1: numIn += 1 percVoxelsInside = float(numIn) / len(voxelList) objid = pointLocator.FindClosestPoint((cxs, cys, czs)) x2,y2,z2 = self.polydata.GetPoint(objid) x2 /= self.spacing[0] y2 /= self.spacing[1] z2 /= self.spacing[2] distToSurf = self.distance((cx,cy,cz), (x2,y2,z2), self.voxelSize) distToCom = self.distance((cx,cy,cz), self.cellCOM, self.voxelSize) objPolyTP.append((objN, (cx,cy,cz), distToSurf, distToCom, inside, percVoxelsInside)) self.objPolydata[currentTimepoint] = objPolyTP n = len(self.imageCache.items()) if n > self.parameters["CacheAmount"]: items = self.imageCache.keys() items.sort() print "Removing ", items[0], "from cache" self.imageCache[items[0]].ReleaseData() del self.imageCache[items[0]] self.imageCache[currentTimepoint] = image self.progressObj.setProgress(currentTimepoint/self.parameters["Time"]) self.updateProgress(None, "ProgressEvent") return image
202: 43, 203: 44, } draw_folding = True folding = vtk.vtkPolyData() folding_on_surface = vtk.vtkPolyData() folding_on_plane = vtk.vtkPolyData() foldingActor = vtk.vtkActor() folding_to_kq = {} if draw_folding: folding_pts_on_plane = vtk.vtkPoints() folding_pts_on_surface = vtk.vtkPoints() pts = vtk.vtkPoints() cells = vtk.vtkCellArray() folding_pts_locator = vtk.vtkPointLocator() folding_pts_locator.InitPointInsertion(pts, [-10, 10, -10, 10, -10, 10]) foldingScalars = vtk.vtkIntArray() plane_to_folding = {} for iPlanePoly in range(plane.GetNumberOfPolys()): if not iPlanePoly in plane_ids: continue for iPt in range(7): iPtOnPlane = plane.GetCell(iPlanePoly).GetPointId(iPt) on_plane = plane.GetPoint(iPtOnPlane) iPtOnFolding = folding_pts_locator.IsInsertedPoint(on_plane) if iPtOnFolding == -1: iPtOnFolding = folding_pts_locator.InsertNextPoint(on_plane) folding_pts_on_plane.InsertNextPoint(on_plane) folding_pts_on_surface.InsertNextPoint(surface.GetPoint(plane_to_kq[iPtOnPlane])) plane_to_folding[int(iPtOnPlane)] = iPtOnFolding