def opyfBuildLocatorandStuff2D(X): # Create points array which are positions to probe data with # FindClosestPoint(), We also create an array to hold the results of this # probe operation and # This array is the same array since we want to find the closest neighbor # The strategy will be to find the 2 closest point since one of them will be the same point # And we consider the second one, the farthest npPoints = X points = vtk.vtkPoints() points.SetDataTypeToDouble() probePoints = vtk.vtkPoints() probePoints.SetDataTypeToDouble() for [x, y] in npPoints: points.InsertNextPoint(x, y, 0.) probePoints.InsertNextPoint(x, y, 0.) polydata = vtk.vtkPolyData() polydata.SetPoints(points) points.ComputeBounds() staticLocator = vtk.vtkStaticPointLocator() staticLocator.SetDataSet(polydata) staticLocator.SetNumberOfPointsPerBucket(5) staticLocator.AutomaticOn() staticLocator.BuildLocator() return staticLocator, points, probePoints
def get_data_vtk(self, points_interpol, interpolation_method="linear"): """ Get interpolated data for points_interpol using vtks built-in interpolation methods """ kernels = { "voronoi": vtk.vtkVoronoiKernel(), "gaussian": vtk.vtkGaussianKernel(), "shepard": vtk.vtkShepardKernel(), "linear": vtk.vtkLinearKernel() } pointnumpyarray = np.array( [points_interpol[pt] for pt in points_interpol]) out_u_grid = vtk.vtkUnstructuredGrid() r = vtk.vtkPoints() r.SetData(numpy_to_vtk(pointnumpyarray)) out_u_grid.SetPoints(r) locator = vtk.vtkStaticPointLocator() locator.SetDataSet(self.output) locator.BuildLocator() interpolator = vtk.vtkPointInterpolator() interpolator.SetInputData(out_u_grid) interpolator.SetSourceData(self.output) interpolator.SetKernel(kernels[interpolation_method]) interpolator.SetLocator(locator) interpolator.Update() return interpolator.GetOutput().GetPointData()
def get_vtk_point_locator(centerline): """Wrapper for vtkStaticPointLocator. Args: centerline (vtkPolyData): Input vtkPolyData. Returns: locator (vtkStaticPointLocator): Point locator of the input surface. """ locator = vtk.vtkStaticPointLocator() locator.SetDataSet(centerline) locator.BuildLocator() return locator
def showPointCloud(modelNodeID): model = slicer.mrmlScene.GetNodeByID(modelNodeID) polydata = model.GetPolyData() # Reuse the locator locator = vtk.vtkStaticPointLocator() locator.SetDataSet(polydata) locator.BuildLocator() # Remove isolated points removal = vtk.vtkRadiusOutlierRemoval() removal.SetInputData(polydata) removal.SetLocator(locator) removal.SetRadius(10) removal.SetNumberOfNeighbors(2) removal.GenerateOutliersOn() # Time execution timer = vtk.vtkTimerLog() timer.StartTimer() removal.Update() timer.StopTimer() time = timer.GetElapsedTime() print("Time to remove points: {0}".format(time)) print(" Number removed: {0}".format(removal.GetNumberOfPointsRemoved()), " (out of: {}".format(polydata.GetNumberOfPoints())) # First output are the non-outliers remMapper = vtk.vtkPointGaussianMapper() remMapper.SetInputConnection(removal.GetOutputPort()) remMapper.EmissiveOff() remMapper.SetScaleFactor(0.0) remActor = vtk.vtkActor() remActor.SetMapper(remMapper) lm = slicer.app.layoutManager() tdWidget = lm.threeDWidget(0) tdView = tdWidget.threeDView() rWin = tdView.renderWindow() rCollection = rWin.GetRenderers() renderer = rCollection.GetItemAsObject(0) # Add the actors to the renderer, set the background and size # renderer.AddActor(remActor)
def findClosestPointsTwoLists(X_source, X_target): '''return the closest points indexes in X_source from the X_target points, indexes output has the same length than X_target''' listPoints = X_source points = vtk.vtkPoints() points.SetDataTypeToDouble() listProbePoints = X_target probePoints = vtk.vtkPoints() probePoints.SetDataTypeToDouble() for [x, y] in listPoints: points.InsertNextPoint(x, y, 0.) for [x, y] in listProbePoints: probePoints.InsertNextPoint(x, y, 0.) polydata = vtk.vtkPolyData() polydata.SetPoints(points) points.ComputeBounds() staticLocator = vtk.vtkStaticPointLocator() staticLocator.SetDataSet(polydata) staticLocator.SetNumberOfPointsPerBucket(5) staticLocator.AutomaticOn() staticLocator.BuildLocator() staticClosestN = vtk.vtkIdList() ind = np.zeros(len(X_target), dtype=np.int) D = np.zeros(len(X_target)) math = vtk.vtkMath() x = [0, 0, 0] p = [0, 0, 0] staticClosestN = vtk.vtkIdList() for i in range(len(X_target)): staticLocator.FindClosestNPoints(1, probePoints.GetPoint(i), staticClosestN) ind[i] = staticClosestN.GetId(0) # we then select the closest point points.GetPoint(ind[i], x) probePoints.GetPoint(i, p) D[i] = math.Distance2BetweenPoints(x, p)**0.5 return ind, D
def opyfBuildLocatorandStuff3D(X): npPoints = X points = vtk.vtkPoints() points.SetDataTypeToDouble() probePoints = vtk.vtkPoints() probePoints.SetDataTypeToDouble() for [x, y, z] in npPoints: points.InsertNextPoint(x, y, z) probePoints.InsertNextPoint(x, y, z) polydata = vtk.vtkPolyData() polydata.SetPoints(points) points.ComputeBounds() staticLocator = vtk.vtkStaticPointLocator() staticLocator.SetDataSet(polydata) staticLocator.SetNumberOfPointsPerBucket(5) staticLocator.AutomaticOn() staticLocator.BuildLocator() return staticLocator, points, probePoints
locator.FindClosestNPoints(10, probePoints.GetPoint(0), closestN) # Time the deletion of the locator. The incremental locator is quite slow due # to fragmented memory. timer.StartTimer() del locator timer.StopTimer() time2 = timer.GetElapsedTime() totalTime = time + opTime + time2 print(" Delete Point Locator: {0}".format(time2)) print(" Point Locator (Total): {0}".format(totalTime)) print("\n") # StaticPointLocator # Time the creation of static point locator staticLocator = vtk.vtkStaticPointLocator() staticLocator.SetDataSet(polydata) staticLocator.SetNumberOfPointsPerBucket(5) staticLocator.AutomaticOn() staticTimer = vtk.vtkTimerLog() staticTimer.StartTimer() staticLocator.BuildLocator() staticTimer.StopTimer() StaticTime = staticTimer.GetElapsedTime() print("Build Static Point Locator: {0}".format(StaticTime)) # Now probe the dataset with FindClosestPoint() math.RandomSeed(314159) staticTimer.StartTimer() for i in range (0,numProbes):
output = pl3d.GetOutput().GetBlock(0) # Create a probe volume center = output.GetCenter() bounds = output.GetBounds() length = output.GetLength() probe = vtk.vtkImageData() probe.SetDimensions(res,res,res) probe.SetOrigin(bounds[0],bounds[2],bounds[4]) probe.SetSpacing((bounds[1]-bounds[0])/(res-1), (bounds[3]-bounds[2])/(res-1), (bounds[5]-bounds[4])/(res-1)) # Reuse the locator locator = vtk.vtkStaticPointLocator() locator.SetDataSet(output) locator.BuildLocator() # Use a gaussian kernel------------------------------------------------ gaussianKernel = vtk.vtkGaussianKernel() gaussianKernel.SetRadius(0.5) gaussianKernel.SetSharpness(4) print ("Radius: {0}".format(gaussianKernel.GetRadius())) interpolator = vtk.vtkPointInterpolator() interpolator.SetInputData(probe) interpolator.SetSourceData(output) interpolator.SetKernel(gaussianKernel) interpolator.SetLocator(locator) interpolator.SetNullPointsStrategyToClosestPoint()
def opyfFindBlobs3D(scalars, th1, th2=None, R=1., minArea=None, CenterType='barycenter'): if th2 is None: th2 = np.max(scalars) [h, w, p] = scalars.shape scalars = scalars.T.copy() scalars = scalars.ravel() # (scalars>=th1)*(scalars<=th2) # indth=np.where((scalars>=th1)*(scalars<=th2)) # Points XYZ x, y, z = np.mgrid[0:h, 0:w, 0:p] pts = np.empty(z.shape + (3, ), dtype=float) pts[..., 0] = x pts[..., 1] = y pts[..., 2] = z pts = pts.transpose(2, 1, 0, 3).copy() pts.shape = pts.size / 3, 3 # VTK points = vtk.vtkPoints() points.SetDataTypeToDouble() for [x, y, z] in pts: points.InsertNextPoint(x, y, z) Scalarsvtk = vtk.vtkFloatArray() for s in scalars: Scalarsvtk.InsertNextValue(s) Ids = vtk.vtkIdList() polydata = vtk.vtkPolyData() # polydata=vtk.vtkUnstructuredGrid() polydata.SetPoints(points) polydata.GetPointData().SetScalars(Scalarsvtk) ThresholdIn = vtk.vtkThresholdPoints() ThresholdIn.SetInputData(polydata) # ThresholdIn.ThresholdByLower(230.) ThresholdIn.ThresholdBetween(th1, th2) ThresholdIn.Update() PointsThresh = ThresholdIn.GetOutput().GetPoints() staticLocator = vtk.vtkStaticPointLocator() staticLocator.SetDataSet(ThresholdIn.GetOutput()) staticLocator.SetNumberOfPointsPerBucket(5) staticLocator.AutomaticOn() staticLocator.BuildLocator() S = ThresholdIn.GetOutput().GetPointData().GetArray(0) nppointsArr = vtk_to_numpy(S) idspointsThresh = np.arange(0, PointsThresh.GetNumberOfPoints()) entitiy = 0 i = idspointsThresh[0] idsStored = np.array([]) ids1 = [0] C = 1 blob3D = [] indstore = 0 while len(idspointsThresh) > 0: C = 1 while C == 1: ids2 = [] l = len(idsStored) for i in ids1: PointswhithinRadius = vtk.vtkIdList() staticLocator.FindPointsWithinRadius(R, PointsThresh.GetPoint(i), PointswhithinRadius) for j in range(PointswhithinRadius.GetNumberOfIds()): tempid = PointswhithinRadius.GetId(j) if len(np.where(idsStored == tempid)[0]) == 0: idsStored = np.append(idsStored, np.int(tempid)) ids2.append(tempid) indDel = np.where(idspointsThresh == tempid) idspointsThresh = np.delete(idspointsThresh, indDel, 0) if len(idsStored) == l: C = 0 blob3D.append(idsStored[indstore:].astype(int)) indstore = len(idsStored) entitiy += 1 if len(idspointsThresh) > 0: ids1 = [idspointsThresh[0]] else: ids1 = ids2 C = np.zeros((len(blob3D), 3)) AreaBlob = [] X = vtk_to_numpy(PointsThresh.GetData()) blob3Dout = [] for i in range(len(blob3D)): ind = blob3D[i] Xblob = X[ind] blob3Dout.append(Xblob) pxInts = nppointsArr[ind] if CenterType == 'barycenter': C[i, :] = np.sum(Xblob * np.array([pxInts, pxInts, pxInts]).T, axis=0) / (np.sum(pxInts)) elif CenterType == 'geometric': C[i, :] = np.sum(Xblob, axis=0) / (np.float(len(pxInts))) AreaBlob.append(len(Xblob)) AreaBlob = np.array(AreaBlob) blob3Dout = np.array(blob3Dout) if minArea is not None: C = C[np.where(AreaBlob > minArea)] blob3Dout = blob3Dout[np.where(AreaBlob > minArea)] AreaBlob = AreaBlob[np.where(AreaBlob > minArea)] return blob3Dout, C, AreaBlob
# Create an initial set of points and associated dataset rpts = vtk.vtkPointSource() rpts.SetNumberOfPoints(numPts) rpts.SetDistributionToUniform() rpts.SetRadius(1) rpts.Update() polydata = rpts.GetOutput() # Print initial statistics print("Processing NumPts: {0}".format(numPts)) timer = vtk.vtkTimerLog() # Create the locator. sclean = vtk.vtkStaticPointLocator() sclean.SetDataSet(polydata) timer.StartTimer() sclean.BuildLocator() timer.StopTimer() time = timer.GetElapsedTime() print("Build Static Point Locator (threaded): {0}".format(time)) print("Number of Divisions: ", sclean.GetDivisions()) # Create a comparison point locator. clean = vtk.vtkPointLocator() clean.SetDataSet(polydata) timer.StartTimer() clean.BuildLocator()
def npInterpolateVTK3D(npPoints, npValues, npTargetPoints, ParametreInterpolatorVTK=None): if ParametreInterpolatorVTK == None: ParametreInterpolatorVTK = { 'kernel': 'Gaussian', 'Radius': 10., 'Sharpness': 2. } print('[' + ParametreInterpolatorVTK['kernel'] + ' Interpolation - Radius =' + str(ParametreInterpolatorVTK['Radius']) + ' - Sharpness =' + str(ParametreInterpolatorVTK['Sharpness']) + '] processing... ') # # Set Source Points UnGrid = vtk.vtkUnstructuredGrid() vtkP = vtk.vtkPoints() for [x, y, z] in npPoints: vtkP.InsertNextPoint(x, y, z) UnGrid.SetPoints(vtkP) # Set source Point Values l, c = npValues.shape for i in range(0, c): vtkFA = vtk.vtkFloatArray() vtkFA.SetName('Values' + str(i)) for v in npValues: vtkFA.InsertNextValue(v[i]) UnGrid.GetPointData().AddArray(vtkFA) # Set Target Points vtkTP = vtk.vtkPoints() for [x, y, z] in npTargetPoints: vtkTP.InsertNextPoint(x, y, z) vtkTargetPointsPolyData = vtk.vtkPolyData() vtkTargetPointsPolyData.SetPoints(vtkTP) if ParametreInterpolatorVTK['kernel'] == 'Gaussian': Kernel = vtk.vtkGaussianKernel() Kernel.SetSharpness(ParametreInterpolatorVTK['Sharpness']) Kernel.SetRadius(ParametreInterpolatorVTK['Radius']) if ParametreInterpolatorVTK['kernel'] == 'Voronoi': Kernel = vtk.vtkVoronoiKernel() if ParametreInterpolatorVTK['kernel'] == 'Shepard': Kernel = vtk.vtkShepardKernel() Kernel.SetRadius(ParametreInterpolatorVTK['Radius']) # Build locator locator = vtk.vtkStaticPointLocator() locator.SetDataSet(UnGrid) locator.BuildLocator() # build interpolator interp = vtk.vtkPointInterpolator() interp.SetInputData(vtkTargetPointsPolyData) interp.SetSourceData(UnGrid) interp.SetKernel(Kernel) interp.SetLocator(locator) interp.GetLocator().SetNumberOfPointsPerBucket(5) interp.SetNullPointsStrategyToMaskPoints() interp.Update() outputInterp = interp.GetOutput() pointsArr = outputInterp.GetPoints().GetData() nppointsArr = vtk_to_numpy(pointsArr) pdata = outputInterp.GetPointData() # Convert volocities into Numpy Array npOutputValues = np.zeros((len(npTargetPoints), c)) for i in range(0, c): vtkOutputValues = pdata.GetArray('Values' + str(i)) npOutputValues[:, i] = vtk_to_numpy(vtkOutputValues) return npOutputValues
# serve as starting points that shoot rays towards the # center of the fist sphere. # sphere = vtk.vtkSphereSource() sphere.SetThetaResolution(2 * res) sphere.SetPhiResolution(res) sphere.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(sphere.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) # Now the locator loc = vtk.vtkStaticPointLocator() loc.SetDataSet(sphere.GetOutput()) loc.SetNumberOfPointsPerBucket(5) loc.BuildLocator() locPD = vtk.vtkPolyData() loc.GenerateRepresentation(4, locPD) locMapper = vtk.vtkPolyDataMapper() locMapper.SetInputData(locPD) locActor = vtk.vtkActor() locActor.SetMapper(locMapper) locActor.GetProperty().SetRepresentationToWireframe() # Now the outer sphere sphere2 = vtk.vtkSphereSource() sphere2.SetThetaResolution(res)
def interpolate_data(self, points, disp, stretch=None, shear=None, on_deformed=True, kernel_radius=3.0, kernel_sharpness=1.0, remove_null=True, return_deformed=True): """ Interpolate data on the mesh. This can be used for comparing experimental and simulation data together. on_deform selects whether to interpolate the data on the original or on the deformed configuration """ if stretch is None: stretch = np.array([]) if shear is None: shear = np.array([]) # We need nPts*3 data for vtk if points.shape[1] == 2: points_ = np.zeros([points.shape[0], 3]) points_[:,0:2] = points # Deform data if needed if on_deformed: points_[:,0:2] = points + disp # Generate vtk points structure with all data vtkpoints = vtk.vtkPoints() vtkpoints.SetData(numpy_support.numpy_to_vtk(points_)) vtkdisp = vtk.vtkDoubleArray() vtkdisp.SetName("disp") vtkdisp.SetNumberOfComponents(disp.shape[1]) vtkdisp.SetNumberOfTuples(disp.shape[0]) vtkdisp.SetVoidArray(disp.flatten(), disp.size, 1) vtkstretch = vtk.vtkDoubleArray() vtkstretch.SetName("stretch") vtkstretch.SetNumberOfComponents(1) vtkstretch.SetNumberOfTuples(stretch.size) vtkstretch.SetVoidArray(stretch, stretch.size, 1) shear = shear.reshape([-1, 4]) vtkshear = vtk.vtkDoubleArray() vtkshear.SetName("shear") vtkshear.SetNumberOfComponents(shear.shape[1]) vtkshear.SetNumberOfTuples(shear.shape[0]) vtkshear.SetVoidArray(shear, shear.size, 1) vtkpointset = vtk.vtkPolyData() vtkpointset.SetPoints(vtkpoints) vtkpointset.GetPointData().AddArray(vtkdisp) vtkpointset.GetPointData().AddArray(vtkstretch) vtkpointset.GetPointData().AddArray(vtkshear) # Build the locator for the interpolation locator = vtk.vtkStaticPointLocator() locator.SetDataSet(vtkpointset) locator.BuildLocator() # Build the Gaussian kernel kernel = vtk.vtkGaussianKernel() kernel.SetKernelFootprint(0) kernel.SetRadius(kernel_radius) kernel.SetSharpness(kernel_sharpness) # If the interpolation is performed on the deformed configuration, warp the data if on_deformed: disp_ = np.zeros(self.x_nodes.shape) disp_[:,0:2] = self.disp warpData = vtk.vtkDoubleArray() warpData.SetName("warp") warpData.SetNumberOfComponents(3) warpData.SetNumberOfTuples(self.x_nodes.shape[0]) warpData.SetVoidArray(disp_, self.x_nodes.shape[0], 1) self.vtkmesh.GetPointData().AddArray(warpData) self.vtkmesh.GetPointData().SetActiveVectors(warpData.GetName()) warpVector = vtk.vtkWarpVector() warpVector.SetInputData(self.vtkmesh) warpVector.Update() self.vtkmesh = warpVector.GetOutput() coarseInterpolator = vtk.vtkPointInterpolator() coarseInterpolator.SetSourceData(vtkpointset) coarseInterpolator.SetInputData(self.vtkmesh) coarseInterpolator.SetKernel(kernel) coarseInterpolator.SetLocator(locator) coarseInterpolator.PassPointArraysOff() coarseInterpolator.SetNullPointsStrategyToMaskPoints() # Get points with an invalid interpolation coarseInterpolator.Update() vtkmesh = coarseInterpolator.GetOutput() if return_deformed: self.x_nodes[:,0:2] += self.disp self.disp = numpy_support.vtk_to_numpy(vtkmesh.GetPointData().GetArray("disp")) self.stretch = numpy_support.vtk_to_numpy(vtkmesh.GetPointData().GetArray("stretch")) self.shear = numpy_support.vtk_to_numpy(vtkmesh.GetPointData().GetArray("shear")) if remove_null: not_null = (numpy_support.vtk_to_numpy(vtkmesh.GetPointData().GetArray( coarseInterpolator.GetValidPointsMaskArrayName()))).astype(bool) idlist_old = np.arange(self.x_nodes.shape[0])[not_null] self.x_nodes = self.x_nodes[not_null] self.disp = self.disp[not_null] self.stretch = self.stretch[not_null] self.shear = self.shear[not_null] idlist_new = np.arange(self.x_nodes.shape[0]) c1 = np.in1d(self.connec[:, 0], idlist_old) c2 = np.in1d(self.connec[:, 1], idlist_old) c3 = np.in1d(self.connec[:, 2], idlist_old) self.connec = self.connec[np.logical_and(np.logical_and(c1,c2),c3)] for i in idlist_new: self.connec[self.connec == idlist_old[i]] = i points = vtk.vtkPoints() points.SetData(numpy_support.numpy_to_vtk(self.x_nodes)) vtkmesh.SetPoints(points) cells = vtk.vtkCellArray() cells.SetCells(self.connec.shape[0], numpy_support.numpy_to_vtkIdTypeArray(self.connec)) vtkmesh.SetPolys(cells) self.shear = self.shear.reshape([-1, 2, 2])