def surface_clip(polydata, type: int): BoundingBox = polydata.GetBounds() center = [0] * 3 normal = [0] * 3 center[0] = (BoundingBox[0] + BoundingBox[1]) / 2 center[1] = (BoundingBox[2] + BoundingBox[3]) / 2 if (type == 0): center[2] = BoundingBox[4] + 120 normal[2] = -1 else: center[2] = BoundingBox[5] - 120 normal[2] = 1 plane1 = vtk.vtkPlane() plane1.SetOrigin(center[0], center[1], center[2]) plane1.SetNormal(normal) planes = vtk.vtkPlaneCollection() planes.AddItem(plane1) clipper = vtk.vtkClipClosedSurface() clipper.SetInputData(polydata) clipper.SetClippingPlanes(planes) clipper.SetScalarModeToColors() clipper.SetActivePlaneId(0) clipper.Update() return clipper.GetOutput()
def setClipPlanes(mapper, xmin, xmax, ymin, ymax): clipPlaneCollection = vtk.vtkPlaneCollection() if xmin != xmax: clipPlaneXMin = vtk.vtkPlane() clipPlaneXMin.SetOrigin(xmin, 0.0, 0.0) clipPlaneXMin.SetNormal(1.0, 0.0, 0.0) clipPlaneXMax = vtk.vtkPlane() clipPlaneXMax.SetOrigin(xmax, 0.0, 0.0) clipPlaneXMax.SetNormal(-1.0, 0.0, 0.0) clipPlaneCollection.AddItem(clipPlaneXMin) clipPlaneCollection.AddItem(clipPlaneXMax) if ymin != ymax: clipPlaneYMin = vtk.vtkPlane() clipPlaneYMin.SetOrigin(0.0, ymin, 0.0) clipPlaneYMin.SetNormal(0.0, 1.0, 0.0) clipPlaneYMax = vtk.vtkPlane() clipPlaneYMax.SetOrigin(0.0, ymax, 0.0) clipPlaneYMax.SetNormal(0.0, -1.0, 0.0) clipPlaneCollection.AddItem(clipPlaneYMin) clipPlaneCollection.AddItem(clipPlaneYMax) if clipPlaneCollection.GetNumberOfItems() > 0: mapper.SetClippingPlanes(clipPlaneCollection)
def computeClippingPlanes(self, source): # Clipping planes planes = vtk.vtkPlaneCollection() axis1 = np.array(source.GetPoint1()) - np.array(source.GetOrigin()) axis2 = np.array(source.GetPoint2()) - np.array(source.GetOrigin()) # Okay plane1 = vtk.vtkPlane() plane1.SetOrigin(source.GetOrigin()) plane1.SetNormal(axis2) plane2 = vtk.vtkPlane() plane2.SetOrigin(source.GetOrigin()) plane2.SetNormal(axis1) tmp = axis2 + np.array(source.GetPoint1()) plane3 = vtk.vtkPlane() plane3.SetOrigin(tmp) plane3.SetNormal(-axis2) plane4 = vtk.vtkPlane() plane4.SetOrigin(tmp) plane4.SetNormal(-axis1) planes.AddItem(plane1) planes.AddItem(plane2) planes.AddItem(plane3) planes.AddItem(plane4) return planes
def GetClippingPlanes(self): if self._ClippingPlanesCollection is None: collection = vtk.vtkPlaneCollection() for plane in self._ClippingPlanes: collection.AddItem(plane) self._ClippingPlanesCollection = collection return self._ClippingPlanesCollection
def opImplement(self): clipper = vtk.vtkClipClosedSurface(); clipper.TriangulationErrorDisplayOn(); clipper.SetInputData(self.data); capPlanes = vtk.vtkPlaneCollection() firstclipPlane = vtk.vtkPlane(); #We should change following 2 lines only #print("Plane normal : {}".format(self.normal)) firstclipPlane.SetNormal(*self.normal); firstclipPlane.SetOrigin(*self.origin); #End possible changes capPlanes.AddItem(firstclipPlane) clipper.SetClippingPlanes(capPlanes); clipper.Update(); resultOne = clipper.GetOutput(); return resultOne;
def Pjauti(self, data): plane1 = vtk.vtkPlane() plane1.SetNormal(1, 0, 0) plane1.SetOrigin(0, 0, 0) plane2 = vtk.vtkPlane() #plane2.SetNormal(-0.5,0.5,0) plane2.SetNormal(0, 1, 0) plane2.SetOrigin(0, 0, 0) coll = vtk.vtkPlaneCollection() coll.AddItem(plane1) coll.AddItem(plane2) clip1 = vtk.vtkClipClosedSurface() clip1.SetClippingPlanes(coll) clip1.SetInputData(data) clip1.Update() return clip1.GetOutput()
def Cut(self): pts = np.array([ float(self.ui.xMin.text()), float(self.ui.xMax.text()), float(self.ui.yMin.text()), float(self.ui.yMax.text()) ]) planex1 = vtk.vtkPlane() planex1.SetOrigin(pts[0], 0, 0) planex1.SetNormal(1, 0, 0) planex2 = vtk.vtkPlane() planex2.SetOrigin(pts[1], 0, 0) planex2.SetNormal(-1, 0, 0) planey1 = vtk.vtkPlane() planey1.SetOrigin(0, pts[2], 0) planey1.SetNormal(0, 1, 0) planey2 = vtk.vtkPlane() planey2.SetOrigin(0, pts[3], 0) planey2.SetNormal(0, -1, 0) planeCollection = vtk.vtkPlaneCollection() planeCollection.AddItem(planex1) planeCollection.AddItem(planex2) planeCollection.AddItem(planey1) planeCollection.AddItem(planey2) Omapper = self.outlineActor.GetMapper() Pmapper = self.pointActor.GetMapper() Omapper.SetClippingPlanes(planeCollection) Pmapper.SetClippingPlanes(planeCollection) if hasattr(self, 'Smapper'): self.Smapper.SetClippingPlanes(planeCollection) nl = np.array(self.ax3D.GetBounds()) self.ren.RemoveActor(self.ax3D) #add axes self.add_axis(self.limits, [1, 1, 1]) #update self.ren.ResetCamera() self.ui.vtkWidget.update() self.ui.vtkWidget.setFocus()
def computeVolume(pdata, orientation): bd = pdata.GetBounds() # Define the cutting plane plane = vtk.vtkPlane() if (orientation == 'z'): plane.SetOrigin(0, 0, bd[5] - 0.1) plane.SetNormal(0, 0, -1) elif (orientation == 'x'): plane.SetOrigin(bd[0] + 0.1, 0, 0) plane.SetNormal(1, 0, 0) elif (orientation == 'n'): plane.SetOrigin(0, 0, bd[5] + 100) plane.SetNormal(0, 0, -1) # Need a plane collection for clipping planeCollection = vtk.vtkPlaneCollection() planeCollection.AddItem(plane) # The clipper generates a clipped polygonial model clipper = vtk.vtkClipClosedSurface() clipper.SetClippingPlanes(planeCollection) if (vtk.vtkVersion.GetVTKMajorVersion() < 6): clipper.SetInput(pdata) else: clipper.SetInputData(pdata) clipper.SetGenerateFaces(1) clipper.SetScalarModeToLabels() clipper.Update() # Get volume using mass property massprop = vtk.vtkMassProperties() if (vtk.vtkVersion.GetVTKMajorVersion() < 6): massprop.SetInput(clipper.GetOutput()) else: massprop.SetInputData(clipper.GetOutput()) return massprop.GetVolume()
def __init__(self, runname, input_file, output_file, radius, x, y, z): self.runname = runname reader = vtk.vtkPolyDataReader() reader.SetFileName(input_file) reader.Update() planes = vtk.vtkPlaneCollection() top = vtk.vtkPlane() top.SetNormal(0, 0, -1) top.SetOrigin(x, y, z + radius) planes.AddItem(top) bottom = vtk.vtkPlane() bottom.SetNormal(0, 0, 1) bottom.SetOrigin(x, y, z - radius) planes.AddItem(bottom) front = vtk.vtkPlane() front.SetNormal(0, -1, 0) front.SetOrigin(x, y + radius, z) planes.AddItem(front) back = vtk.vtkPlane() back.SetNormal(0, 1, 0) back.SetOrigin(x, y - radius, z) planes.AddItem(back) right = vtk.vtkPlane() right.SetNormal(1, 0, 0) right.SetOrigin(x - radius, y, z) planes.AddItem(right) left = vtk.vtkPlane() left.SetNormal(-1, 0, 0) left.SetOrigin(x + radius, y, z) planes.AddItem(left) clipper = vtk.vtkClipClosedSurface() clipper.SetClippingPlanes(planes) clipper.SetInputConnection(reader.GetOutputPort()) connectivity = vtk.vtkPolyDataConnectivityFilter() connectivity.SetExtractionModeToAllRegions() connectivity.SetInputConnection(clipper.GetOutputPort()) connectivity.Update() specified = vtk.vtkPolyDataConnectivityFilter() specified.SetExtractionModeToSpecifiedRegions() specified.SetInputConnection(clipper.GetOutputPort()) tester = vtk.vtkPolyDataConnectivityFilter() tester.SetExtractionModeToSpecifiedRegions() tester.SetInputConnection(clipper.GetOutputPort()) dims = {} for i in range(connectivity.GetNumberOfExtractedRegions()): tester.AddSpecifiedRegion(i) tester.Update() bounds = tester.GetOutput().GetBounds() if bounds[0] + radius - delta < x or bounds[1] - radius + delta > x or \ bounds[2] + radius - delta < y or bounds[3] - radius + delta > y or \ bounds[4] + radius - delta < z or bounds[5] - radius + delta > z: mindim = min(bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4]) dims[i] = mindim tester.DeleteSpecifiedRegion(i) for i in sorted(dims.iteritems(), key=lambda i: i[1], reverse=True)[0:5]: print i specified.AddSpecifiedRegion(i[0]) #cleaner = vtk.vtkCleanPolyData() #cleaner.SetInputConnection(specified.GetOutputPort()) #cleaner.SetTolerance(1e-5) #orientator = vtk.vtkPolyDataNormals() #orientator.SetInputConnection(clipper.GetOutputPort()) #orientator.ConsistencyOn() #orientator.AutoOrientNormalsOn() writer = vtk.vtkSTLWriter() writer.SetFileName(output_file + 'tmp1.stl') writer.SetInputConnection(clipper.GetOutputPort()) writer.Write() with open("/tmp/test.mlx", "w") as f: f.write(""" <FilterScript> <filter name="Remove Zero Area Faces"/> <filter name="Re-Orient all faces coherentely"/> <filter name="Quadric Edge Collapse Decimation"> <Param type="RichInt" value="30000" name="TargetFaceNum"/> <Param type="RichFloat" value="0" name="TargetPerc"/> <Param type="RichFloat" value="0.3" name="QualityThr"/> <Param type="RichBool" value="false" name="PreserveBoundary"/> <Param type="RichBool" value="false" name="PreserveNormal"/> <Param type="RichBool" value="true" name="PreserveTopology"/> <Param type="RichBool" value="true" name="OptimalPlacement"/> <Param type="RichBool" value="false" name="PlanarQuadric"/> <Param type="RichBool" value="false" name="QualityWeight"/> <Param type="RichBool" value="true" name="AutoClean"/> <Param type="RichBool" value="false" name="Selected"/> </filter> </FilterScript> """) subprocess.call([ "meshlabserver", "-i", output_file + 'tmp1.stl', "-o", output_file + '.off', "-s", "/tmp/test.mlx" ]) #reader = vtk.vtkSTLReader() #reader.SetFileName(output_file + 'tmp2.stl') #reader.Update() writer = vtk.vtkSTLWriter() writer.SetFileName(output_file) writer.SetInputConnection(specified.GetOutputPort()) writer.Write() vtk_writer = vtk.vtkXMLPolyDataWriter() vtk_writer.SetFileName(output_file + ".vtu") vtk_writer.SetInputConnection(specified.GetOutputPort()) vtk_writer.Write()
v16.SetDataSpacing(3.2,3.2,1.5) v16.Update() iso = vtk.vtkImageMarchingCubes() iso.SetInputConnection(v16.GetOutputPort()) iso.SetValue(0,1150) iso.SetInputMemoryLimit(1000) topPlane = vtk.vtkPlane() topPlane.SetNormal(0,0,1) topPlane.SetOrigin(0,0,0.5) botPlane = vtk.vtkPlane() botPlane.SetNormal(0,0,-1) botPlane.SetOrigin(0,0,137.0) sagPlane = vtk.vtkPlane() sagPlane.SetNormal(1,0,0) sagPlane.SetOrigin(100.8,0,0) capPlanes = vtk.vtkPlaneCollection() capPlanes.AddItem(topPlane) capPlanes.AddItem(botPlane) capPlanes.AddItem(sagPlane) clip = vtk.vtkClipClosedSurface() clip.SetClippingPlanes(capPlanes) clip.SetInputConnection(iso.GetOutputPort()) clip.SetBaseColor(0.9804,0.9216,0.8431) clip.SetClipColor(1.0,1.0,1.0) clip.SetActivePlaneColor(1.0,1.0,0.8) clip.SetActivePlaneId(2) clip.SetScalarModeToColors() clip.GenerateOutlineOn() clip.GenerateFacesOn() isoMapper = vtk.vtkPolyDataMapper() isoMapper.SetInputConnection(clip.GetOutputPort())
plane3.SetOrigin(0, -15, 0) plane3.SetNormal(0.163176, 0.925417, -0.342020) plane4 = vtk.vtkPlane() plane4.SetOrigin(0, 24, 0) plane4.SetNormal(0, -1, 0) plane5 = vtk.vtkPlane() plane5.SetOrigin(0, 0, -24) plane5.SetNormal(0, 0, 1) plane6 = vtk.vtkPlane() plane6.SetOrigin(0, 0, 24) plane6.SetNormal(0, 0, -1) clippingPlanes = vtk.vtkPlaneCollection() clippingPlanes.AddItem(plane1) clippingPlanes.AddItem(plane2) clippingPlanes.AddItem(plane3) clippingPlanes.AddItem(plane4) clippingPlanes.AddItem(plane5) clippingPlanes.AddItem(plane6) # Cropping planes are in data coords volumeMapper1 = vtk.vtkFixedPointVolumeRayCastMapper() volumeMapper1.SetInputConnection(reader.GetOutputPort()) volumeMapper1.CroppingOn() volumeMapper1.SetCroppingRegionPlanes(16, 33, 16, 33, 16, 33) volumeMapper1.SetClippingPlanes(clippingPlanes) volume1 = vtk.vtkVolume()
def __init__(self, data_dir,reader): planes = vtk.vtkPlane() planeC = vtk.vtkPlaneCollection() planeC.AddItem(planes) # Stripper for getting smooth poly outlines, # gives circle and not random triangles stripper = vtk.vtkStripper() stripper.SetInputConnection(reader.GetOutputPort()) # Clipper for PLANE clipper = vtk.vtkClipClosedSurface() clipper.SetInputConnection(stripper.GetOutputPort()) clipper.SetClippingPlanes(planeC) clipMapper = vtk.vtkImageFlip() clipMapper = vtk.vtkPolyDataMapper() clipMapper.SetInputConnection(clipper.GetOutputPort()) clipActor = vtk.vtkActor() clipActor.SetMapper(clipMapper) clipActor.GetProperty().SetColor(0.5,0.5,0.5) clipActor.GetProperty().SetOpacity(0.5) clipActor.SetPosition(0.001,0.001,0.001) clipperOutline = vtk.vtkClipClosedSurface() clipperOutline.SetInputConnection(stripper.GetOutputPort()) clipperOutline.SetClippingPlanes(planeC) clipperOutline.GenerateFacesOff() clipperOutline.GenerateOutlineOn() innerNorms = vtk.vtkTriangleMeshPointNormals() innerNorms.SetInputConnection(reader.GetOutputPort()) innerMapper = vtk.vtkOpenGLPolyDataMapper() innerMapper.SetInputConnection(innerNorms.GetOutputPort()) innerActor = vtk.vtkActor() innerActor.SetMapper(innerMapper) clipperOutlineMapper = vtk.vtkPolyDataMapper() clipperOutlineMapper.SetInputConnection(clipperOutline.GetOutputPort()) clipOutlineActor = vtk.vtkActor() clipOutlineActor.SetMapper(clipperOutlineMapper) clipOutlineActor.GetProperty().SetColor(0,1,0) clipOutlineActor.SetPosition(0.001,0.001,0.001) planeWidget = vtk.vtkImagePlaneWidget() planeWidget.SetInputConnection(reader.GetOutputPort()) planeWidget.RestrictPlaneToVolumeOn() planeWidget.GetResliceOutput() rsx = planeWidget.GetResliceAxes() #planeWidget.SetSliceIndex(52) #planeWidget.SetOrigin(1,-1,-1) planeWidget.SetResliceInterpolateToLinear() self.clipActor = clipActor self.planes = planes self.planeWidget = planeWidget self.innerActor = innerActor self.clipOutlineActor = clipOutlineActor px = planeWidget.GetSlicePosition() #Cut(px) #clipActor.VisibilityOn() def UpdateMesh(obj, event): obj.GetNormal() self.planes.SetNormal(obj.GetNormal()) self.planes.SetOrigin(obj.GetOrigin()) self.clipActor.VisibilityOn() #planeWidget.AddObserver("EndInteractionEvent", CutMesh) planeWidget.AddObserver("InteractionEvent", UpdateMesh) self.planeWidget = planeWidget
def OnRenderEvent(self, renderer, vtkevent): VPN = renderer.GetActiveCamera().GetViewPlaneNormal() absVPN = list(map(abs, VPN)) planeIndex = absVPN.index(max(absVPN)) oldPlaneIndex = self._RendererCurrentIndex[renderer] if VPN[planeIndex] < 0: planeIndex = planeIndex + 3 if planeIndex != oldPlaneIndex or self._StatusChange: allPlanes = self._RendererActorList[renderer] if oldPlaneIndex >= 0 and oldPlaneIndex < 6: for actor in allPlanes[oldPlaneIndex]: renderer.RemoveActor(actor) # the OrthoPlane actors if self._OrthoPlanes: for plane in self._OrthoPlanes.GetPlanes(): for actor in plane.GetActors(renderer): if actor.GetTexture(): renderer.RemoveActor(actor) # make a list of all the other actors allActorsList = [] allActors = renderer.GetActors() allActors.InitTraversal() while 1: actor = allActors.GetNextItem() if actor is None: break if actor.GetProperty().GetOpacity() < 1.0: allActorsList.append(actor) for actor in allActorsList: renderer.RemoveActor(actor) i = 0 for actor in allPlanes[planeIndex]: if (i % 3 == 0 or (self._OrthoPlanes and self._ShowOrthoPlanes)) and \ self._ShowVolume: renderer.AddActor(actor) i = i + 1 self._RendererCurrentIndex[renderer] = planeIndex if self._LookupTable.GetMTime() > self._RenderTime.GetMTime(): self._ImageMapToColors.UpdateWholeExtent() self._ImageToStructuredPoints.UpdateWholeExtent() i = 0 for actor in self._RendererActorList[renderer][planeIndex]: if i % 3 == 0: actor.GetTexture().Render(renderer) actor.GetTexture().GetInput().ReleaseData() i = i + 1 if not (self._OrthoPlanes and self._ShowOrthoPlanes): transform = self._ClippingCube.GetTransform() cplanes = self._CornerClippingPlanes bplanes = self._CubeClippingPlanes cplanes.InitTraversal() bplanes.InitTraversal() for p in self._ClippingCube.GetPlanes(): bplane = bplanes.GetNextItem() bplane.SetNormal(transform.TransformNormal(p.GetNormal())) bplane.SetOrigin(transform.TransformPoint(p.GetCenter())) cplane = cplanes.GetNextItem() cplane.SetNormal(transform.TransformNormal(p.GetNormal())) cplane.SetOrigin(transform.TransformPoint(p.GetCenter())) else: for i in range(self._OrthoPlanes.GetNumberOfInputs()): needupdate = 0 try: table = self._OrthoPlanesLookupTables[i] except KeyError: table = vtk.vtkLookupTable() self._OrthoPlanesLookupTables[i] = table needupdate = 1 oldtable = self._OrthoPlanes.GetLookupTable(i) vtable = self._LookupTable if (oldtable.GetMTime() > table.GetMTime() or vtable.GetMTime() > table.GetMTime() or needupdate): # map everything with alpha below threshold to transparent trange = oldtable.GetTableRange() vrange = vtable.GetTableRange() n = oldtable.GetNumberOfColors() m = vtable.GetNumberOfColors() table.SetTableRange(trange[0], trange[1]) table.SetNumberOfColors(n) for j in range(n): r, g, b, a = oldtable.GetTableValue(j) v = trange[0] + j / (n - 1.0) * (trange[1] - trange[0]) idx = int((v - vrange[0]) / (vrange[1] - vrange[0]) * (m - 1.0) + 0.5) if idx < 0: idx = 0 if idx > m - 1: idx = m - 1 vr, vg, vb, va = vtable.GetTableValue(idx) # vr,vg,vb,va = vtable.GetColor(v) if va < self._OrthoPickThreshold or j == 0: table.SetTableValue(j, r, g, b, 0) else: table.SetTableValue(j, r, g, b, a) transform = self._OrthoPlanes.GetTransform() pos = transform.TransformPoint(self._OrthoPlanes.GetOrthoCenter()) cpos = renderer.GetActiveCamera().GetPosition() cnorm = (cpos[0] - pos[0], cpos[1] - pos[1], cpos[2] - pos[2]) n = math.sqrt(cnorm[0]**2 + cnorm[1]**2 + cnorm[2]**2) cnorm = (old_div(cnorm[0], n), old_div(cnorm[1], n), old_div(cnorm[2], n)) origins = [] normals = [] cplanes = self._CornerClippingPlanes bplanes = self._CubeClippingPlanes cplanes.InitTraversal() bplanes.InitTraversal() for plane in self._OrthoPlanes.GetPlanes(): origin = plane.GetOrigin() normal = plane.GetNormal() originw = transform.TransformPoint(origin) normalw = transform.TransformNormal(normal) if (cnorm[0] * normalw[0] + cnorm[1] * normalw[1] + cnorm[2] * normalw[2] > 0): normalw = (-normalw[0], -normalw[1], -normalw[2]) else: normal = (-normal[0], -normal[1], -normal[2]) origins.append(origin) normals.append(normal) # this is a brute-force way of matching the planes cplane = cplanes.GetNextItem() cplane.SetOrigin(originw) cplane.SetNormal(normalw) for p in self._ClippingCube.GetPlanes(): if (-normal[0], -normal[1], -normal[2]) == p.GetNormal(): bplane = bplanes.GetNextItem() bplane.SetNormal(normalw[0], normalw[1], normalw[2]) bplane.SetOrigin( transform.TransformPoint(p.GetCenter())) if bplane.EvaluateFunction(*cplane.GetOrigin()) < 0: cplane.SetOrigin(bplane.GetOrigin()) break cplane = cplanes.GetNextItem() cplane.SetOrigin(originw) cplane.SetNormal(-normalw[0], -normalw[1], -normalw[2]) for p in self._ClippingCube.GetPlanes(): if normal == p.GetNormal(): bplane = bplanes.GetNextItem() bplane.SetNormal(-normalw[0], -normalw[1], -normalw[2]) bplane.SetOrigin( transform.TransformPoint(p.GetCenter())) if bplane.EvaluateFunction(*cplane.GetOrigin()) < 0: cplane.SetOrigin(bplane.GetOrigin()) break # make sure orthoplanes are drawn after the volume k = 0 for plane in self._OrthoPlanes.GetPlanes(): i = 0 for actor in plane.GetActors(renderer): texture = actor.GetTexture() if not texture: continue if texture.GetLookupTable( ) != self._OrthoPlanesLookupTables[i]: texture.SetLookupTable( self._OrthoPlanesLookupTables[i]) texture.MapColorScalarsThroughLookupTableOn() # these next three lines are a real hack to force the # color mapping to be done by the texture, not by # vtkImageMapToColors source = texture.GetInput().GetSource() while not source.IsA("vtkImageReslice"): source = source.GetInput().GetSource() texture.SetInput(source.GetOutput()) if actor.GetProperty().GetOpacity() != 0.999: property = vtk.vtkProperty() actor.GetProperty().DeepCopy(property) actor.SetProperty(property) actor.GetProperty().SetOpacity(0.999) mapper = actor.GetMapper() planes = mapper.GetClippingPlanes() if not planes or planes.GetNumberOfItems() != 6: planes = vtk.vtkPlaneCollection() for j in range(6): planes.AddItem(vtk.vtkPlane()) mapper.SetClippingPlanes(planes) planes.InitTraversal() bplanes.InitTraversal() for j in range(6): np = planes.GetNextItem() bplane = bplanes.GetNextItem() # an ugly hack to ensure exact rounding for comparison np.SetNormal( transform.TransformNormal(normals[old_div(j, 2)])) if old_div(j, 2) != k and bplane.GetNormal() == np.GetNormal() and \ bplane.EvaluateFunction(*origins[old_div(j, 2)]) > 0: np.SetOrigin(origins[old_div(j, 2)]) np.SetNormal(normals[old_div(j, 2)]) else: np.SetOrigin(transform.GetInverse().TransformPoint( bplane.GetOrigin())) np.SetNormal( transform.GetInverse().TransformNormal( bplane.GetNormal())) i = i + 1 if planeIndex != oldPlaneIndex or self._StatusChange: renderer.AddActor(actor) k = k + 1 # put all the other actors back if planeIndex != oldPlaneIndex or self._StatusChange: for actor in allActorsList: renderer.AddActor(actor) self._StatusChange = 0 self._RenderTime.Modified()
def __init__(self): ActorFactory.ActorFactory.__init__(self) # whether to display the volume self._ShowVolume = 1 self._StatusChange = 0 # create a clipping cube to go with the volume self._ClippingCube = ClippingCubeFactory.ClippingCubeFactory() self.AddChild(self._ClippingCube) self._CubeClippingPlanes = vtk.vtkPlaneCollection() for i in range(6): self._CubeClippingPlanes.AddItem(vtk.vtkPlane()) # for if we clip in with OrthoPlanes self._OrthoPlanes = None self._ShowOrthoPlanes = 1 self._OrthoPlanesLookupTables = {} self._OrthoPickThreshold = 0.0025 # corner clipping planes, in pairs with opposite normals self._CornerClippingPlanes = vtk.vtkPlaneCollection() for i in range(6): self._CornerClippingPlanes.AddItem(vtk.vtkPlane()) # clipping planes for the volume, sorted for the # three chunks that will make up the final volume self._ClippingPlanes = [ vtk.vtkPlaneCollection(), vtk.vtkPlaneCollection(), vtk.vtkPlaneCollection() ] for i in range(3): planes = self._ClippingPlanes[i] cplanes = self._CornerClippingPlanes bplanes = self._CubeClippingPlanes if i == 0: planes.AddItem(cplanes.GetItemAsObject(0)) planes.AddItem(bplanes.GetItemAsObject(1)) planes.AddItem(bplanes.GetItemAsObject(2)) planes.AddItem(bplanes.GetItemAsObject(3)) planes.AddItem(bplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) else: planes.AddItem(bplanes.GetItemAsObject(0)) planes.AddItem(cplanes.GetItemAsObject(1)) if i == 1: planes.AddItem(cplanes.GetItemAsObject(2)) planes.AddItem(bplanes.GetItemAsObject(3)) planes.AddItem(bplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) else: planes.AddItem(bplanes.GetItemAsObject(2)) planes.AddItem(cplanes.GetItemAsObject(3)) if i == 2: planes.AddItem(cplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) else: planes.AddItem(bplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) self._Input = None # generate the pipeline self._ImagePrefilter = vtk.vtkImageShrink3D() self._ImageReslice = vtk.vtkImageReslice() self._ImageReslice.SetInterpolationModeToLinear() self._ImageMapToColors = vtk.vtkImageMapToColors() self._ImageMapToColors.SetOutputFormatToRGBA() self._ImageToStructuredPoints = vtk.vtkImageToStructuredPoints() self._ImageClipsXY = [] self._PlanesXY = [] self._ActorsXY = [] self._PropertyXY = vtk.vtkProperty() self._PropertyXY.SetDiffuse(0) self._PropertyXY.SetAmbient(1) self._ImageClipsYZ = [] self._PlanesYZ = [] self._ActorsYZ = [] self._PropertyYZ = vtk.vtkProperty() self._PropertyYZ.SetDiffuse(0) self._PropertyYZ.SetAmbient(1) self._ImageClipsZX = [] self._PlanesZX = [] self._ActorsZX = [] self._PropertyZX = vtk.vtkProperty() self._PropertyZX.SetDiffuse(0) self._PropertyZX.SetAmbient(1) # a list of the renderer info self._RendererCurrentIndex = {} self._RendererActorList = {} self._RendererObserverList = {} # a transform to apply to the image self._ImageTransform = None self._TransformToGrid = vtk.vtkTransformToGrid() # the alpha pick threshold for the volume self._PickThreshold = 0.25 # the implicit volume for finding the gradient self._ImplicitVolume = vtk.vtkImplicitVolume() # the extent of the texture maps self._VolumeResolution = (64, 64, 64) # the bounds of the volume self._VolumeBounds = None
def create3D(): points = [] ilgis = 0 for x in range(COUNT): ilgis, points = GetForma(ilgis, points) points.append([0, ilgis]) points.append([0, 0]) points.append([R / 2.0, 0]) rodData = "translate([0," + str(R / 4.0) + "," + str( R / 4.0 ) + "])rotate ([-90,0,0]) rotate_extrude($fn=200) polygon( points=" + str( points) + " );\n" rod = open("rod.scad", "w") rod.write(rodData) rod.close() call(["openscad", "-o", "rod.stl", "rod.scad"]) read = vtk.vtkSTLReader() read.SetFileName("rod.stl") read.Update() tran = vtk.vtkTransform() bounds = read.GetOutput().GetBounds() tran.Translate( -read.GetOutput().GetBounds()[0] - (bounds[1] - bounds[0]) / 2.0, -read.GetOutput().GetBounds()[2] - (bounds[3] - bounds[2]) / 2.0, -read.GetOutput().GetBounds()[4] - (bounds[5] - bounds[4]) / 2.0) tfilter = vtk.vtkTransformFilter() tfilter.SetInputData(read.GetOutput()) tfilter.SetTransform(tran) tfilter.Update() w = vtk.vtkSTLWriter() w.SetFileName("rod.stl") w.SetInputData(tfilter.GetOutput()) w.Update() plane1 = vtk.vtkPlane() plane1.SetNormal(1, 0, 0) plane1.SetOrigin(0, 0, 0) plane2 = vtk.vtkPlane() plane2.SetNormal(0, 0, 1) plane2.SetOrigin(0, 0, 0) coll = vtk.vtkPlaneCollection() coll.AddItem(plane1) coll.AddItem(plane2) clip1 = vtk.vtkClipClosedSurface() clip1.SetClippingPlanes(coll) clip1.GenerateFacesOn() clip1.SetInputConnection(tfilter.GetOutputPort()) clip1.Update() beton = vtk.vtkCubeSource() beton.SetBounds(-boxSize, boxSize, -ilgis / 2.0, ilgis / 2.0, -boxSize, boxSize) beton.Update() clip2 = vtk.vtkClipClosedSurface() clip2.SetClippingPlanes(coll) clip2.GenerateFacesOn() clip2.SetInputConnection(beton.GetOutputPort()) clip2.Update() box = vtk.vtkCubeSource() b = clip2.GetOutput().GetBounds() bbbb = clip1.GetOutput().GetBounds() box.SetBounds(b[0], b[1], bbbb[2] - (bbbb[3] - bbbb[2]) * CalcBoxSizeProc / 1000.0, bbbb[3] + (bbbb[3] - bbbb[2]) * CalcBoxSizeProc / 1000.0, b[4], b[5]) box.Update() SaveToSTL(box.GetOutput(), "box.stl") SaveToSTL(clip2.GetOutput(), "beton.stl") SaveToSTL(clip1.GetOutput(), "rod.stl") # create a rendering window and renderer ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # create a renderwindowinteractor iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(clip1.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) ren.AddActor(actor) mapper1 = vtk.vtkPolyDataMapper() mapper1.SetInputConnection(clip2.GetOutputPort()) actor1 = vtk.vtkActor() actor1.SetMapper(mapper1) ren.AddActor(actor1)
def ClipClosedSurface(): colors = vtk.vtkNamedColors() # Create a sphere sphereSource = vtk.vtkSphereSource() sphereSource.SetThetaResolution(20) sphereSource.SetPhiResolution(11) sphereSource.Update() polyData = sphereSource.GetOutput() center = polyData.GetCenter() plane1 = vtk.vtkPlane() plane1.SetOrigin(center[0], center[1], center[2]) plane1.SetNormal(0.0, -1.0, 0.0) plane2 = vtk.vtkPlane() plane2.SetOrigin(center[0], center[1], center[2]) plane2.SetNormal(0.0, 0.0, 1.0) plane3 = vtk.vtkPlane() plane3.SetOrigin(center[0], center[1], center[2]) plane3.SetNormal(-1.0, 0.0, 0.0) planes = vtk.vtkPlaneCollection() planes.AddItem(plane1) planes.AddItem(plane2) planes.AddItem(plane3) clipper = vtk.vtkClipClosedSurface() clipper.SetInputData(polyData) clipper.SetClippingPlanes(planes) # clipper.SetActivePlaneId(2) clipper.SetScalarModeToColors() clipper.SetClipColor(colors.GetColor3d("Green")) clipper.SetBaseColor(colors.GetColor3d("Red")) # clipper.SetActivePlaneColor(colors.GetColor3d("SandyBrown")) clipMapper = vtk.vtkDataSetMapper() clipMapper.SetInputConnection(clipper.GetOutputPort()) clipActor = vtk.vtkActor() clipActor.SetMapper(clipMapper) clipActor.GetProperty().SetColor(1.0000, 0.3882, 0.2784) clipActor.GetProperty().SetInterpolationToFlat() # Create graphics stuff ren1 = vtk.vtkRenderer() ren1.SetBackground(colors.GetColor3d("SteelBlue")) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) renWin.SetSize(512, 512) renWin.SetWindowName("ClipClosedSurface") iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren1.AddActor(clipActor) # Generate an interesting view # ren1.ResetCamera() ren1.GetActiveCamera().Azimuth(120) ren1.GetActiveCamera().Elevation(30) ren1.GetActiveCamera().Dolly(1.0) ren1.ResetCameraClippingRange() renWin.Render() iren.Initialize() iren.Start()
def __init__(self, data_dir, Mreader, Vreader): # inv,inc,iniv,inxi,inxc Volume # in9,in99,inim,ins Actors planes = vtk.vtkPlane() #planes.SetOrigin(0,-1,0) #planes.SetNormal(1,0,0) planeC = vtk.vtkPlaneCollection() planeC.AddItem(planes) ###################################################### # Strip, Clip, Mapper, Actor # Stripper for getting smooth poly outlines, # gives circle and not random triangles stripper = vtk.vtkStripper() stripper.SetInputConnection(Mreader.GetOutputPort()) # Clipper for PLANE 1 Stripper 1 clipper = vtk.vtkClipClosedSurface() clipper.SetInputConnection(stripper.GetOutputPort()) #clip.Update() clipperOutline = vtk.vtkClipClosedSurface() clipperOutline.SetInputConnection(stripper.GetOutputPort()) clipperOutline.SetClippingPlanes(planeC) clipperOutline.GenerateFacesOff() clipperOutline.GenerateOutlineOn() innerNorms = vtk.vtkTriangleMeshPointNormals() innerNorms.SetInputConnection(Mreader.GetOutputPort()) innerMapper = vtk.vtkOpenGLPolyDataMapper() innerMapper.SetInputConnection(innerNorms.GetOutputPort()) innerActor = vtk.vtkActor() innerActor.SetMapper(innerMapper) clipMapper = vtk.vtkImageFlip() clipMapper = vtk.vtkPolyDataMapper() clipMapper.SetInputConnection(clipper.GetOutputPort()) clipActor = vtk.vtkActor() clipActor.SetMapper(clipMapper) clipActor.GetProperty().SetColor(1, 0.5, 0.5) clipActor.GetProperty().SetOpacity(0.5) clipActor.SetPosition(0.001, 0.001, 0.001) clipperOutlineMapper = vtk.vtkPolyDataMapper() clipperOutlineMapper.SetInputConnection(clipperOutline.GetOutputPort()) clipOutlineActor = vtk.vtkActor() clipOutlineActor.SetMapper(clipperOutlineMapper) clipOutlineActor.GetProperty().SetColor(0, 1, 0) clipOutlineActor.SetPosition(0.001, 0.001, 0.001) tfun = vtk.vtkPiecewiseFunction() tfun.AddPoint(0, 0) tfun.AddPoint(1600, 0.05) tfun.AddPoint(2500, 0.15) tfun.AddPoint(2400, 0.0) tfun.AddPoint(2540, 0.97) volumeMapper = vtk.vtkGPUVolumeRayCastMapper() volumeMapper.SetInputConnection(Vreader.GetOutputPort()) volumeMapper.SetBlendModeToComposite() volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetScalarOpacity(tfun) volumeProperty.SetInterpolationTypeToLinear() volumeProperty.ShadeOn() newvol = vtk.vtkVolume() newvol.SetMapper(volumeMapper) newvol.SetProperty(volumeProperty) ####################### planeWidget = vtk.vtkImagePlaneWidget() planeWidget.RestrictPlaneToVolumeOn() planeWidget.SetInputConnection(Mreader.GetOutputPort()) planeWidget.RestrictPlaneToVolumeOn() planeWidget.GetResliceOutput() rsx = planeWidget.GetResliceAxes() #planeWidget.SetSliceIndex(52) #planeWidget.SetOrigin(1,-1,-1) planeWidget.SetResliceInterpolateToLinear() planeWidget.PlaceWidget() #planeWidget.SetInteractor(iren) px = planeWidget.GetSlicePosition() #Cut(px) #clipActor.VisibilityOn() def UpdateMesh(obj, event): #global planes, clipActor obj.GetNormal() planes.SetNormal(obj.GetNormal()) planes.SetOrigin(obj.GetOrigin()) clipper.SetClippingPlanes(planeC) clipActor.VisibilityOn() planesS = vtk.vtkPlanes() def ClipVolumeRender(obj, event): #global planes, volumeMapper planes.SetOrigin(obj.GetOrigin()) x2 = obj.GetOrigin()[0] y2 = obj.GetOrigin()[1] z2 = obj.GetOrigin()[2] x3 = obj.GetPoint1()[0] y3 = obj.GetPoint1()[1] z3 = obj.GetPoint1()[2] x1 = obj.GetPoint2()[0] y1 = obj.GetPoint2()[1] z1 = obj.GetPoint2()[2] a1 = x2 - x1 b1 = y2 - y1 c1 = z2 - z1 a2 = x3 - x1 b2 = y3 - y1 c2 = z3 - z1 a = b1 * c2 - b2 * c1 b = a2 * c1 - a1 * c2 c = a1 * b2 - b1 * a2 d = (-a * x1 - b * y1 - c * z1) #level1 = list([x,y,z,0,x,y,z,0,x,y,z,0,x,y,z,0,x,y,z,0,x,y,z,0]) level1 = list([ -a, -b, -c, -d, -a, -b, -c, -d, -a, -b, -c, -d, -a, -b, -c, -d, -a, -b, -c, -d, -a, -b, -c, -d ]) print(a, b, c, d) planesS.SetFrustumPlanes(level1) #level2 = list([xMin,xMax, yMin,yMax,zMin,zMax]) #planesS.SetBounds(level2) #planesS.SetNormals(obj.GetNormal()) #planesS.GetPlane(0,planes) volumeMapper.SetClippingPlanes(planesS) #print(planesS.GetPoints()) newvol.VisibilityOn() ClipVolumeRender(planeWidget, "STR") UpdateMesh(planeWidget, "STR") #planeWidget.AddObserver("EndInteractionEvent", CutMesh) #planeWidget.AddObserver("StartInteractionEvent", StartInteraction) planeWidget.AddObserver("InteractionEvent", UpdateMesh) #planeWidget.AddObserver("EndInteractionEvent", CutMesh) planeWidget.AddObserver("InteractionEvent", ClipVolumeRender) #planeWidget.AddObserver("EndInteractionEvent", EndInteraction) self.planeWidget = planeWidget #self.reader = reader self.clipActor = clipActor #ren1.AddActor(VActor) self.newvol = newvol self.clipOutlineActor = clipOutlineActor
def LerSTL(self, path): mesh = vtk.vtkSTLReader() mesh.SetFileName(path) mesh.Update() # faz a mapeação dos dados do stl stlMapper = vtk.vtkPolyDataMapper() stlMapper.SetInputConnection(mesh.GetOutputPort()) #represenatação da visualização, neste caso sem ver. stlActor = vtk.vtkLODActor() stlActor.SetMapper(stlMapper) #------------------------------------------------------------------- # construção do plano para corte plane = self.plane = vtk.vtkPlane() # chamar a função plano de corte PlaneCollection = vtk.vtkPlaneCollection( ) # cria uma colecção de planos PlaneCollection.AddItem( plane) # estou a adicionar o plano de corte a essa colecção # faz o corte e fecha logo de imediato o polidata self.clipper = clipper = vtk.vtkClipClosedSurface() clipper.SetInputData(mesh.GetOutput()) clipper.SetClippingPlanes( PlaneCollection) #recebe os meus planos de corte clipper.SetBaseColor(0.0, 0.0, 1.0) clipper.SetClipColor(0.0, 0.0, 1.0) clipper.SetScalarModeToColors() clipper.GenerateFacesOn() #gera a face que fecha o polidata # mapeamento da região da polidata cortada. clipMapper = vtk.vtkPolyDataMapper() clipMapper.SetInputData(clipper.GetOutput()) clipMapper.ScalarVisibilityOn() #------------------------------------------- #--------------da a cor a parte cortada---- backProp = vtk.vtkProperty() backProp.SetDiffuseColor((0.0, 1.0, 0.0)) #--------------------------------------------------- # faz a visualização do polidata cortada-- clipActor = vtk.vtkActor() clipActor.SetMapper(clipMapper) clipActor.GetProperty().SetColor((0.0, 1.0, 0.0)) #-------------------------------------------------------- # esta é a representação do wigdet do plano de corte rep = vtk.vtkImplicitPlaneRepresentation() rep.PlaceWidget(stlActor.GetBounds() ) #é a posição dos limite aonde o plano de corte fica rep.SetPlaceFactor(1.25) # expandir os limite do widget para 25% rep.UseBoundsOn() # mostra a fronteira rep.NormalToZAxisOn() #da a posição de corte, no sentido de z rep.OutlineTranslationOff( ) # nao posso mexer o widget, so posso mexer o plano de corte rep.PlaceWidget(mesh.GetOutput().GetBounds() ) #mostra aonde vai ser posicionado o widget rep.OutsideBoundsOn() rep.VisibilityOn() #............ # chama o proprio widget , para interação para fazer o corte self.planeWidget = vtk.vtkImplicitPlaneWidget2() self.planeWidget.SetInteractor(self.Interactor) self.planeWidget.SetRepresentation(rep) # adiconar a representação self.planeWidget.SetEnabled(0) self.planeWidget.AddObserver( "EndInteractionEvent", self.myCallback) # vai tratar o evento para fazero corte self.planeWidget.On() #--------------------------------------- # adiconar os actores ao renderer para visualização self.renderer.AddActor(stlActor) self.renderer.AddActor(clipActor) #------------------------------------------- #posicionar a camera para poder visualizar a volume todo self.renderer.ResetCamera() #---------------------------------------- #faze a renderização total self.Interactor.Render() #----------------------------- # liga o plano para fazer funcionar o widget- self.VerPlano = True
def OnRenderEvent(self, renderer, vtkevent): VPN = renderer.GetActiveCamera().GetViewPlaneNormal() absVPN = list(map(abs, VPN)) planeIndex = absVPN.index(max(absVPN)) oldPlaneIndex = self._RendererCurrentIndex[renderer] if VPN[planeIndex] < 0: planeIndex = planeIndex + 3 if planeIndex != oldPlaneIndex or self._StatusChange: allPlanes = self._RendererActorList[renderer] if oldPlaneIndex >= 0 and oldPlaneIndex < 6: for actor in allPlanes[oldPlaneIndex]: renderer.RemoveActor(actor) # the OrthoPlane actors if self._OrthoPlanes: for plane in self._OrthoPlanes.GetPlanes(): for actor in plane.GetActors(renderer): if actor.GetTexture(): renderer.RemoveActor(actor) # make a list of all the other actors allActorsList = [] allActors = renderer.GetActors() allActors.InitTraversal() while 1: actor = allActors.GetNextItem() if actor is None: break if actor.GetProperty().GetOpacity() < 1.0: allActorsList.append(actor) for actor in allActorsList: renderer.RemoveActor(actor) i = 0 for actor in allPlanes[planeIndex]: if (i % 3 == 0 or (self._OrthoPlanes and self._ShowOrthoPlanes)) and \ self._ShowVolume: renderer.AddActor(actor) i = i + 1 self._RendererCurrentIndex[renderer] = planeIndex if self._LookupTable.GetMTime() > self._RenderTime.GetMTime(): self._ImageMapToColors.UpdateWholeExtent() self._ImageToStructuredPoints.UpdateWholeExtent() i = 0 for actor in self._RendererActorList[renderer][planeIndex]: if i % 3 == 0: actor.GetTexture().Render(renderer) actor.GetTexture().GetInput().ReleaseData() i = i + 1 if not (self._OrthoPlanes and self._ShowOrthoPlanes): transform = self._ClippingCube.GetTransform() cplanes = self._CornerClippingPlanes bplanes = self._CubeClippingPlanes cplanes.InitTraversal() bplanes.InitTraversal() for p in self._ClippingCube.GetPlanes(): bplane = bplanes.GetNextItem() bplane.SetNormal(transform.TransformNormal(p.GetNormal())) bplane.SetOrigin(transform.TransformPoint(p.GetCenter())) cplane = cplanes.GetNextItem() cplane.SetNormal(transform.TransformNormal(p.GetNormal())) cplane.SetOrigin(transform.TransformPoint(p.GetCenter())) else: for i in range(self._OrthoPlanes.GetNumberOfInputs()): needupdate = 0 try: table = self._OrthoPlanesLookupTables[i] except KeyError: table = vtk.vtkLookupTable() self._OrthoPlanesLookupTables[i] = table needupdate = 1 oldtable = self._OrthoPlanes.GetLookupTable(i) vtable = self._LookupTable if (oldtable.GetMTime() > table.GetMTime() or vtable.GetMTime() > table.GetMTime() or needupdate): # map everything with alpha below threshold to transparent trange = oldtable.GetTableRange() vrange = vtable.GetTableRange() n = oldtable.GetNumberOfColors() m = vtable.GetNumberOfColors() table.SetTableRange(trange[0], trange[1]) table.SetNumberOfColors(n) for j in range(n): r, g, b, a = oldtable.GetTableValue(j) v = trange[0] + j / (n - 1.0) * (trange[1] - trange[0]) idx = int((v - vrange[0]) / (vrange[ 1] - vrange[0]) * (m - 1.0) + 0.5) if idx < 0: idx = 0 if idx > m - 1: idx = m - 1 vr, vg, vb, va = vtable.GetTableValue(idx) # vr,vg,vb,va = vtable.GetColor(v) if va < self._OrthoPickThreshold or j == 0: table.SetTableValue(j, r, g, b, 0) else: table.SetTableValue(j, r, g, b, a) transform = self._OrthoPlanes.GetTransform() pos = transform.TransformPoint(self._OrthoPlanes.GetOrthoCenter()) cpos = renderer.GetActiveCamera().GetPosition() cnorm = (cpos[0] - pos[0], cpos[1] - pos[1], cpos[2] - pos[2]) n = math.sqrt(cnorm[0] ** 2 + cnorm[1] ** 2 + cnorm[2] ** 2) cnorm = (old_div(cnorm[0], n), old_div(cnorm[1], n), old_div(cnorm[2], n)) origins = [] normals = [] cplanes = self._CornerClippingPlanes bplanes = self._CubeClippingPlanes cplanes.InitTraversal() bplanes.InitTraversal() for plane in self._OrthoPlanes.GetPlanes(): origin = plane.GetOrigin() normal = plane.GetNormal() originw = transform.TransformPoint(origin) normalw = transform.TransformNormal(normal) if (cnorm[0] * normalw[0] + cnorm[1] * normalw[1] + cnorm[2] * normalw[2] > 0): normalw = (-normalw[0], -normalw[1], -normalw[2]) else: normal = (-normal[0], -normal[1], -normal[2]) origins.append(origin) normals.append(normal) # this is a brute-force way of matching the planes cplane = cplanes.GetNextItem() cplane.SetOrigin(originw) cplane.SetNormal(normalw) for p in self._ClippingCube.GetPlanes(): if (-normal[0], -normal[1], -normal[2]) == p.GetNormal(): bplane = bplanes.GetNextItem() bplane.SetNormal(normalw[0], normalw[1], normalw[2]) bplane.SetOrigin( transform.TransformPoint(p.GetCenter())) if bplane.EvaluateFunction(*cplane.GetOrigin()) < 0: cplane.SetOrigin(bplane.GetOrigin()) break cplane = cplanes.GetNextItem() cplane.SetOrigin(originw) cplane.SetNormal(-normalw[0], -normalw[1], -normalw[2]) for p in self._ClippingCube.GetPlanes(): if normal == p.GetNormal(): bplane = bplanes.GetNextItem() bplane.SetNormal(-normalw[0], -normalw[1], -normalw[2]) bplane.SetOrigin( transform.TransformPoint(p.GetCenter())) if bplane.EvaluateFunction(*cplane.GetOrigin()) < 0: cplane.SetOrigin(bplane.GetOrigin()) break # make sure orthoplanes are drawn after the volume k = 0 for plane in self._OrthoPlanes.GetPlanes(): i = 0 for actor in plane.GetActors(renderer): texture = actor.GetTexture() if not texture: continue if texture.GetLookupTable() != self._OrthoPlanesLookupTables[i]: texture.SetLookupTable( self._OrthoPlanesLookupTables[i]) texture.MapColorScalarsThroughLookupTableOn() # these next three lines are a real hack to force the # color mapping to be done by the texture, not by # vtkImageMapToColors source = texture.GetInput().GetSource() while not source.IsA("vtkImageReslice"): source = source.GetInput().GetSource() texture.SetInput(source.GetOutput()) if actor.GetProperty().GetOpacity() != 0.999: property = vtk.vtkProperty() actor.GetProperty().DeepCopy(property) actor.SetProperty(property) actor.GetProperty().SetOpacity(0.999) mapper = actor.GetMapper() planes = mapper.GetClippingPlanes() if not planes or planes.GetNumberOfItems() != 6: planes = vtk.vtkPlaneCollection() for j in range(6): planes.AddItem(vtk.vtkPlane()) mapper.SetClippingPlanes(planes) planes.InitTraversal() bplanes.InitTraversal() for j in range(6): np = planes.GetNextItem() bplane = bplanes.GetNextItem() # an ugly hack to ensure exact rounding for comparison np.SetNormal(transform.TransformNormal(normals[old_div(j, 2)])) if old_div(j, 2) != k and bplane.GetNormal() == np.GetNormal() and \ bplane.EvaluateFunction(*origins[old_div(j, 2)]) > 0: np.SetOrigin(origins[old_div(j, 2)]) np.SetNormal(normals[old_div(j, 2)]) else: np.SetOrigin(transform.GetInverse(). TransformPoint(bplane.GetOrigin())) np.SetNormal(transform.GetInverse(). TransformNormal(bplane.GetNormal())) i = i + 1 if planeIndex != oldPlaneIndex or self._StatusChange: renderer.AddActor(actor) k = k + 1 # put all the other actors back if planeIndex != oldPlaneIndex or self._StatusChange: for actor in allActorsList: renderer.AddActor(actor) self._StatusChange = 0 self._RenderTime.Modified()
def __init__(self): ActorFactory.ActorFactory.__init__(self) # whether to display the volume self._ShowVolume = 1 self._StatusChange = 0 # create a clipping cube to go with the volume self._ClippingCube = ClippingCubeFactory.ClippingCubeFactory() self.AddChild(self._ClippingCube) self._CubeClippingPlanes = vtk.vtkPlaneCollection() for i in range(6): self._CubeClippingPlanes.AddItem(vtk.vtkPlane()) # for if we clip in with OrthoPlanes self._OrthoPlanes = None self._ShowOrthoPlanes = 1 self._OrthoPlanesLookupTables = {} self._OrthoPickThreshold = 0.0025 # corner clipping planes, in pairs with opposite normals self._CornerClippingPlanes = vtk.vtkPlaneCollection() for i in range(6): self._CornerClippingPlanes.AddItem(vtk.vtkPlane()) # clipping planes for the volume, sorted for the # three chunks that will make up the final volume self._ClippingPlanes = [vtk.vtkPlaneCollection(), vtk.vtkPlaneCollection(), vtk.vtkPlaneCollection()] for i in range(3): planes = self._ClippingPlanes[i] cplanes = self._CornerClippingPlanes bplanes = self._CubeClippingPlanes if i == 0: planes.AddItem(cplanes.GetItemAsObject(0)) planes.AddItem(bplanes.GetItemAsObject(1)) planes.AddItem(bplanes.GetItemAsObject(2)) planes.AddItem(bplanes.GetItemAsObject(3)) planes.AddItem(bplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) else: planes.AddItem(bplanes.GetItemAsObject(0)) planes.AddItem(cplanes.GetItemAsObject(1)) if i == 1: planes.AddItem(cplanes.GetItemAsObject(2)) planes.AddItem(bplanes.GetItemAsObject(3)) planes.AddItem(bplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) else: planes.AddItem(bplanes.GetItemAsObject(2)) planes.AddItem(cplanes.GetItemAsObject(3)) if i == 2: planes.AddItem(cplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) else: planes.AddItem(bplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) self._Input = None # generate the pipeline self._ImagePrefilter = vtk.vtkImageShrink3D() self._ImageReslice = vtk.vtkImageReslice() self._ImageReslice.SetInterpolationModeToLinear() self._ImageMapToColors = vtk.vtkImageMapToColors() self._ImageMapToColors.SetOutputFormatToRGBA() self._ImageToStructuredPoints = vtk.vtkImageToStructuredPoints() self._ImageClipsXY = [] self._PlanesXY = [] self._ActorsXY = [] self._PropertyXY = vtk.vtkProperty() self._PropertyXY.SetDiffuse(0) self._PropertyXY.SetAmbient(1) self._ImageClipsYZ = [] self._PlanesYZ = [] self._ActorsYZ = [] self._PropertyYZ = vtk.vtkProperty() self._PropertyYZ.SetDiffuse(0) self._PropertyYZ.SetAmbient(1) self._ImageClipsZX = [] self._PlanesZX = [] self._ActorsZX = [] self._PropertyZX = vtk.vtkProperty() self._PropertyZX.SetDiffuse(0) self._PropertyZX.SetAmbient(1) # a list of the renderer info self._RendererCurrentIndex = {} self._RendererActorList = {} self._RendererObserverList = {} # a transform to apply to the image self._ImageTransform = None self._TransformToGrid = vtk.vtkTransformToGrid() # the alpha pick threshold for the volume self._PickThreshold = 0.25 # the implicit volume for finding the gradient self._ImplicitVolume = vtk.vtkImplicitVolume() # the extent of the texture maps self._VolumeResolution = (64, 64, 64) # the bounds of the volume self._VolumeBounds = None
def __init__(self): ActorFactory.ActorFactory.__init__(self) self._LookupTable = None # lookup table is currently not used self._ColorTransferFunction = None self._OpacityTransferFunction = None self._RendererObserverList = {} # create a clipping cube to go with the volume self._ClippingCube = ClippingCubeFactory.ClippingCubeFactory() self.AddChild(self._ClippingCube) self._CubeClippingPlanes = vtk.vtkPlaneCollection() for i in range(6): self._CubeClippingPlanes.AddItem(vtk.vtkPlane()) # corner clipping planes, in pairs with opposite normals self._CornerClippingPlanes = vtk.vtkPlaneCollection() for i in range(6): self._CornerClippingPlanes.AddItem(vtk.vtkPlane()) # clipping planes for the volume, sorted for the # three chunks that will make up the final volume # (these are currently unused) self._ClippingPlanes = [vtk.vtkPlaneCollection(), vtk.vtkPlaneCollection(), vtk.vtkPlaneCollection()] for i in range(3): planes = self._ClippingPlanes[i] cplanes = self._CornerClippingPlanes bplanes = self._CubeClippingPlanes if i == 0: planes.AddItem(cplanes.GetItemAsObject(0)) planes.AddItem(bplanes.GetItemAsObject(1)) planes.AddItem(bplanes.GetItemAsObject(2)) planes.AddItem(bplanes.GetItemAsObject(3)) planes.AddItem(bplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) else: planes.AddItem(bplanes.GetItemAsObject(0)) planes.AddItem(cplanes.GetItemAsObject(1)) if i == 1: planes.AddItem(cplanes.GetItemAsObject(2)) planes.AddItem(bplanes.GetItemAsObject(3)) planes.AddItem(bplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) else: planes.AddItem(bplanes.GetItemAsObject(2)) planes.AddItem(cplanes.GetItemAsObject(3)) if i == 2: planes.AddItem(cplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) else: planes.AddItem(bplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) # generate the pipeline pieces self._Input = None # transform the full-resolution volume self._RayCastReslice = vtk.vtkImageReslice() self._RayCastReslice.SetInterpolationModeToLinear() # subsample the volume for low-res rendering self._ImagePrefilter1 = vtk.vtkImageShrink3D() self._ImagePrefilter2 = vtk.vtkImageShrink3D() # transform the subsampled volume self._ImageReslice1 = vtk.vtkImageReslice() self._ImageReslice1.SetInterpolationModeToLinear() self._ImageReslice2 = vtk.vtkImageReslice() self._ImageReslice2.SetInterpolationModeToLinear() # convert to RGBA for rendering (unused) self._ImageMapToColors = vtk.vtkImageMapToColors() self._ImageMapToColors.SetOutputFormatToRGBA() # strictly for VTK 3.2 compatibility self._ImageToStructuredPoints = vtk.vtkImageToStructuredPoints() # a transform to apply to the image self._ImageTransform = None self._TransformToGrid = vtk.vtkTransformToGrid() # the opacity pick threshold for the volume self._PickThreshold = 0.99 # the implicit volume for finding the gradient self._ImplicitVolume = vtk.vtkImplicitVolume() # the texture dimensions (later this will be set automatically # to provide the desired interactive rendering time) self._TextureSize = 128 # the bounds of the volume self._VolumeBounds = None # vtkVolume specific stuff self._VolumeProperty = vtk.vtkVolumeProperty() self._VolumeProperty.SetInterpolationTypeToLinear() rayCastFunction = vtk.vtkVolumeRayCastCompositeFunction() self._VolumeRayCastMapper = vtk.vtkVolumeRayCastMapper() self._VolumeRayCastMapper.SetVolumeRayCastFunction(rayCastFunction) self._VolumeRayCastMapper.SetClippingPlanes( self._ClippingCube.GetClippingPlanes()) try: # vtk 3.2 does not contain this function call: self._VolumeRayCastMapper.AutoAdjustSampleDistancesOff() except: pass self._VolumeTextureMapper1 = vtk.vtkVolumeTextureMapper2D() self._VolumeTextureMapper1.SetTargetTextureSize(old_div(self._TextureSize, 4), old_div(self._TextureSize, 4)) self._VolumeTextureMapper1.SetMaximumNumberOfPlanes( old_div(self._TextureSize, 2)) self._VolumeTextureMapper1.SetClippingPlanes( self._ClippingCube.GetClippingPlanes()) try: # vtk 3.2 does not contain this function call: # set to the amount of available texture memory (24MB is a good # start) self._VolumeTextureMapper1.SetMaximumStorageSize(24 * 1024 * 1024) except: pass self._VolumeTextureMapper2 = vtk.vtkVolumeTextureMapper2D() self._VolumeTextureMapper2.SetTargetTextureSize(self._TextureSize, self._TextureSize) self._VolumeTextureMapper2.SetMaximumNumberOfPlanes(self._TextureSize) self._VolumeTextureMapper2.SetClippingPlanes( self._ClippingCube.GetClippingPlanes()) try: # vtk 3.2 does not contain this function call: # set to the amount of available texture memory (24MB is a good # start) self._VolumeTextureMapper2.SetMaximumStorageSize(24 * 1024 * 1024) except: pass # set two levels of detail: texture and ray-casting self._Volume = vtk.vtkLODProp3D() self._Volume.PickableOff() idT1 = self._Volume.AddLOD(self._VolumeTextureMapper1, self._VolumeProperty, 0.02) idT2 = self._Volume.AddLOD(self._VolumeTextureMapper2, self._VolumeProperty, 0.1) # remember these LOD id numbers self._lod = [idT1, idT2] # idRC = self._Volume.AddLOD(self._VolumeRayCastMapper, # self._VolumeProperty, # 2.0) self._Volume.SetLODLevel(idT1, 2.0) self._Volume.SetLODLevel(idT2, 1.0)
def __init__(self, runname, input_file, output_file, radius, x, y, z): self.runname = runname reader = vtk.vtkPolyDataReader() reader.SetFileName(input_file) reader.Update() planes = vtk.vtkPlaneCollection() top = vtk.vtkPlane() top.SetNormal(0, 0, -1) top.SetOrigin(x, y, z + radius) planes.AddItem(top) bottom = vtk.vtkPlane() bottom.SetNormal(0, 0, 1) bottom.SetOrigin(x, y, z - radius) planes.AddItem(bottom) front = vtk.vtkPlane() front.SetNormal(0, -1, 0) front.SetOrigin(x, y + radius, z) planes.AddItem(front) back = vtk.vtkPlane() back.SetNormal(0, 1, 0) back.SetOrigin(x, y - radius, z) planes.AddItem(back) right = vtk.vtkPlane() right.SetNormal(1, 0, 0) right.SetOrigin(x - radius, y, z) planes.AddItem(right) left = vtk.vtkPlane() left.SetNormal(-1, 0, 0) left.SetOrigin(x + radius, y, z) planes.AddItem(left) clipper = vtk.vtkClipClosedSurface() clipper.SetClippingPlanes(planes) clipper.SetInputConnection(reader.GetOutputPort()) connectivity = vtk.vtkPolyDataConnectivityFilter() connectivity.SetExtractionModeToAllRegions() connectivity.SetInputConnection(clipper.GetOutputPort()) connectivity.Update() specified = vtk.vtkPolyDataConnectivityFilter() specified.SetExtractionModeToSpecifiedRegions() specified.SetInputConnection(clipper.GetOutputPort()) tester = vtk.vtkPolyDataConnectivityFilter() tester.SetExtractionModeToSpecifiedRegions() tester.SetInputConnection(clipper.GetOutputPort()) dims = {} for i in range(connectivity.GetNumberOfExtractedRegions()): tester.AddSpecifiedRegion(i) tester.Update() bounds = tester.GetOutput().GetBounds() if bounds[0] + radius - delta < x or bounds[1] - radius + delta > x or \ bounds[2] + radius - delta < y or bounds[3] - radius + delta > y or \ bounds[4] + radius - delta < z or bounds[5] - radius + delta > z: mindim = min(bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4]) dims[i] = mindim tester.DeleteSpecifiedRegion(i) for i in sorted(dims.iteritems(), key=lambda i: i[1], reverse=True)[0:5]: print i specified.AddSpecifiedRegion(i[0]) #cleaner = vtk.vtkCleanPolyData() #cleaner.SetInputConnection(specified.GetOutputPort()) #cleaner.SetTolerance(1e-5) #orientator = vtk.vtkPolyDataNormals() #orientator.SetInputConnection(clipper.GetOutputPort()) #orientator.ConsistencyOn() #orientator.AutoOrientNormalsOn() writer = vtk.vtkSTLWriter() writer.SetFileName(output_file + 'tmp1.stl') writer.SetInputConnection(clipper.GetOutputPort()) writer.Write() with open("/tmp/test.mlx", "w") as f: f.write(""" <FilterScript> <filter name="Remove Zero Area Faces"/> <filter name="Re-Orient all faces coherentely"/> <filter name="Quadric Edge Collapse Decimation"> <Param type="RichInt" value="30000" name="TargetFaceNum"/> <Param type="RichFloat" value="0" name="TargetPerc"/> <Param type="RichFloat" value="0.3" name="QualityThr"/> <Param type="RichBool" value="false" name="PreserveBoundary"/> <Param type="RichBool" value="false" name="PreserveNormal"/> <Param type="RichBool" value="true" name="PreserveTopology"/> <Param type="RichBool" value="true" name="OptimalPlacement"/> <Param type="RichBool" value="false" name="PlanarQuadric"/> <Param type="RichBool" value="false" name="QualityWeight"/> <Param type="RichBool" value="true" name="AutoClean"/> <Param type="RichBool" value="false" name="Selected"/> </filter> </FilterScript> """) subprocess.call(["meshlabserver", "-i", output_file + 'tmp1.stl', "-o", output_file + '.off', "-s", "/tmp/test.mlx"]) #reader = vtk.vtkSTLReader() #reader.SetFileName(output_file + 'tmp2.stl') #reader.Update() writer = vtk.vtkSTLWriter() writer.SetFileName(output_file) writer.SetInputConnection(specified.GetOutputPort()) writer.Write() vtk_writer = vtk.vtkXMLPolyDataWriter() vtk_writer.SetFileName(output_file + ".vtu") vtk_writer.SetInputConnection(specified.GetOutputPort()) vtk_writer.Write()
def GetPlaneEquations(self): planes = vtk.vtkPlaneCollection() for plane in self._Planes: planes.AddItem(plane.GetPlaneEquation()) return planes