def clipSurfacesForFullLVMesh(endo, epi, verbose=0): myVTK.myPrint(verbose, "*** clipSurfacesForFullLVMesh ***") endo_implicit_distance = vtk.vtkImplicitPolyDataDistance() endo_implicit_distance.SetInput(endo) epi_implicit_distance = vtk.vtkImplicitPolyDataDistance() epi_implicit_distance.SetInput(epi) epi_clip = vtk.vtkClipPolyData() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): epi_clip.SetInputData(epi) else: epi_clip.SetInput(epi) epi_clip.SetClipFunction(endo_implicit_distance) epi_clip.GenerateClippedOutputOn() epi_clip.Update() clipped_epi = epi_clip.GetOutput(0) clipped_valve = epi_clip.GetOutput(1) endo_clip = vtk.vtkClipPolyData() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): endo_clip.SetInputData(endo) else: endo_clip.SetInput(endo) endo_clip.SetClipFunction(epi_implicit_distance) endo_clip.InsideOutOn() endo_clip.Update() clipped_endo = endo_clip.GetOutput(0) return (clipped_endo, clipped_epi, clipped_valve)
def clipSurfacesForFullLVMesh(endo, epi, verbose=1): myVTK.myPrint(verbose, "*** clipSurfacesForFullLVMesh ***") endo_implicit_distance = vtk.vtkImplicitPolyDataDistance() endo_implicit_distance.SetInput(endo) epi_implicit_distance = vtk.vtkImplicitPolyDataDistance() epi_implicit_distance.SetInput(epi) epi_clip = vtk.vtkClipPolyData() epi_clip.SetInputData(epi) epi_clip.SetClipFunction(endo_implicit_distance) epi_clip.GenerateClippedOutputOn() epi_clip.Update() clipped_epi = epi_clip.GetOutput(0) clipped_valve = epi_clip.GetOutput(1) endo_clip = vtk.vtkClipPolyData() endo_clip.SetInputData(endo) endo_clip.SetClipFunction(epi_implicit_distance) endo_clip.InsideOutOn() endo_clip.Update() clipped_endo = endo_clip.GetOutput(0) return (clipped_endo, clipped_epi, clipped_valve)
def clipSurfacesForCutLVMesh( endo, epi, height, verbose=1): myVTK.myPrint(verbose, "*** clipSurfacesForCutLVMesh ***") plane = vtk.vtkPlane() plane.SetNormal(0,0,-1) plane.SetOrigin(0,0,height) clip = vtk.vtkClipPolyData() clip.SetClipFunction(plane) clip.SetInputData(endo) clip.Update() clipped_endo = clip.GetOutput(0) clip = vtk.vtkClipPolyData() clip.SetClipFunction(plane) clip.SetInputData(epi) clip.Update() clipped_epi = clip.GetOutput(0) return (clipped_endo, clipped_epi)
def clipSurfacesForCutLVMesh(endo, epi, height, verbose=0): myVTK.myPrint(verbose, "*** clipSurfacesForCutLVMesh ***") plane = vtk.vtkPlane() plane.SetNormal(0, 0, -1) plane.SetOrigin(0, 0, height) clip = vtk.vtkClipPolyData() clip.SetClipFunction(plane) if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): clip.SetInputData(endo) else: clip.SetInput(endo) clip.Update() clipped_endo = clip.GetOutput(0) clip = vtk.vtkClipPolyData() clip.SetClipFunction(plane) if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): clip.SetInputData(epi) else: clip.SetInput(epi) clip.Update() clipped_epi = clip.GetOutput(0) return (clipped_endo, clipped_epi)
def clipSurfacesForFullBiVMesh(pdata_endLV, pdata_endRV, pdata_epi, verbose=0): myVTK.myPrint(verbose, "*** clipSurfacesForFullBiVMesh ***") pdata_endLV_implicit_distance = vtk.vtkImplicitPolyDataDistance() pdata_endLV_implicit_distance.SetInput(pdata_endLV) pdata_endRV_implicit_distance = vtk.vtkImplicitPolyDataDistance() pdata_endRV_implicit_distance.SetInput(pdata_endRV) pdata_epi_implicit_distance = vtk.vtkImplicitPolyDataDistance() pdata_epi_implicit_distance.SetInput(pdata_epi) pdata_endLV_clip = vtk.vtkClipPolyData() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): pdata_endLV_clip.SetInputData(pdata_endLV) else: pdata_endLV_clip.SetInput(pdata_endLV) pdata_endLV_clip.SetClipFunction(pdata_epi_implicit_distance) pdata_endLV_clip.InsideOutOn() pdata_endLV_clip.Update() clipped_pdata_endLV = pdata_endLV_clip.GetOutput(0) pdata_endRV_clip = vtk.vtkClipPolyData() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): pdata_endRV_clip.SetInputData(pdata_endRV) else: pdata_endRV_clip.SetInput(pdata_endRV) pdata_endRV_clip.SetClipFunction(pdata_epi_implicit_distance) pdata_endRV_clip.InsideOutOn() pdata_endRV_clip.Update() clipped_pdata_endRV = pdata_endRV_clip.GetOutput(0) pdata_epi_clip = vtk.vtkClipPolyData() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): pdata_epi_clip.SetInputData(pdata_epi) else: pdata_epi_clip.SetInput(pdata_epi) pdata_epi_clip.SetClipFunction(pdata_endLV_implicit_distance) pdata_epi_clip.GenerateClippedOutputOn() pdata_epi_clip.Update() clipped_pdata_epi = pdata_epi_clip.GetOutput(0) clipped_valM = pdata_epi_clip.GetOutput(1) pdata_epi_clip = vtk.vtkClipPolyData() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): pdata_epi_clip.SetInputData(clipped_pdata_epi) else: pdata_epi_clip.SetInput(clipped_pdata_epi) pdata_epi_clip.SetClipFunction(pdata_endRV_implicit_distance) pdata_epi_clip.GenerateClippedOutputOn() pdata_epi_clip.Update() clipped_pdata_epi = pdata_epi_clip.GetOutput(0) clipped_valP = pdata_epi_clip.GetOutput(1) return (clipped_pdata_endLV, clipped_pdata_endRV, clipped_pdata_epi, clipped_valM, clipped_valP)
def contours(self, i, ct_image, isovalue, cmap): contour = vtk.vtkContourFilter() contour.SetInputConnection(self.ct_image.GetOutputPort()); contour.ComputeNormalsOn() contour.SetValue(0, isovalue) color_fun = vtk.vtkColorTransferFunction() color_fun.SetColorSpaceToRGB() color_fun.AddRGBPoint(isovalue, cmap[0], cmap[1],cmap[2]) clipper_x = vtk.vtkClipPolyData() clipper_x.SetClipFunction(self.plane_x) clipper_x.SetInputConnection(contour.GetOutputPort()) clipper_y = vtk.vtkClipPolyData() clipper_y.SetClipFunction(self.plane_y) clipper_y.SetInputConnection(clipper_x.GetOutputPort()) clipper_z = vtk.vtkClipPolyData() clipper_z.SetClipFunction(self.plane_z) clipper_z.SetInputConnection(clipper_y.GetOutputPort()) probe_filter = vtk.vtkProbeFilter() probe_filter.SetSourceConnection(self.gm_image.GetOutputPort()) probe_filter.SetInputConnection(clipper_z.GetOutputPort()) gmin = self.gimin[i] gmax = self.gimax[i] gm_clipper_min = vtk.vtkClipPolyData() gm_clipper_min.SetInputConnection(probe_filter.GetOutputPort()) gm_clipper_min.InsideOutOff() gm_clipper_min.SetValue(gmin) gm_clipper_max = vtk.vtkClipPolyData() gm_clipper_max.SetInputConnection(gm_clipper_min.GetOutputPort()) gm_clipper_max.InsideOutOn() gm_clipper_max.SetValue(int(gmax)) color_mapper = vtk.vtkPolyDataMapper() color_mapper.SetLookupTable(color_fun) color_mapper.SetInputConnection(gm_clipper_max.GetOutputPort()) color_mapper.SetScalarRange(gm_clipper_max.GetOutput().GetScalarRange()) color_actor=vtk.vtkActor() color_actor.GetProperty().SetOpacity(cmap[3]) color_actor.SetMapper(color_mapper) self.clipper_X.append(clipper_x) self.clipper_Y.append(clipper_x) self.clipper_Z.append(clipper_x) return color_actor
def generate_actors(data, gradient_magnitude, iso_values, cmap, clip): # contour iso = vtk.vtkContourFilter() iso.SetInputConnection(data.GetOutputPort()) if (iso_values): [ iso.SetValue(index, value) for (index, value) in enumerate(iso_values) ] else: iso.SetValue(0, max / 4) #probe probe = vtk.vtkProbeFilter() probe.SetInputConnection(iso.GetOutputPort()) probe.SetSourceConnection(gradient_magnitude.GetOutputPort()) # generate vtkPlanes stuff. origins = generate_plane_origins(clip) normals = generate_plane_normals() # the list of planes planes = vtk.vtkPlanes() planes.SetPoints(origins) planes.SetNormals(normals) planes.GetPlane(0, xplane) planes.GetPlane(1, yplane) planes.GetPlane(2, zplane) xclipper = vtk.vtkClipPolyData() xclipper.SetInputConnection(probe.GetOutputPort()) xclipper.SetClipFunction(xplane) yclipper = vtk.vtkClipPolyData() yclipper.SetInputConnection(xclipper.GetOutputPort()) yclipper.SetClipFunction(yplane) zclipper = vtk.vtkClipPolyData() zclipper.SetInputConnection(yclipper.GetOutputPort()) zclipper.SetClipFunction(zplane) ctf = generate_ctf(cmap) clipMapper = vtk.vtkDataSetMapper() clipMapper.SetLookupTable(ctf) clipMapper.SetInputConnection(zclipper.GetOutputPort()) clipMapper.SetScalarRange(0, 255) # Generate iso surface actor from iso surface mapper. isoActor = vtk.vtkActor() isoActor.SetMapper(clipMapper) return [isoActor]
def clipSurfacesForFullBiVMesh( pdata_endLV, pdata_endRV, pdata_epi, verbose=1): myVTK.myPrint(verbose, "*** clipSurfacesForFullBiVMesh ***") pdata_endLV_implicit_distance = vtk.vtkImplicitPolyDataDistance() pdata_endLV_implicit_distance.SetInput(pdata_endLV) pdata_endRV_implicit_distance = vtk.vtkImplicitPolyDataDistance() pdata_endRV_implicit_distance.SetInput(pdata_endRV) pdata_epi_implicit_distance = vtk.vtkImplicitPolyDataDistance() pdata_epi_implicit_distance.SetInput(pdata_epi) pdata_endLV_clip = vtk.vtkClipPolyData() pdata_endLV_clip.SetInputData(pdata_endLV) pdata_endLV_clip.SetClipFunction(pdata_epi_implicit_distance) pdata_endLV_clip.InsideOutOn() pdata_endLV_clip.Update() clipped_pdata_endLV = pdata_endLV_clip.GetOutput(0) pdata_endRV_clip = vtk.vtkClipPolyData() pdata_endRV_clip.SetInputData(pdata_endRV) pdata_endRV_clip.SetClipFunction(pdata_epi_implicit_distance) pdata_endRV_clip.InsideOutOn() pdata_endRV_clip.Update() clipped_pdata_endRV = pdata_endRV_clip.GetOutput(0) pdata_epi_clip = vtk.vtkClipPolyData() pdata_epi_clip.SetInputData(pdata_epi) pdata_epi_clip.SetClipFunction(pdata_endLV_implicit_distance) pdata_epi_clip.GenerateClippedOutputOn() pdata_epi_clip.Update() clipped_pdata_epi = pdata_epi_clip.GetOutput(0) clipped_valM = pdata_epi_clip.GetOutput(1) pdata_epi_clip = vtk.vtkClipPolyData() pdata_epi_clip.SetInputData(clipped_pdata_epi) pdata_epi_clip.SetClipFunction(pdata_endRV_implicit_distance) pdata_epi_clip.GenerateClippedOutputOn() pdata_epi_clip.Update() clipped_pdata_epi = pdata_epi_clip.GetOutput(0) clipped_valP = pdata_epi_clip.GetOutput(1) return (clipped_pdata_endLV, clipped_pdata_endRV, clipped_pdata_epi, clipped_valM, clipped_valP)
def createBreastModel(self, breastBound, InputModel, breastFlag, reverseNormal, setInsideOut, plane, planeWithSplineTransform): # Creates the cropped breast model from the original input model and the created warped posterior wall of the breast # Clip the input model with the breast boundary loop to isolate the breast clippedBreastModel = vtk.vtkClipPolyData() clippedBreastModel.SetClipFunction(breastBound) clippedBreastModel.SetInputData(InputModel) # This value below may need to be changed clippedBreastModel.SetInsideOut(True) clippedBreastModel.Update() # Now use the vtkPolyDataConnectivityFilter to extract the largest region connectedBreastModel = vtk.vtkPolyDataConnectivityFilter() connectedBreastModel.SetInputConnection(clippedBreastModel.GetOutputPort()) connectedBreastModel.SetExtractionModeToLargestRegion() connectedBreastModel.Update() # linearly extrude the breast model to ensure the final surface will be airtight extrudeBreastModel = vtk.vtkLinearExtrusionFilter() extrudeBreastModel.SetInputConnection(connectedBreastModel.GetOutputPort()) extrudeBreastModel.SetScaleFactor(100) extrudeBreastModel.CappingOn() normVec = plane.GetNormal() if breastFlag == True: normVec = [normVec[0] * -1, normVec[1] * -1, normVec[2] * -1] if reverseNormal == True: normVec = [normVec[0] * -1, normVec[1] * -1, normVec[2] * -1] extrudeBreastModel.SetVector(normVec) extrudeBreastModel.Update() # create implicit representation of the plane transformed with the spline implictSplinePlane = vtk.vtkImplicitPolyDataDistance() implictSplinePlane.SetInput(planeWithSplineTransform.GetOutput()) # Now re-clip the now air-tight breast model wit the curved surface breastModel = vtk.vtkClipPolyData() breastModel.SetClipFunction(implictSplinePlane) breastModel.SetInputConnection(extrudeBreastModel.GetOutputPort()) # This value below may need to be changed if setInsideOut == True: breastModel.SetInsideOut(True) else: breastModel.SetInsideOut(False) breastModel.Update() return breastModel.GetOutput()
def clipping_skin_with_sphere(contour_filter_leg): """ Makes an actor for the leg which cuts it using a clipper The goal here is to make a boolean difference between the leg and a sphere placed on the knee area. :param contour_filter_leg: The raw SLC data for the leg :return: Leg cut actor, and the sphere """ sphere = vtk.vtkSphere() sphere.SetRadius(50) sphere.SetCenter(75, 40, 110) clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(contour_filter_leg.GetOutputPort()) clipper.SetClipFunction(sphere) clipper.SetValue(0) clipper.Update() mapper = vtk.vtkDataSetMapper() mapper.SetInputData(clipper.GetOutput()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.GetProperty().SetColor(colors.GetColor3d("SkinColor")) actor.SetMapper(mapper) return actor, sphere
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkClipPolyData(), 'Processing.', ('vtkPolyData',), ('vtkPolyData', 'vtkPolyData'), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def __init__(self): # POINTS self.points = vtk.vtkPoints() self.cell = vtk.vtkCellArray() self.poly = vtk.vtkPolyData() self.poly.SetPoints(self.points) self.poly.SetVerts(self.cell) # mapper = vtk.vtkPolyDataMapper() # mapper.SetInputData(self.poly) # self.actor = vtk.vtkActor() # self.actor.SetMapper(mapper) # CLIP box = vtk.vtkBox() box.SetBounds(0, 1, 0, 1, 0, 1) self.clipper = vtk.vtkClipPolyData() self.clipper.SetInputData(self.poly) self.clipper.SetClipFunction(box) self.clipper.Update() mapper_in = vtk.vtkPolyDataMapper() mapper_in.SetInputConnection(self.clipper.GetOutputPort(1)) actor_in = vtk.vtkActor() actor_in.SetMapper(mapper_in) actor_in.GetProperty().SetColor(1, 0, 0) mapper_out = vtk.vtkPolyDataMapper() mapper_out.SetInputConnection(self.clipper.GetOutputPort(0)) actor_out = vtk.vtkActor() actor_out.SetMapper(mapper_out) actor_out.GetProperty().SetColor(0, 1, 0) self.actor = vtk.vtkAssembly() self.actor.AddPart(actor_in) self.actor.AddPart(actor_out) for i in range(10000): self.points_grown_up()
def SphereDrill(self, m_holelist, m_holeRadius, m_quiet=False): """ Drill sphere at locations specified by m_holelist. :param m_holelist: [list] A list of coordinates where holes are to be drilled :param m_holeRadius: [float] The radius of the hole to drill :param m_quiet: [bool] :return: """ m_totalNumOfHoles = len(m_holelist) if not m_quiet: t = time.time() print "Drilling" for i in xrange(m_totalNumOfHoles): m_sphere = vtk.vtkSphere() m_sphere.SetCenter(m_holelist[i]) m_sphere.SetRadius(m_holeRadius) clipper = vtk.vtkClipPolyData() clipper.SetInputData(self._data) clipper.SetClipFunction(m_sphere) clipper.Update() clipped = clipper.GetOutput() self._data.DeepCopy(clipped) if not m_quiet: print "\t%s/%s -- %.2f %%" % (i + 1, m_totalNumOfHoles, (i + 1) * 100 / float(m_totalNumOfHoles)) if not m_quiet: print "Finished: Totaltime used = %.2f s" % (time.time() - t) pass
def cut_with_planes(obj): #This function take a obj (vtk source) and cuts it with a plane defined by normal and point. num_cuts = 40 rad_tol = 0.5 point_min = obj.GetRadius() - rad_tol points = vtkPoints() normals = vtkDoubleArray() normals.SetNumberOfComponents(3) for i in range(num_cuts): normal = make_rand_vector() point = (point_min + np.random.rand(3) * rad_tol/2) * np.sign(normal) normals.InsertNextTuple(normal) points.InsertNextPoint(*point) #Create vtkPlanes object: planes = vtkPlanes() planes.SetPoints(points) planes.SetNormals(normals) #Create clipper object: clipper = vtkClipPolyData() clipper.SetInputConnection(obj.GetOutputPort()) clipper.SetClipFunction(planes) #Cut in the positive side of the plane: # clipper.SetValue(0) clipper.InsideOutOn() clipper.Update() #Returned as cut vtkPolyData: return clipper.GetOutput()
def _Clip(self, pd): # The plane implicit function will be >0 for all the points in the positive side # of the plane (i.e. x s.t. n.(x-o)>0, where n is the plane normal and o is the # plane origin). plane = vtkPlane() plane.SetOrigin(self.Iolet.Centre.x, self.Iolet.Centre.y, self.Iolet.Centre.z) plane.SetNormal(self.Iolet.Normal.x, self.Iolet.Normal.y, self.Iolet.Normal.z) # The sphere implicit function will be >0 for all the points outside the sphere. sphere = vtkSphere() sphere.SetCenter(self.Iolet.Centre.x, self.Iolet.Centre.y, self.Iolet.Centre.z) sphere.SetRadius(self.Iolet.Radius) # The VTK_INTERSECTION operator takes the maximum value of all the registered # implicit functions. This will result in the function evaluating to >0 for all # the points outside the sphere plus those inside the sphere in the positive # side of the plane. clippingFunction = vtkImplicitBoolean() clippingFunction.AddFunction(plane) clippingFunction.AddFunction(sphere) clippingFunction.SetOperationTypeToIntersection() clipper = vtkClipPolyData() clipper.SetInput(pd) clipper.SetClipFunction(clippingFunction) # Filter to get part closest to seed point connectedRegionGetter = vtkPolyDataConnectivityFilter() connectedRegionGetter.SetExtractionModeToClosestPointRegion() connectedRegionGetter.SetClosestPoint(*self.SeedPoint) connectedRegionGetter.SetInputConnection(clipper.GetOutputPort()) connectedRegionGetter.Update() return connectedRegionGetter.GetOutput()
def vtk_clip_polydata(surface, cutter=None, value=0, get_inside_out=False, generate_clip_scalars=False): """Clip the input vtkPolyData object with a cutter function (plane, box, etc) Args: generate_clip_scalars (bool): If True, output scalar values will be interpolated from implicit function values. get_inside_out (bool): Get inside out, default is False surface (vtkPolyData): Input vtkPolyData for clipping cutter (vtkBox, vtkPlane): Function for cutting the polydata (default None). value (float): Distance to the ImplicteFunction or scalar value to clip. Returns: clipper (vtkPolyData): The clipped surface """ clipper = vtk.vtkClipPolyData() clipper.SetInputData(surface) if cutter is None: clipper.GenerateClipScalarsOff() else: clipper.SetClipFunction(cutter) if get_inside_out: clipper.InsideOutOn() if generate_clip_scalars and cutter is not None: clipper.GenerateClipScalarsOn() clipper.GenerateClippedOutputOn() clipper.SetValue(value) clipper.Update() return clipper.GetOutput(), clipper.GetClippedOutput()
def __init__(self, parent=None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() superquadricSource = vtk.vtkSuperquadricSource() superquadricSource.SetPhiRoundness(3.1) superquadricSource.SetThetaRoundness(2.2) clipPlane = vtk.vtkPlane() clipPlane.SetNormal(1.0, -1.0, -1.0) clipPlane.SetOrigin(0, 0, 0) clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(superquadricSource.GetOutputPort()) clipper.SetClipFunction(clipPlane) superquadricMapper = vtk.vtkPolyDataMapper() superquadricMapper.SetInputConnection(clipper.GetOutputPort()) superquadricActor = vtk.vtkActor() superquadricActor.SetMapper(superquadricMapper) #create renderers and add actors of plane and cube self.ren.AddActor(superquadricActor) self.ren.ResetCamera() self._initialized = False
def CLIPPED_LINE(self, Slice, pSource, pTarget, Norm1, centroid_slice): time_0 = TIME() #Get the two in-plane normals Norm2_slice = (pSource - centroid_slice ) / np.linalg.norm(pSource - centroid_slice) Norm3_slice = np.cross(Norm1, Norm2_slice) #Generate the two planes plane_N2 = vtk.vtkPlane() plane_N2.SetOrigin(centroid_slice) plane_N2.SetNormal(Norm2_slice) plane_N3 = vtk.vtkPlane() plane_N3.SetOrigin(centroid_slice) plane_N3.SetNormal(Norm3_slice) #Clip the plane to get a line across the diameter Line = vtk.vtkCutter() Line.GenerateTrianglesOff() Line.SetCutFunction(plane_N3) Line.SetInputData(Slice) Line.Update() #Separate the line into only one quarter (i.e. half the line) Line1 = vtk.vtkClipPolyData() Line1.SetClipFunction(plane_N2) Line1.SetInputData(Line.GetOutput()) Line1.Update() Line1_data = Line1.GetOutput() del plane_N2, plane_N3, Line, Line1 time_ = TIME() - time_0 return Line1_data, time_
def cut_brain_hemi(hemi_elec_data, hemi_poly_data): depth_elec_data = hemi_elec_data[(hemi_elec_data.eType == 'D') | (hemi_elec_data.eType == 'd')] print depth_elec_data print x_coords = np.array([avg_surf.x_snap for avg_surf in depth_elec_data.avgSurf], dtype=np.float) y_coords = np.array([avg_surf.y_snap for avg_surf in depth_elec_data.avgSurf], dtype=np.float) z_coords = np.array([avg_surf.z_snap for avg_surf in depth_elec_data.avgSurf], dtype=np.float) x_min, x_max = np.min(x_coords), np.max(x_coords) y_min, y_max = np.min(y_coords), np.max(y_coords) z_min, z_max = np.min(z_coords), np.max(z_coords) clipPlane = vtk.vtkPlane() clipPlane.SetNormal(0.0, 0.0, 1.0) # clipPlane.SetOrigin(0, 0, np.max(z_coords)) # clipPlane.SetOrigin(np.max(x_coords), np.max(y_coords), np.max(z_coords)) clipPlane.SetOrigin(0, 0, -500) clipper = vtk.vtkClipPolyData() clipper.SetInputData(hemi_poly_data) clipper.SetClipFunction(clipPlane) return clipper
def getConnectedVerticesWithinRadius(model, seedPt, radius): connectedPts_list = vtk.vtkIdList() x, y, z = model.GetPoint(seedPt) sphere = vtk.vtkSphere() sphere.SetRadius(radius) sphere.SetCenter(x, y, z) clipper = vtk.vtkClipPolyData() clipper.SetClipFunction(sphere) clipper.SetInputData(model) clipper.GenerateClippedOutputOn() clipper.Update() # slice_writer = vtk.vtkXMLPolyDataWriter() # slice_writer.SetInputData(clipper.GetClippedOutput()) # slice_writer.SetFileName('Region_cut' + '.vtp') # slice_writer.Write() connect = vtk.vtkConnectivityFilter() connect.SetInputData(clipper.GetClippedOutput()) connect.SetExtractionModeToClosestPointRegion() connect.SetClosestPoint(x, y, z) connect.Update() region = connect.GetOutput() for ptID in xrange(0, region.GetNumberOfPoints()): xp, yp, zp = region.GetPoint(ptID) modelpt = model.FindPoint(xp, yp, zp) connectedPts_list.InsertUniqueId(modelpt) return connectedPts_list
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 clipDataSetWithPolygon(vtkDataSet, vtkPoly, returnImpDist=False, insideOut=True, extractBounds=False): """ Function to clips cells from a vtkDataSet, given polygon/s in a vtkPolyData. Returns a clipped cells that fall inside or outside the polygon boundary. """ # Make a implicit function impDist = convertToImplicitPolyDataDistance(vtkPoly) # Reduce the data to the bounds if extractBounds: extBoundsFilt = extractDataSetByBounds(vtkDataSet, vtkPoly) else: extBoundsFilt = extractDataSetByBounds(vtkDataSet, vtkDataSet) if vtkDataSet.IsA('vtkPolyData'): clipFilt = vtk.vtkClipPolyData() else: clipFilt = vtk.vtkClipDataSet() clipFilt.SetInsideOut(insideOut + 0) clipFilt.SetInputConnection(extBoundsFilt.GetOutputPort()) clipFilt.SetClipFunction(impDist) clipFilt.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION) # clipFilt.SetMergeTolerance(0.000001) clipFilt.Update() if returnImpDist: return clipFilt.GetOutput(), impDist else: return clipFilt.GetOutput()
def getClippedPDataUsingPlane(pdata_mesh, plane_O, plane_N, verbose=0): mypy.my_print(verbose, "*** getClippedPDataUsingPlane ***") plane = vtk.vtkPlane() plane.SetOrigin(plane_O) plane.SetNormal(plane_N) #mypy.my_print(verbose-1, "pdata_mesh.GetBounds() = "+str(pdata_mesh.GetBounds())) #mypy.my_print(verbose-1, "plane_O = "+str(plane_O)) #mypy.my_print(verbose-1, "plane_N = "+str(plane_N)) clip = vtk.vtkClipPolyData() clip.SetClipFunction(plane) clip.GenerateClippedOutputOn() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): clip.SetInputData(pdata_mesh) else: clip.SetInput(pdata_mesh) clip.Update() clipped0 = clip.GetOutput(0) clipped1 = clip.GetOutput(1) #mypy.my_print(verbose-1, "clipped0.GetNumberOfPoints() = "+str(clipped0.GetNumberOfPoints())) #mypy.my_print(verbose-1, "clipped1.GetNumberOfPoints() = "+str(clipped1.GetNumberOfPoints())) #mypy.my_print(verbose-1, "clipped0.GetNumberOfCells() = "+str(clipped0.GetNumberOfCells())) #mypy.my_print(verbose-1, "clipped1.GetNumberOfCells() = "+str(clipped1.GetNumberOfCells())) if (clipped0.GetNumberOfCells() > clipped1.GetNumberOfCells()): return clipped0, clipped1 else: return clipped1, clipped0
def getPatch(self, inputModel, inputCurve): # Clip model with curve loop = vtk.vtkSelectPolyData() loop.SetLoop(inputCurve) loop.GenerateSelectionScalarsOn() loop.SetInputData(inputModel) loop.SetSelectionModeToLargestRegion() clip = vtk.vtkClipPolyData() clip.InsideOutOn() clip.SetInputConnection(loop.GetOutputPort()) clip.GenerateClippedOutputOn() clip.Update() extractLargestPart = False clippedOutput = clip.GetOutput( ) if extractLargestPart else clip.GetClippedOutput() connectivity = vtk.vtkConnectivityFilter() connectivity.SetInputData(clippedOutput) connectivity.Update() clippedOutput2 = connectivity.GetOutput() # Remove unused points cleaner = vtk.vtkCleanPolyData() cleaner.SetInputData(clippedOutput2) cleaner.Update() return cleaner.GetOutput()
def AutoClip(self): # Check to see if ClipsIn is provided if self.ClipsIn == None: self.PrintError('Error: no AutoClip without ClipsIn') # Init AutoClipper/Function AutoClipper = vtk.vtkClipPolyData() AutoClipFunction = vtk.vtkPlanes() AutoClipper.SetInputData(self.Surface) AutoClipper.GenerateClippedOutputOn() AutoClipper.SetInsideOut(self.InsideOut) AutoClipper.SetClipFunction(AutoClipFunction) # Perform ClipFunction while ClipsIn is not empty while not self.ClipsIn.GetNumberOfBlocks() == 0: Bounds = self.NextBlockBounds() self.PrintLog('Bounds for AutoClip are: ' + str(Bounds)) AutoClipFunction.SetBounds(Bounds) AutoClipper.Update() self.Surface.DeepCopy(AutoClipper.GetOutput()) import pdb; pdb.set_trace() self.CleanAutoClip() self.PrintLog('AutoClip complete.')
def actor_clip(): sphere = vtk.vtkSphereSource() sphere.SetCenter(1, 1, 1) sphere.SetRadius(1) sphere.Update() box = vtk.vtkBox() box.SetBounds(0, 7, -1, 4, -3, 1) clipper = vtk.vtkClipPolyData() clipper.SetClipFunction(box) clipper.SetInputConnection(sphere.GetOutputPort()) clipper.GenerateClippedOutputOn() clipper.Update() mapper_in = vtk.vtkPolyDataMapper() mapper_in.SetInputConnection(clipper.GetOutputPort(1)) actor_in = vtk.vtkActor() actor_in.SetMapper(mapper_in) actor_in.GetProperty().SetColor(0, 255, 0) actor_in.GetProperty().SetPointSize(2) mapper_out = vtk.vtkPolyDataMapper() mapper_out.SetInputConnection(clipper.GetOutputPort(0)) actor_out = vtk.vtkActor() actor_out.SetMapper(mapper_out) actor_out.GetProperty().SetColor(255, 0, 0) actor_in.GetProperty().SetPointSize(2) return actor_in, actor_out
def generate_actors(data, val, clip): # contour global iso iso.SetInputConnection(data.GetOutputPort()) if (val): iso.SetValue(0, val) else: iso.SetValue(0, max / 4) ctf = vtk.vtkColorTransferFunction() ctf.AddRGBPoint(min, 31 / 255, 162 / 255, 255 / 255) ctf.AddRGBPoint(max, 255 / 255, 251 / 255, 19 / 255) # generate vtkPlanes stuff. origins = generate_plane_origins(clip) normals = generate_plane_normals() # the list of planes planes = vtk.vtkPlanes() planes.SetPoints(origins) planes.SetNormals(normals) planes.GetPlane(0, xplane) planes.GetPlane(1, yplane) planes.GetPlane(2, zplane) xclipper = vtk.vtkClipPolyData() xclipper.SetInputConnection(iso.GetOutputPort()) xclipper.SetClipFunction(xplane) yclipper = vtk.vtkClipPolyData() yclipper.SetInputConnection(xclipper.GetOutputPort()) yclipper.SetClipFunction(yplane) zclipper = vtk.vtkClipPolyData() zclipper.SetInputConnection(yclipper.GetOutputPort()) zclipper.SetClipFunction(zplane) clipMapper = vtk.vtkDataSetMapper() clipMapper.SetLookupTable(ctf) clipMapper.SetInputConnection(zclipper.GetOutputPort()) clipMapper.SetScalarRange(0, 255) # Generate iso surface actor from iso surface mapper. isoActor = vtk.vtkActor() isoActor.SetMapper(clipMapper) return [isoActor]
def Execute(self): if self.Surface == None: self.PrintError('Error: no Surface.') if self.WidgetType == "box": self.ClipFunction = vtk.vtkPlanes() elif self.WidgetType == "sphere": self.ClipFunction = vtk.vtkSphere() self.Clipper = vtk.vtkClipPolyData() self.Clipper.SetInput(self.Surface) self.Clipper.SetClipFunction(self.ClipFunction) self.Clipper.GenerateClippedOutputOn() self.Clipper.InsideOutOn() if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 mapper = vtk.vtkPolyDataMapper() mapper.SetInput(self.Surface) mapper.ScalarVisibilityOff() self.Actor = vtk.vtkActor() self.Actor.SetMapper(mapper) self.vmtkRenderer.Renderer.AddActor(self.Actor) if self.WidgetType == "box": self.ClipWidget = vtk.vtkBoxWidget() self.ClipWidget.GetFaceProperty().SetColor(0.6,0.6,0.2) self.ClipWidget.GetFaceProperty().SetOpacity(0.25) elif self.WidgetType == "sphere": self.ClipWidget = vtk.vtkSphereWidget() self.ClipWidget.GetSphereProperty().SetColor(0.6,0.6,0.2) self.ClipWidget.GetSphereProperty().SetOpacity(0.25) self.ClipWidget.GetSelectedSphereProperty().SetColor(0.6,0.0,0.0) self.ClipWidget.GetSelectedSphereProperty().SetOpacity(0.75) self.ClipWidget.SetRepresentationToSurface() self.ClipWidget.SetPhiResolution(20) self.ClipWidget.SetThetaResolution(20) self.ClipWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.Display() self.Transform = vtk.vtkTransform() self.ClipWidget.GetTransform(self.Transform) if self.OwnRenderer: self.vmtkRenderer.Deallocate() if self.CleanOutput == 1: cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(self.Surface) cleaner.Update() self.Surface = cleaner.GetOutput() if self.Surface.GetSource(): self.Surface.GetSource().UnRegisterAllOutputs()
def Clipper(src, dx, dy, dz): """ Clip a vtkPolyData source. A cube is made whose size corresponds the the bounds of the source. Then each side is shrunk by the appropriate dx, dy or dz. After this operation the source is clipped by the cube. :param: src - the vtkPolyData source :param: dx - the amount to clip in the x-direction :param: dy - the amount to clip in the y-direction :param: dz - the amount to clip in the z-direction :return: vtkPolyData. """ bounds = [0, 0, 0, 0, 0, 0] src.GetBounds(bounds) plane1 = vtk.vtkPlane() plane1.SetOrigin(bounds[0] + dx, 0, 0) plane1.SetNormal(1, 0, 0) plane2 = vtk.vtkPlane() plane2.SetOrigin(bounds[1] - dx, 0, 0) plane2.SetNormal(-1, 0, 0) plane3 = vtk.vtkPlane() plane3.SetOrigin(0, bounds[2] + dy, 0) plane3.SetNormal(0, 1, 0) plane4 = vtk.vtkPlane() plane4.SetOrigin(0, bounds[3] - dy, 0) plane4.SetNormal(0, -1, 0) plane5 = vtk.vtkPlane() plane5.SetOrigin(0, 0, bounds[4] + dz) plane5.SetNormal(0, 0, 1) plane6 = vtk.vtkPlane() plane6.SetOrigin(0, 0, bounds[5] - dz) plane6.SetNormal(0, 0, -1) clipFunction = vtk.vtkImplicitBoolean() clipFunction.SetOperationTypeToUnion() clipFunction.AddFunction(plane1) clipFunction.AddFunction(plane2) clipFunction.AddFunction(plane3) clipFunction.AddFunction(plane4) clipFunction.AddFunction(plane5) clipFunction.AddFunction(plane6) # Clip it. clipper = vtk.vtkClipPolyData() clipper.SetClipFunction(clipFunction) clipper.SetInputData(src) clipper.GenerateClipScalarsOff() clipper.GenerateClippedOutputOff() #clipper.GenerateClippedOutputOn() clipper.Update() return clipper.GetOutput()
def __init__(self): VTKPythonAlgorithmBase.__init__(self, nInputPorts=1, nOutputPorts=1) self.__PlaneOriginAbove = None self.__PlaneNormalAbove = None self.__PlaneOriginBelow = None self.__PlaneNormalBelow = None self.visPlane = [vtk.vtkPlane(), vtk.vtkPlane()] self.planeClipper = [vtk.vtkClipPolyData(), vtk.vtkClipPolyData()] self.planeClipper[1].SetInputConnection( self.planeClipper[0].GetOutputPort()) self.planeClipper[0].SetClipFunction(self.visPlane[0]) self.planeClipper[1].SetClipFunction(self.visPlane[1]) self.planeClipper[0].InsideOutOn() self.planeClipper[1].InsideOutOn()
def Execute(Surface, cl): if Surface == None: print 'Error: no Surface.' sys.exit(0) # Initialize Clipper = vtk.vtkClipPolyData() Clipper.SetInput(Surface) Clipper.GenerateClippedOutputOn() Clipper.SetInsideOut(0) ClipFunction = vtk.vtkPlanes() Clipper.SetClipFunction(ClipFunction) Cutter = vtk.vtkCutter() Cutter.SetInput(Surface) Cutter.SetCutFunction(ClipFunction) ClippedSurface = vtk.vtkPolyData() CutLines = vtk.vtkPolyData() ClipWidget = vtk.vtkBoxWidget() ClipWidget.GetFaceProperty().SetColor(0.6,0.6,0.2) ClipWidget.GetFaceProperty().SetOpacity(0.25) Transform = vtk.vtkTransform() ClipWidget.GetTransform(Transform) for i in range(cl.GetNumberOfLines()): # TODO: Implement thing here. # Clean surface cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(Surface) cleaner.Update() Surface = cleaner.GetOutput() cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(ClippedSurface) cleaner.Update() ClippedSurface = cleaner.GetOutput() cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(CutLines) cleaner.Update() stripper = vtk.vtkStripper() stripper.SetInput(cleaner.GetOutput()) stripper.Update() CutLines = stripper.GetOutput() if Surface.GetSource(): Surface.GetSource().UnRegisterAllOutputs() if __name__=='__main__': surface = read_command_line() Execute()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkClipPolyData(), 'Processing.', ('vtkPolyData', ), ('vtkPolyData', 'vtkPolyData'), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def clipper(inp,clip): clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(inp) clipper.SetClipFunction(clip) planeMapper=vtk.vtkPolyDataMapper() planeMapper.SetInputConnection(clipper.GetOutputPort()) planeActor = vtk.vtkActor() planeActor.SetMapper(planeMapper) return planeActor
def Clipper(src, dx, dy, dz): ''' Clip a vtkPolyData source. A cube is made whose size corresponds the the bounds of the source. Then each side is shrunk by the appropriate dx, dy or dz. After this operation the source is clipped by the cube. :param: src - the vtkPolyData source :param: dx - the amount to clip in the x-direction :param: dy - the amount to clip in the y-direction :param: dz - the amount to clip in the z-direction :return: vtkPolyData. ''' bounds = [0,0,0,0,0,0] src.GetBounds(bounds) plane1 = vtk.vtkPlane() plane1.SetOrigin(bounds[0] + dx, 0, 0) plane1.SetNormal(1, 0, 0) plane2 = vtk.vtkPlane() plane2.SetOrigin(bounds[1] - dx, 0, 0) plane2.SetNormal(-1, 0, 0) plane3 = vtk.vtkPlane() plane3.SetOrigin(0, bounds[2] + dy, 0) plane3.SetNormal(0, 1, 0) plane4 = vtk.vtkPlane() plane4.SetOrigin(0, bounds[3] - dy, 0) plane4.SetNormal(0, -1, 0) plane5 = vtk.vtkPlane() plane5.SetOrigin(0, 0, bounds[4] + dz) plane5.SetNormal(0, 0, 1) plane6 = vtk.vtkPlane() plane6.SetOrigin(0, 0, bounds[5] - dz) plane6.SetNormal(0, 0, -1) clipFunction = vtk.vtkImplicitBoolean() clipFunction.SetOperationTypeToUnion() clipFunction.AddFunction(plane1) clipFunction.AddFunction(plane2) clipFunction.AddFunction(plane3) clipFunction.AddFunction(plane4) clipFunction.AddFunction(plane5) clipFunction.AddFunction(plane6) # Clip it. clipper =vtk.vtkClipPolyData() clipper.SetClipFunction(clipFunction) clipper.SetInputData(src) clipper.GenerateClipScalarsOff() clipper.GenerateClippedOutputOff() #clipper.GenerateClippedOutputOn() clipper.Update() return clipper.GetOutput()
def clip_surface(self, surface, slice_plane): '''Clip a surface. ''' clip_filter = vtk.vtkClipPolyData() clip_filter.SetInputData(surface) clip_filter.GenerateClippedOutputOn() clip_filter.SetClipFunction(slice_plane) clip_filter.Update() return clip_filter.GetOutput()
def _ClipModelNormal(self, plane, surface): """Clips surface""" clipper = vtk.vtkClipPolyData() clipper.SetInputData(surface) clipper.GenerateClipScalarsOn() clipper.GenerateClippedOutputOn() clipper.SetClipFunction(plane) clipper.Update() return clipper
def Execute(self): if (self.Surface == None): self.PrintError('Error: no Surface.') if self.WidgetType == "box": self.ClipFunction = vtk.vtkPlanes() elif self.WidgetType == "sphere": self.ClipFunction = vtk.vtkSphere() self.Clipper = vtk.vtkClipPolyData() self.Clipper.SetInput(self.Surface) self.Clipper.SetClipFunction(self.ClipFunction) self.Clipper.GenerateClippedOutputOn() self.Clipper.InsideOutOn() if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 mapper = vtk.vtkPolyDataMapper() mapper.SetInput(self.Surface) mapper.ScalarVisibilityOff() self.Actor = vtk.vtkActor() self.Actor.SetMapper(mapper) self.vmtkRenderer.Renderer.AddActor(self.Actor) if self.WidgetType == "box": self.ClipWidget = vtk.vtkBoxWidget() self.ClipWidget.GetFaceProperty().SetColor(0.6, 0.6, 0.2) self.ClipWidget.GetFaceProperty().SetOpacity(0.25) elif self.WidgetType == "sphere": self.ClipWidget = vtk.vtkSphereWidget() self.ClipWidget.GetSphereProperty().SetColor(0.6, 0.6, 0.2) self.ClipWidget.GetSphereProperty().SetOpacity(0.25) self.ClipWidget.GetSelectedSphereProperty().SetColor(0.6, 0.0, 0.0) self.ClipWidget.GetSelectedSphereProperty().SetOpacity(0.75) self.ClipWidget.SetRepresentationToSurface() self.ClipWidget.SetPhiResolution(20) self.ClipWidget.SetThetaResolution(20) self.ClipWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.Display() if self.OwnRenderer: self.vmtkRenderer.Deallocate() if self.CleanOutput == 1: cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(self.Surface) cleaner.Update() self.Surface = cleaner.GetOutput() if self.Surface.GetSource(): self.Surface.GetSource().UnRegisterAllOutputs()
def semiTransparent(mcBone, mcSkin): """ Create the semi-transparent visualisation of the skin. A sphere is clipping the skin near the articulation and the front face (as seen from the camera) of the skin is semi-transparent. Args: mcBone: vtkMarchingCubes used to create the bone mcSkin: vtkMarchingCubes used to create the skin Returns: vtkAssembly """ # Create a sphere for clipping sphere = vtk.vtkSphere() sphere.SetCenter(80, 20, 120) sphere.SetRadius(60) # Clip skin with a sphere clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(mcSkin.GetOutputPort()) clipper.SetClipFunction(sphere) clipper.SetValue(1) clipper.Update() # Skin mapper mapperSkin = vtk.vtkDataSetMapper() mapperSkin.SetInputConnection(clipper.GetOutputPort()) mapperSkin.ScalarVisibilityOff() # Opaque back skin actorSkinBack = vtk.vtkActor() actorSkinBack.SetMapper(mapperSkin) actorSkinBack.GetProperty().SetColor(0.95, 0.64, 0.64) actorSkinBack.GetProperty().SetFrontfaceCulling(True) # Transparent front skin actorSkinFront = vtk.vtkActor() actorSkinFront.SetMapper(mapperSkin) actorSkinFront.GetProperty().SetColor(0.95, 0.64, 0.64) actorSkinFront.GetProperty().SetBackfaceCulling(True) actorSkinFront.GetProperty().SetOpacity(0.5) # Bone mapper and actor mapperBone = vtk.vtkDataSetMapper() mapperBone.SetInputConnection(mcBone.GetOutputPort()) mapperBone.ScalarVisibilityOff() actorBone = vtk.vtkActor() actorBone.SetMapper(mapperBone) actorBone.GetProperty().SetColor(0.9, 0.9, 0.9) # Group the actors assembly = vtk.vtkAssembly() assembly.AddPart(actorSkinBack) assembly.AddPart(actorSkinFront) assembly.AddPart(actorBone) return assembly
def __init__(self, parent=None, id=-1, pos=wx.DefaultPosition, title="3D Density"): VizFrame.__init__(self, parent, id, pos, title) self.widget = wxVTKRenderWindowInteractor(self,-1) style = vtk.vtkInteractorStyleTrackballCamera() self.widget.SetInteractorStyle(style) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.1, 0.7) self.widget.GetRenderWindow().AddRenderer(self.ren) self.data = None self.colors = None # layout the frame self.box = wx.BoxSizer(wx.HORIZONTAL) self.leftPanel = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.box) self.box.Add(self.leftPanel,0, wx.EXPAND) self.box.Add(self.widget,1,wx.EXPAND) self.Layout() self.MenuBar = wx.MenuBar() self.FileMenu = wx.Menu() self.GateMenu = wx.Menu() self.MenuBar.Append(self.FileMenu, "File") self.MenuBar.Append(self.GateMenu, "Gating") self.SetMenuBar(self.MenuBar) export = self.FileMenu.Append(-1, "Export graphics") self.Bind(wx.EVT_MENU, self.OnExport, export) self.colorGate = self.GateMenu.Append(-1, "Gate on visible colors only") self.Bind(wx.EVT_MENU, self.GateByColor, self.colorGate) self.colorGate.Enable(False) gate = self.GateMenu.Append(-1, "Capture gated events") self.boxAddMenuItem = self.GateMenu.Append(-1, "Add box gate") self.GateMenu.AppendSeparator() self.boxes = [] self.Bind(wx.EVT_MENU, self.OnBox, self.boxAddMenuItem) self.Bind(wx.EVT_MENU, self.Gate, gate) self.selectActor = vtk.vtkLODActor() self.planes = {} #vtk.vtkPlanes() self.clipper = vtk.vtkClipPolyData() self.boxCount = 1 self.boxIds = {} self.Show() self.SendSizeEvent()
def planeclip(polydata, point, normal, insideout=True): """Clip polydata with a plane defined by point and normal. Change clipping direction with 'insideout' argument.""" clipplane = vtk.vtkPlane() clipplane.SetOrigin(point) clipplane.SetNormal(normal) clipper = vtk.vtkClipPolyData() clipper.SetInput(polydata) clipper.SetClipFunction(clipplane) if insideout: clipper.InsideOutOn() clipper.Update() return clipper.GetOutput()
def _createTube(self): logging.debug("In MultiSliceContour::createTube()") points = vtk.vtkPoints() for point in self._originalPoints: points.InsertNextPoint(point) self._parametricSpline = vtk.vtkParametricSpline() self._parametricSpline.SetPoints(points) self._parametricFuntionSource = vtk.vtkParametricFunctionSource() self._parametricFuntionSource.SetParametricFunction(self._parametricSpline) self._parametricFuntionSource.SetUResolution(100) self._tubeFilter = vtk.vtkTubeFilter() self._tubeFilter.SetNumberOfSides(10) self._tubeFilter.SetRadius(self._radius) self._tubeFilter.SetInputConnection(self._parametricFuntionSource.GetOutputPort()) self._tubeActor = [] self._cubes = [] i = 0 for cutter in self._cutters: cutter.SetInputConnection(self._tubeFilter.GetOutputPort()) cutter.Update() cube = vtk.vtkBox() #TODO change imagebounds to planesourceRange cube.SetBounds(self._scene.slice[i].getBounds()) clip = vtk.vtkClipPolyData() clip.SetClipFunction(cube) clip.SetInputConnection(cutter.GetOutputPort()) clip.InsideOutOn() clip.Update() self._cubes.append(cube) tubeMapper=vtk.vtkPolyDataMapper() tubeMapper.ScalarVisibilityOff() tubeMapper.SetInputConnection(clip.GetOutputPort()) tubeMapper.GlobalImmediateModeRenderingOn() tubeActor = vtk.vtkActor() tubeActor.SetMapper(tubeMapper) tubeActor.GetProperty().LightingOff() tubeActor.GetProperty().SetColor(self.lineColor) tubeActor.SetUserTransform(self._scene.slice[i].resliceTransform.GetInverse()) self._tubeActor.append(tubeActor) self._scene.renderer.AddActor(tubeActor) i = i+1
def planeclip(surface, point, normal, insideout=1): clipplane = vtk.vtkPlane() clipplane.SetOrigin(point) clipplane.SetNormal(normal) clipper = vtk.vtkClipPolyData() clipper.SetInputData(surface) clipper.SetClipFunction(clipplane) if insideout == 1: clipper.InsideOutOn() else: clipper.InsideOutOff() clipper.Update() return clipper.GetOutput()
def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._clipPolyData = vtk.vtkClipPolyData() module_utils.setup_vtk_object_progress(self, self._clipPolyData, 'Calculating normals') NoConfigModuleMixin.__init__( self, {'vtkClipPolyData' : self._clipPolyData}) self.sync_module_logic_with_config()
def doClip1(data,value,normal,axis=0): # We have the actor, do clipping clpf = vtk.vtkPlane() if axis == 0: clpf.SetOrigin(value,0,0) clpf.SetNormal(normal,0,0) else: clpf.SetOrigin(0,value,0) clpf.SetNormal(0,normal,0) clp = vtk.vtkClipPolyData() clp.SetClipFunction(clpf) clp.SetInputData(data) clp.Update() return clp.GetOutput()
def getClippedPDataUsingField(pdata_mesh, array_name, threshold_value, verbose=0): mypy.my_print(verbose, "*** getClippedPDataUsingField ***") pdata_mesh.GetPointData().SetActiveScalars(array_name) clip_poly_data = vtk.vtkClipPolyData() if vtk.vtkVersion.GetVTKMajorVersion() >= 6: clip_poly_data.SetInputData(pdata_mesh) else: clip_poly_data.SetInput(pdata_mesh) clip_poly_data.SetValue(threshold_value) clip_poly_data.GenerateClippedOutputOn() clip_poly_data.Update() return clip_poly_data.GetOutput(0), clip_poly_data.GetOutput(1)
def preprocess_mesh(mesh, num_patches=10): """ This function... :param mesh: :param num_patches: :return: """ # run patching for i in range(num_patches): mesh = patch(mesh) edges2 = vtk.vtkFeatureEdges() edges2.SetInputData(mesh) edges2.FeatureEdgesOff() edges2.NonManifoldEdgesOn() edges2.ManifoldEdgesOff() edges2.BoundaryEdgesOn() edges2.Update() edgesPd = edges2.GetOutput() print( "{0} cells and {1} points".format( edgesPd.GetNumberOfCells(), edgesPd.GetNumberOfPoints() ) ) toDelete = vtk.vtkFloatArray() toDelete.SetNumberOfComponents(1) toDelete.SetNumberOfValues(mesh.GetNumberOfPoints()) for i in range(mesh.GetNumberOfPoints()): toDelete.SetValue(i, 0) for i in range(edgesPd.GetNumberOfPoints()): edgePnt = edgesPd.GetPoint(i) meshVertId = mesh.FindPoint(edgePnt) toDelete.SetValue(meshVertId, 1) mesh.GetPointData().SetScalars(toDelete) clipper = vtk.vtkClipPolyData() clipper.SetValue(0.5) clipper.SetInputData(mesh) clipper.InsideOutOn() clipper.Update() return clipper.GetOutput()
def update_pipeline(self): if self.isoActor is not None: self.renderer.RemoveActor(self.isoActor) pipe = self.marchingCubes if self.useConnect: self.connect.SetInput( pipe.GetOutput()) pipe = self.connect if self.useDecimate: self.deci.SetInput( pipe.GetOutput()) pipe = self.deci if 0: plane = vtk.vtkPlane() clipper = vtk.vtkClipPolyData() polyData = pipe.GetOutput() clipper.SetInput(polyData) clipper.SetClipFunction(plane) clipper.InsideOutOff() pipe = clipper def callback(pw, event): pw.GetPlane(plane) self.interactor.Render() self.planeWidget = vtk.vtkImplicitPlaneWidget() self.planeWidget.SetInteractor(self.interactor) self.planeWidget.On() self.planeWidget.SetPlaceFactor(1.0) self.planeWidget.SetInput(polyData) self.planeWidget.PlaceWidget() self.planeWidget.AddObserver("InteractionEvent", callback) self.isoMapper = vtk.vtkPolyDataMapper() self.isoMapper.SetInput(pipe.GetOutput()) self.isoMapper.ScalarVisibilityOff() self.isoActor = vtk.vtkActor() self.isoActor.SetMapper(self.isoMapper) self.renderer.AddActor(self.isoActor) self.update_properties()
def cutter(self): maxLayers = 0 for model in self.modelDict.values(): if len(model.layerValues) > maxLayers: maxLayers = len(model.layerValues) for model in self.modelDict.values(): i = self.currentIndex if i < 0: i = 0 self.currentIndex = -1 elif i > len(model.layerValues) - 1: i = len(model.layerValues) - 1 # The last layer if len(model.layerValues) > maxLayers: self.currentIndex = maxLayers for actor in [model._actor, model._slice_actor, model._support_actor, model._base_actor]: if actor is not None: actor.GetProperty().SetOpacity(0) for polydata in [model._slice_vtkpolydata, model._support_vtkpolydata, model._base_vtkpolydata]: if polydata is not None: plane = vtk.vtkPlane() plane.SetOrigin(0, 0, model.layerValues[i] -0.005) # some errors if path height is 0.005 plane.SetNormal(0, 0, 1) window = vtk.vtkImplicitWindowFunction() window.SetImplicitFunction(plane) try: pathHeight = float(self.toolDict[str(model._modelMaterial)].pathHeight) except: pathHeight = model.pathHeight # error fix in gcode import window.SetWindowRange(0, pathHeight) clipper = vtk.vtkClipPolyData() clipper.AddInput(polydata) clipper.SetClipFunction(window) clipper.GenerateClippedOutputOn() if self.tubeOn: try: clipActor = self.tubeView(clipper, float(self.toolDict[str(model._modelMaterial)].pathWidth)) except: clipActor = self.tubeView(clipper, pathHeight) # error fix in gcode import else: clipMapper = vtk.vtkPolyDataMapper() clipMapper.SetInputConnection(clipper.GetOutputPort()) clipActor = vtk.vtkActor() clipActor.SetMapper(clipMapper) self.ren.AddActor(clipActor) self.newActors.append(clipActor)
def clipPDataUsingField( pdata_mesh, array_name, threshold_value, verbose=1): myVTK.myPrint(verbose, "*** clipPDataUsingField ***") pdata_mesh.GetPointData().SetActiveScalars(array_name) clip_poly_data = vtk.vtkClipPolyData() clip_poly_data.SetInputData(pdata_mesh) clip_poly_data.SetValue(threshold_value) clip_poly_data.GenerateClippedOutputOn() clip_poly_data.Update() return clip_poly_data.GetOutput(0), clip_poly_data.GetOutput(1)
def test_vtk_clip(fname=None): import explorers import vtk_explorers import vtk if not fname: fname = "info.json" # set up some processing task s = vtk.vtkSphereSource() plane = vtk.vtkPlane() plane.SetOrigin(0, 0, 0) plane.SetNormal(-1, -1, 0) clip = vtk.vtkClipPolyData() clip.SetInputConnection(s.GetOutputPort()) clip.SetClipFunction(plane) clip.GenerateClipScalarsOn() clip.GenerateClippedOutputOn() clip.SetValue(0) m = vtk.vtkPolyDataMapper() m.SetInputConnection(clip.GetOutputPort()) rw = vtk.vtkRenderWindow() r = vtk.vtkRenderer() rw.AddRenderer(r) a = vtk.vtkActor() a.SetMapper(m) r.AddActor(a) #make or open a cinema data store to put results in cs = FileStore(fname) cs.filename_pattern = "{offset}_slice.png" cs.add_descriptor("offset", make_cinema_descriptor_properties('offset', [0,.2,.4,.6,.8,1.0])) #associate control points wlth parameters of the data store g = vtk_explorers.Clip('offset', clip) e = vtk_explorers.ImageExplorer(cs, ['offset'], [g], rw) #run through all parameter combinations and put data into the store e.explore() return e
def create_actor (self, glyph , opacity=1,color=[0.1,0.1,0.1]): ## Adds clipping abilities to the actor clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(glyph.GetOutputPort()) clipper.SetClipFunction(self.planesParticles) clipper.InsideOutOn() mapper=vtk.vtkPolyDataMapper() mapper.SetColorModeToMapScalars() # mapper.SetScalarRange(-700, -400) # This is for val # mapper.SetScalarRange(0, 300) # This is for val mapper.SetScalarRange(self.min_rad,self.max_rad) mapper.SetScalarRange(-500, -200) # if len(color) > 0: # mapper.ScalarVisibilityOn() # #mapper.SetScalarRange(self.min_rad,self.max_rad) # else: # mapper.SetColorModeToDefault() # print color mapper.SetInputConnection(clipper.GetOutputPort()) # mapper.SetInputConnection(glyph.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) if len(color) > 0 : actor.GetProperty().SetColor(color) print "Setting the color of the particles to" print color actor.GetProperty().SetOpacity(opacity) actor.VisibilityOn() self.mapper_list.append(mapper) self.actor_list.append(actor) self.ren.AddActor(actor) self.particles_loaded = True self.particles_added_to_renderer = True return actor
def scalarclip(polydata, arrayname, scalarvalue, insideout=True, ispointdata=True): """Clip vtkPolyData returning regions with value of array above a specified value.""" clipper = vtk.vtkClipPolyData() clipper.SetInput(polydata) if ispointdata: # array is pointdata clipper.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject. FIELD_ASSOCIATION_POINTS, arrayname) else: # array is celldata clipper.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject. FIELD_ASSOCIATION_CELLS, arrayname) clipper.SetValue(scalarvalue) if insideout: # inverse clipping direction clipper.InsideOutOn() clipper.Update() return clipper.GetOutput()
def cylinderclip(dataset, point0, point1,normal,radius): """Define cylinder. The cylinder is infinite in extent. We therefore have to truncate the cylinder using vtkImplicitBoolean in combination with 2 clipping planes located at point0 and point1. The radius of the cylinder is set to be slightly larger than 'maxradius'.""" rotationaxis = cross([0, 1, 0], normal) rotationangle = (180 / math.pi) * angle([0, 1, 0], normal) transform = vtk.vtkTransform() transform.Translate(point0) transform.RotateWXYZ(rotationangle, rotationaxis) transform.Inverse() cylinder = vtk.vtkCylinder() cylinder.SetRadius(radius) cylinder.SetTransform(transform) plane0 = vtk.vtkPlane() plane0.SetOrigin(point0) plane0.SetNormal([-x for x in normal]) plane1 = vtk.vtkPlane() plane1.SetOrigin(point1) plane1.SetNormal(normal) clipfunction = vtk.vtkImplicitBoolean() clipfunction.SetOperationTypeToIntersection() clipfunction.AddFunction(cylinder) clipfunction.AddFunction(plane0) clipfunction.AddFunction(plane1) clipper = vtk.vtkClipPolyData() clipper.SetInputData(dataset) clipper.SetClipFunction(clipfunction) clipper.Update() return extractlargestregion(clipper.GetOutput())
def clipPDataUsingPlane( pdata_mesh, plane_C, plane_N, verbose=1): myVTK.myPrint(verbose, "*** clipPDataUsingPlane ***") plane = vtk.vtkPlane() plane.SetOrigin(plane_C) plane.SetNormal(plane_N) clip = vtk.vtkClipPolyData() clip.SetClipFunction(plane) clip.GenerateClippedOutputOn() clip.SetInputData(pdata_mesh) clip.Update() clipped0 = clip.GetOutput(0) clipped1 = clip.GetOutput(1) if (clipped0.GetNumberOfPoints() > clipped1.GetNumberOfPoints()): return clipped0, clipped1 else: return clipped1, clipped0
def clipPDataUsingPlane( pdata_mesh, plane_O, plane_N, verbose=1): myVTK.myPrint(verbose, "*** clipPDataUsingPlane ***") plane = vtk.vtkPlane() plane.SetOrigin(plane_O) plane.SetNormal(plane_N) #myVTK.myPrint(verbose-1, "pdata_mesh.GetBounds() = "+str(pdata_mesh.GetBounds())) #myVTK.myPrint(verbose-1, "plane_O = "+str(plane_O)) #myVTK.myPrint(verbose-1, "plane_N = "+str(plane_N)) clip = vtk.vtkClipPolyData() clip.SetClipFunction(plane) clip.GenerateClippedOutputOn() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): clip.SetInputData(pdata_mesh) else: clip.SetInput(pdata_mesh) clip.Update() clipped0 = clip.GetOutput(0) clipped1 = clip.GetOutput(1) #myVTK.myPrint(verbose-1, "clipped0.GetNumberOfPoints() = "+str(clipped0.GetNumberOfPoints())) #myVTK.myPrint(verbose-1, "clipped1.GetNumberOfPoints() = "+str(clipped1.GetNumberOfPoints())) #myVTK.myPrint(verbose-1, "clipped0.GetNumberOfCells() = "+str(clipped0.GetNumberOfCells())) #myVTK.myPrint(verbose-1, "clipped1.GetNumberOfCells() = "+str(clipped1.GetNumberOfCells())) if (clipped0.GetNumberOfCells() > clipped1.GetNumberOfCells()): return clipped0, clipped1 else: return clipped1, clipped0
def clip(self, plane): """Clip the surface against the supplied plane, using a vtkClipPolyData filter.""" if self.Clipper is None: self.Clipper = vtk.vtkClipPolyData() self.Clipper.SetInput(self.Clipped) pass # Get the axis-aligned cuboid bounding the surface bounds = self.Surface.GetBounds() # (xmin,xmax, ymin,ymax, zmin,zmax) planes = vtk.vtkPlanes() planes.SetBounds(*bounds) # Iterate over BB, find plane with closest normal, replace # with our plane. maxDot = -1; maxI = -1 for i in range(planes.GetNumberOfPlanes()): bound = planes.GetPlane(i) dot = normalDot(plane, bound) if dot> maxDot: maxDot = dot maxI = i pass continue planes.GetNormals().SetTuple3(maxI, *plane.GetNormal()) planes.GetPoints().SetPoint(maxI, *plane.GetOrigin()) self.Clipper.SetClipFunction(planes) self.Clipper.GenerateClippedOutputOn() self.Clipper.InsideOutOn() self.Clipper.Update() self.Clipped.DeepCopy(self.Clipper.GetClippedOutput()) self.Clipped.Update() return
sphere.SetCenter(0.0, 0.1, 0.2) sphere.SetRadius(0.75) # Extract points within sphere extract = vtk.vtkFitImplicitFunction() extract.SetInputConnection(points.GetOutputPort()) extract.SetImplicitFunction(sphere) extract.SetThreshold(0.005) extract.GenerateVerticesOn() # Clip out some of the points with a plane; requires vertices plane = vtk.vtkPlane() plane.SetOrigin(sphere.GetCenter()) plane.SetNormal(1, 1, 1) clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(extract.GetOutputPort()) clipper.SetClipFunction(plane) # Generate density field from points # Use fixed radius dens0 = vtk.vtkPointDensityFilter() dens0.SetInputConnection(clipper.GetOutputPort()) dens0.SetSampleDimensions(res, res, res) dens0.SetDensityEstimateToFixedRadius() dens0.SetRadius(0.05) # dens0.SetDensityEstimateToRelativeRadius() dens0.SetRelativeRadius(2.5) # dens0.SetDensityFormToVolumeNormalized() dens0.SetDensityFormToNumberOfPoints() dens0.ComputeGradientOn()
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()