def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) InputArrayChoiceMixin.__init__(self) self._config.scaleFactor = 1 configList = [ ('Scale factor:', 'scaleFactor', 'base:float', 'text', 'The warping will be scaled by this factor'), ('Vectors selection:', 'vectorsSelection', 'base:str', 'choice', 'The attribute that will be used as vectors for the warping.', (self._defaultVectorsSelectionString, self._userDefinedString))] self._warpVector = vtk.vtkWarpVector() ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkWarpVector' : self._warpVector}) module_utils.setup_vtk_object_progress(self, self._warpVector, 'Warping points.') self.sync_module_logic_with_config()
def run_vtk(hdf5_filename: str, scale: float): #alg = HDF5Source() alg = H5NastranReader() alg.SetFileName(hdf5_filename) #cf = vtk.vtkContourFilter() #cf.SetInputConnection(alg.GetOutputPort()) #cf.SetValue(0, 200) model, ugrid, root, alt_grids = get_nastran_ugrid(hdf5_filename) ugrid = alt_grids['main'] warp = vtk.vtkWarpVector() warp.SetScaleFactor(scale) warp.SetInputData(ugrid) warp.Update() #warp = ugrid grid_mapper = vtk.vtkDataSetMapper() if 0: grid_mapper.SetInputData(ugrid) else: grid_mapper.SetInputData(warp.GetOutput()) #grid_mapper = vtk.vtkPolyDataMapper() #grid_mapper.SetInputConnection(ugrid.GetOutputPort()) actor = vtk.vtkLODActor() actor.SetMapper(grid_mapper) add_actor_to_renderer(actor) print('go')
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) InputArrayChoiceMixin.__init__(self) self._config.scaleFactor = 1 configList = [ ('Scale factor:', 'scaleFactor', 'base:float', 'text', 'The warping will be scaled by this factor'), ('Vectors selection:', 'vectorsSelection', 'base:str', 'choice', 'The attribute that will be used as vectors for the warping.', (self._defaultVectorsSelectionString, self._userDefinedString)) ] self._warpVector = vtk.vtkWarpVector() ScriptedConfigModuleMixin.__init__(self, configList, { 'Module (self)': self, 'vtkWarpVector': self._warpVector }) module_utils.setup_vtk_object_progress(self, self._warpVector, 'Warping points.') self.sync_module_logic_with_config()
def apply_modes(self, modes_with_scales): for mode, scale in modes_with_scales.items(): print('Applying ' + mode + ' multiplied by ' + str(scale)) self.mesh.GetOutput().GetPointData().SetActiveVectors(mode) warp_vector = vtk.vtkWarpVector() warp_vector.SetInputConnection(self.mesh.GetOutputPort()) warp_vector.SetScaleFactor(scale) warp_vector.Update() self.mesh = warp_vector
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkWarpVector(), 'Processing.', ('vtkPointSet', ), ('vtkPointSet', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def main(): file_name, color_scheme = get_program_parameters() colors = vtk.vtkNamedColors() # Read a vtk file # plate = vtk.vtkPolyDataReader() plate.SetFileName(file_name) plate.SetVectorsName("mode8") plate.Update() warp = vtk.vtkWarpVector() warp.SetInputConnection(plate.GetOutputPort()) warp.SetScaleFactor(0.5) normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(warp.GetOutputPort()) color = vtk.vtkVectorDot() color.SetInputConnection(normals.GetOutputPort()) lut = vtk.vtkLookupTable() MakeLUT(color_scheme, lut) plateMapper = vtk.vtkDataSetMapper() plateMapper.SetInputConnection(color.GetOutputPort()) plateMapper.SetLookupTable(lut) plateMapper.SetScalarRange(-1, 1) plateActor = vtk.vtkActor() plateActor.SetMapper(plateMapper) # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren.AddActor(plateActor) ren.SetBackground(colors.GetColor3d("Wheat")) renWin.SetSize(512, 512) ren.GetActiveCamera().SetPosition(13.3991, 14.0764, 9.97787) ren.GetActiveCamera().SetFocalPoint(1.50437, 0.481517, 4.52992) ren.GetActiveCamera().SetViewAngle(30) ren.GetActiveCamera().SetViewUp(-0.120861, 0.458556, -0.880408) ren.GetActiveCamera().SetClippingRange(12.5724, 26.8374) # Render the image. renWin.Render() iren.Start()
def getWarpedMesh(mesh, displacement_field_name='displacement'): mesh.GetPointData().SetActiveVectors(displacement_field_name) warp = vtk.vtkWarpVector() warp.SetInputData(mesh) warp.Update() mesh = warp.GetOutput() return mesh
def __init__ (self, mod_m): debug ("In WarpVectorCutPlane::__init__ ()") Common.state.busy () Base.Objects.CutPlaneModule.__init__ (self, mod_m) self.cut = vtk.vtkCutter () self.warp = vtk.vtkWarpVector () self.norm = vtk.vtkPolyDataNormals () self.mapper = self.map = vtk.vtkPolyDataMapper () self.map.SetLookupTable (self.mod_m.get_scalar_lut ()) self.actor = self.act = vtk.vtkActor () self.data_out = self.mod_m.GetOutput () self._initialize () self._gui_init () self.renwin.Render () Common.state.idle ()
def sliceDown(self): # Warp using the normals warp = vtk.vtkWarpVector() warp.SetInputData(fixMesh(downsample(self.currentPeel))) # fixMesh here updates normals needed for warping warp.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject().FIELD_ASSOCIATION_POINTS, vtk.vtkDataSetAttributes().NORMALS) warp.SetScaleFactor(-1) warp.Update() out = vtk.vtkPolyData() out = upsample(warp.GetPolyDataOutput()) out = smooth(out) out = fixMesh(out) out = cleanMesh(out) self.currentPeel = out
def getMeshVolume( mesh, warp_mesh=1 ): if warp_mesh == 1: warp = vtk.vtkWarpVector() warp.SetInputData(mesh) warp.Update() mesh = warp.GetOutput() polydata = myvtk.ugrid2pdata(mesh) mass = myvtk.getMassProperties(polydata) volume = mass.GetVolume() return volume
def main(args): INDIR = args.indir FILENAME = args.input_filename OUTDIR = args.outdir WARP_VECTOR_NAME = args.warp_vec_name mesh = intializeVTP(INDIR + FILENAME) mesh.GetPointData().SetActiveVectors(WARP_VECTOR_NAME) warpVector = vtk.vtkWarpVector() warpVector.SetInputData(mesh) warpVector.Update() if (args.output_filename is None): output_filename = OUTDIR + '/Warped_' + FILENAME else: output_filename = OUTDIR + args.output_filename writeVTP(warpVector.GetOutput(), output_filename)
def _getElementMetrics(self): for k, p in self.polydatas.items(): # create a deformed polydata object for deformed metrics warp = vtk.vtkWarpVector() warp.SetInputData(p) warp.SetScaleFactor(1) p.GetPointData().SetActiveVectors('displacement') warp.Update() warped = warp.GetOutput() # Use the MeshQuality filter with the metric set to volume to quickly get cell volumes # for reference and deformed cases. mesh_quality = vtk.vtkMeshQuality() mesh_quality.SetTetQualityMeasureToVolume() mesh_quality.SetInputData(p) mesh_quality.Update() r_volumes = mesh_quality.GetOutput().GetCellData().GetArray("Quality") r_volumes.SetName('Reference Volume') p.GetCellData().AddArray(r_volumes) mesh_quality2 = vtk.vtkMeshQuality() mesh_quality2.SetTetQualityMeasureToVolume() mesh_quality2.SetInputData(warped) mesh_quality2.Update() d_volumes = mesh_quality2.GetOutput().GetCellData().GetArray("Quality") d_volumes.SetName('Deformed Volume') p.GetCellData().AddArray(d_volumes) # CellCenters filter generates new polydata with points at centroids. Grab these points # data array and add it to polydata for reference and deformed. cell_centers = vtk.vtkCellCenters() cell_centers.VertexCellsOff() cell_centers.SetInputData(p) cell_centers.Update() r_centroids = cell_centers.GetOutput().GetPoints().GetData() r_centroids.SetName('Reference Centroid') p.GetCellData().AddArray(r_centroids) cell_centers2 = vtk.vtkCellCenters() cell_centers2.VertexCellsOff() cell_centers2.SetInputData(warped) cell_centers2.Update() d_centroids = cell_centers2.GetOutput().GetPoints().GetData() d_centroids.SetName('Deformed Centroid') p.GetCellData().AddArray(d_centroids)
def warpVTU(data_vtu_in, array_type, array_name): # type: (object, object, object) -> object if array_type == 'point': if data_vtu_in.GetPointData().HasArray(array_name): data_vtu_in.GetPointData().SetActiveVectors(array_name) else: print("Point data array '%s' does not exist" % array_name) elif array_type == 'cell': if data_vtu_in.GetCellData().HasArray(array_name): data_vtu_in.GetCellData().SetActiveVectors(array_name) else: print("Cell data array '%s' does not exist" % array_name) else: print("Array type '%s' undefined" % array_type) warpVector = vtk.vtkWarpVector() warpVector.SetInputData(data_vtu_in) warpVector.Update() model_vtu_deformed = warpVector.GetOutput() return model_vtu_deformed
fd2ad.SetInputData(do2ds.GetRectilinearGridOutput()) fd2ad.SetInputFieldToDataObjectField() fd2ad.SetOutputAttributeDataToPointData() fd2ad.SetVectorComponent(0, "vectors", 0) fd2ad.SetVectorComponent(1, "vectors", 1) fd2ad.SetVectorComponent(2, "vectors", 2) fd2ad.SetScalarComponent(0, "scalars", 0) fd2ad.Update() # create pipeline # plane = vtk.vtkRectilinearGridGeometryFilter() plane.SetInputData(fd2ad.GetRectilinearGridOutput()) plane.SetExtent(0, 100, 0, 100, 15, 15) warper = vtk.vtkWarpVector() warper.SetInputConnection(plane.GetOutputPort()) warper.SetScaleFactor(0.05) planeMapper = vtk.vtkDataSetMapper() planeMapper.SetInputConnection(warper.GetOutputPort()) planeMapper.SetScalarRange(0.197813, 0.710419) planeActor = vtk.vtkActor() planeActor.SetMapper(planeMapper) cutPlane = vtk.vtkPlane() cutPlane.SetOrigin(fd2ad.GetOutput().GetCenter()) cutPlane.SetNormal(1, 0, 0) planeCut = vtk.vtkCutter()
def determineCapPerfusionVolumes(caps,cap_center_coordinates,heart): numPts = heart.GetNumberOfPoints() heart_data = [0]*numPts heart_graph = Graph() cap_heart_points = set() for i in cap_center_coordinates: cap_heart_points.add(heart.FindPoint(i)) heart_graph = generateGraph(heart) heart = multipleCapSourceDistance(heart,heart_graph,100000000000,cap_heart_points) for i in range(0,numPts): connnectedPt_list = getConnectedVerticesNotIncludingSeed(heart,i) for j in range(0,connnectedPt_list.GetNumberOfIds()): # new point to decide whether to add to patch, edge, or nothing (if already in edge) cpt = connnectedPt_list.GetId(j) heart_graph.add_edge(i,cpt,calcDistance2Points(heart,i,cpt)) heart_graph.add_edge(cpt,i,calcDistance2Points(heart,i,cpt)) print(cap_heart_points) for i in range(0,len(cap_center_coordinates)): if heart.FindPoint(cap_center_coordinates[i]) in heart_graph.nodes: visited, path = dijsktra(heart_graph,heart.FindPoint(cap_center_coordinates[i])) data_array = vtk.vtkDoubleArray() data_array.SetName(caps[i] + '_distance_map') for i in range(0,numPts): if i in visited: data_array.InsertNextValue(visited[i]) else: data_array.InsertNextValue(-1) heart.GetPointData().AddArray(data_array) writeVTU(heart,'heart_distance_mapped.vtu') for ip in range(0,numPts): value = image.GetPointData().GetArray(0).GetValue(image.FindPoint(heart.GetPoint(ip))) min,min_pt_index = minDistanceBetweenPointsGraph(heart_graph, heart, ip, cap_center_coordinates) heart_data[ip] = min_pt_index #generate summary data array for perfusion data_array = vtk.vtkDoubleArray() data_array.SetName('PerfusionVolumes') for ptID in range(0,numPts): data_array.InsertNextValue(heart_data[ptID]) heart.GetPointData().AddArray(data_array) perfusion_data = np.zeros((len(caps),numPts)) for ip in range(0,len(heart_data)): if(heart_data[ip]>=0): perfusion_data[heart_data[ip],ip] = 1 #generate separate data array for each perfusion volume #calculate the volume of each perfused area of each cap volumes = [] LCA_data = np.zeros(numPts) RCA_data = np.zeros(numPts) RSA_data = np.zeros(numPts) CA_data = np.zeros(numPts) cap_pt_list = vtk.vtkIdList() for i in tqdm(range(0,len(perfusion_data))): data = vtk.vtkDoubleArray() data.SetName(str(i) + '_' + caps[i]) for ip in range(0,numPts): if(perfusion_data[i,ip]>0): cap_pt_list.InsertNextId(ip) if(caps[i].startswith('LCA')): LCA_data[ip] = perfusion_data[i,ip] CA_data[ip] = 1 elif(caps[i].startswith('RCA')): RCA_data[ip] = perfusion_data[i,ip] CA_data[ip] = 2 elif(caps[i].startswith('RSA')): RSA_data[ip] = perfusion_data[i,ip] CA_data[ip] = 3 data.InsertNextValue(perfusion_data[i,ip]) heart.GetPointData().AddArray(data) Mass = extractRegionVolume(heart,cap_pt_list) p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(heart) p2c.PassPointDataOn() warp = vtk.vtkWarpVector() warp.SetInputConnection(p2c.GetOutputPort()) thresh = vtk.vtkThreshold() thresh.SetInputConnection(warp.GetOutputPort()) thresh.ThresholdBetween(i,i) thresh.SetInputArrayToProcess(1, 0, 0, 0, "PerfusionVolumes") volumes.append(Mass.GetVolume()) cap_pt_list.Reset() heart.GetPointData().AddArray(convert_np_array_to_vtk('LCA_all',LCA_data)) heart.GetPointData().AddArray(convert_np_array_to_vtk('RCA_all',RCA_data)) heart.GetPointData().AddArray(convert_np_array_to_vtk('RSA_all',RSA_data)) heart.GetPointData().AddArray(convert_np_array_to_vtk('CA_all',CA_data)) return volumes
def generateWarpedImages( ref_image_folder, ref_image_basename, sol_folder, sol_basename, ref_frame=0, sol_ext="vtu", verbose=0): myVTK.myPrint(verbose, "*** generateWarpedImages ***") ref_image_zfill = len(glob.glob(ref_image_folder+"/"+ref_image_basename+"_*.vti")[0].rsplit("_")[-1].split(".")[0]) ref_image_filename = ref_image_folder+"/"+ref_image_basename+"_"+str(ref_frame).zfill(ref_image_zfill)+".vti" ref_image = myVTK.readImage( filename=ref_image_filename) interpolator = myVTK.createImageInterpolator( image=ref_image) #I = numpy.empty(1) #interpolator.Interpolate([0.35, 0.25, 0.], I) image = vtk.vtkImageData() image.SetOrigin(ref_image.GetOrigin()) image.SetSpacing(ref_image.GetSpacing()) image.SetExtent(ref_image.GetExtent()) if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): image.AllocateScalars(vtk.VTK_FLOAT, 1) else: image.SetScalarTypeToFloat() image.SetNumberOfScalarComponents(1) image.AllocateScalars() scalars = image.GetPointData().GetScalars() sol_zfill = len(glob.glob(sol_folder+"/"+sol_basename+"_*."+sol_ext)[0].rsplit("_")[-1].split(".")[0]) n_frames = len(glob.glob(sol_folder+"/"+sol_basename+"_"+"[0-9]"*sol_zfill+"."+sol_ext)) #n_frames = 1 X = numpy.empty(3) U = numpy.empty(3) x = numpy.empty(3) I = numpy.empty(1) m = numpy.empty(1) for k_frame in xrange(n_frames): myVTK.myPrint(verbose, "k_frame = "+str(k_frame)) mesh = myVTK.readUGrid( filename=sol_folder+"/"+sol_basename+"_"+str(k_frame).zfill(sol_zfill)+"."+sol_ext) #print mesh warp = vtk.vtkWarpVector() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): warp.SetInputData(mesh) else: warp.SetInput(mesh) warp.Update() warped_mesh = warp.GetOutput() #myVTK.writeUGrid( #ugrid=warped_mesh, #filename=sol_folder+"/"+sol_basename+"-warped_"+str(k_frame).zfill(sol_zfill)+"."+sol_ext) probe = vtk.vtkProbeFilter() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): probe.SetInputData(image) probe.SetSourceData(warped_mesh) else: probe.SetInput(image) probe.SetSource(warped_mesh) probe.Update() probed_image = probe.GetOutput() scalars_mask = probed_image.GetPointData().GetArray("vtkValidPointMask") scalars_U = probed_image.GetPointData().GetArray("displacement") #myVTK.writeImage( #image=probed_image, #filename=sol_folder+"/"+sol_basename+"_"+str(k_frame).zfill(sol_zfill)+".vti") for k_point in xrange(image.GetNumberOfPoints()): scalars_mask.GetTuple(k_point, m) if (m[0] == 0): I[0] = 0. else: image.GetPoint(k_point, x) scalars_U.GetTuple(k_point, U) X = x - U interpolator.Interpolate(X, I) scalars.SetTuple(k_point, I) myVTK.writeImage( image=image, filename=sol_folder+"/"+sol_basename+"-warped_"+str(k_frame).zfill(sol_zfill)+".vti")
def main(): fileName, dataPoint = get_program_parameters() colors = vtk.vtkNamedColors() thickness = list() displacement = list() for i in range(0, 10): thickness.append('thickness' + str(i)) displacement.append('displacement' + str(i)) reader = list() warp = list() connect = list() mold = list() moldMapper = list() moldActor = list() connect2 = list() parison = list() normals2 = list() parisonMapper = list() parisonActor = list() cf = list() contourMapper = list() contours = list() ren = list() lut = vtk.vtkLookupTable() lut.SetHueRange(0.0, 0.66667) for i in range(0, 10): # Create the reader and warp the data vith vectors. reader.append(vtk.vtkDataSetReader()) reader[i].SetFileName(fileName) reader[i].SetScalarsName(thickness[i]) reader[i].SetVectorsName(displacement[i]) reader[i].Update() warp.append(vtk.vtkWarpVector()) warp[i].SetInputData(reader[i].GetUnstructuredGridOutput()) # Extract the mold from the mesh using connectivity. connect.append(vtk.vtkConnectivityFilter()) connect[i].SetInputConnection(warp[i].GetOutputPort()) connect[i].SetExtractionModeToSpecifiedRegions() connect[i].AddSpecifiedRegion(0) connect[i].AddSpecifiedRegion(1) mold.append(vtk.vtkGeometryFilter()) mold[i].SetInputConnection(connect[i].GetOutputPort()) moldMapper.append(vtk.vtkDataSetMapper()) moldMapper[i].SetInputConnection(mold[i].GetOutputPort()) moldMapper[i].ScalarVisibilityOff() moldActor.append(vtk.vtkActor()) moldActor[i].SetMapper(moldMapper[i]) moldActor[i].GetProperty().SetColor(colors.GetColor3d("ivory_black")) moldActor[i].GetProperty().SetRepresentationToWireframe() # Extract the parison from the mesh using connectivity. connect2.append(vtk.vtkConnectivityFilter()) connect2[i].SetInputConnection(warp[i].GetOutputPort()) connect2[i].SetExtractionModeToSpecifiedRegions() connect2[i].AddSpecifiedRegion(2) parison.append(vtk.vtkGeometryFilter()) parison[i].SetInputConnection(connect2[i].GetOutputPort()) normals2.append(vtk.vtkPolyDataNormals()) normals2[i].SetInputConnection(parison[i].GetOutputPort()) normals2[i].SetFeatureAngle(60) parisonMapper.append(vtk.vtkPolyDataMapper()) parisonMapper[i].SetInputConnection(normals2[i].GetOutputPort()) parisonMapper[i].SetLookupTable(lut) parisonMapper[i].SetScalarRange(0.12, 1.0) parisonActor.append(vtk.vtkActor()) parisonActor[i].SetMapper(parisonMapper[i]) cf.append(vtk.vtkContourFilter()) cf[i].SetInputConnection(connect2[i].GetOutputPort()) cf[i].SetValue(0, 0.5) contourMapper.append(vtk.vtkPolyDataMapper()) contourMapper[i].SetInputConnection(cf[i].GetOutputPort()) contours.append(vtk.vtkActor()) contours[i].SetMapper(contourMapper[i]) ren.append(vtk.vtkRenderer()) ren[i].AddActor(moldActor[i]) ren[i].AddActor(parisonActor[i]) ren[i].AddActor(contours[i]) ren[i].SetBackground(colors.GetColor3d("AliceBlue")) ren[i].GetActiveCamera().SetPosition(50.973277, 12.298821, 29.102547) ren[i].GetActiveCamera().SetFocalPoint(0.141547, 12.298821, -0.245166) ren[i].GetActiveCamera().SetViewUp(-0.500000, 0.000000, 0.866025) ren[i].GetActiveCamera().SetClippingRange(36.640827, 78.614680) # Create the RenderWindow and RenderWindowInteractor. renWin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) rendererSizeX = 750 rendererSizeY = 400 renWinScale = 0.5 renWin.SetWindowName("Blow") if 0 <= dataPoint < 10: renWin.AddRenderer(ren[dataPoint]) renWin.SetSize(rendererSizeX, rendererSizeY) else: gridDimensionsX = 2 gridDimensionsY = 5 renWin.SetSize(int(rendererSizeX * gridDimensionsX * renWinScale), int(rendererSizeY * gridDimensionsY * renWinScale)) # Add and position the renders to the render window. viewPort = list() for row in range(0, gridDimensionsY): for col in range(0, gridDimensionsX): idx = row * gridDimensionsX + col x0 = float(col) / gridDimensionsX y0 = float(gridDimensionsY - row - 1) / gridDimensionsY x1 = float(col + 1) / gridDimensionsX y1 = float(gridDimensionsY - row) / gridDimensionsY viewPort[:] = [] viewPort.append(x0) viewPort.append(y0) viewPort.append(x1) viewPort.append(y1) renWin.AddRenderer(ren[idx]) ren[idx].SetViewport(viewPort) iren.Initialize() iren.Start()
def animate(self, pd, ind): """ Helper function called by **deformableRegistration** if **animate** is *True*. Spawns a window with an interactive 3-D rendering of the current analyzed object in its reference state. The displacements calculated from the deformable image registration can be applied to this object to animate the deformation by pressing the RIGHT-ARROW. Pressing the UP-ARROW will animate and also save the frames to disk. Parameters ---------- pd : vtkPolyData The current analyzed object's reference geometry. ind : int The index of the current polydata in **rsurfs**. Necessary for naming directory created if animation frames are saved. """ pd.GetPointData().SetActiveVectors("Displacement") class vtkTimerCallback(object): def __init__(self): self.timer_count = 0 def execute(self, obj, event): if self.timer_count == 10: self.timer_count = 0 warpVector = vtk.vtkWarpVector() warpVector.SetInputData(pd) warpVector.SetScaleFactor(0.1 * (self.timer_count + 1)) warpVector.Update() poly = warpVector.GetPolyDataOutput() getScalars = vtk.vtkExtractVectorComponents() getScalars.SetInputData(poly) getScalars.Update() vectorNorm = vtk.vtkVectorNorm() vectorNorm.SetInputData(poly) vectorNorm.Update() scalars = [] scalars.append(getScalars.GetVzComponent()) scalars.append(vectorNorm.GetOutput()) scalars.append(getScalars.GetVxComponent()) scalars.append(getScalars.GetVyComponent()) names = ("Z", "Mag", "X", "Y") for k, a in enumerate(self.actors): calc = vtk.vtkArrayCalculator() scalars[k].GetPointData().GetScalars().SetName(names[k]) calc.SetInputData(scalars[k]) calc.AddScalarArrayName(names[k]) calc.SetResultArrayName(names[k]) calc.SetFunction("%s * 0.1 * %f" % (names[k], self.timer_count + 1)) calc.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(calc.GetOutput()) mapper.SetScalarRange(calc.GetOutput().GetScalarRange()) mapper.SetScalarModeToUsePointData() mapper.SetColorModeToMapScalars() mapper.Update() a.SetMapper(mapper) cb.scalar_bars[k].SetLookupTable(mapper.GetLookupTable()) iren = obj iren.GetRenderWindow().Render() time.sleep(0.3) if self.key == "Up": try: os.mkdir(self.directory) except: pass w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(obj.GetRenderWindow()) w2i.Update() png = vtk.vtkPNGWriter() png.SetInputConnection(w2i.GetOutputPort()) png.SetFileName(self.directory + os.sep + "frame{:d}.png".format(self.timer_count)) png.Update() png.Write() self.timer_count += 1 def Keypress(self, obj, event): self.key = obj.GetKeySym() if self.key == "Right" or self.key == "Up": for i in range(10): obj.CreateOneShotTimer(1) renwin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renwin) iren.Initialize() cb = vtkTimerCallback() xmins = (0, 0.5, 0, 0.5) xmaxs = (0.5, 1, 0.5, 1) ymins = (0, 0, 0.5, 0.5) ymaxs = (0.5, 0.5, 1, 1) titles = ('Z Displacement', 'Magnitude', 'X Displacement', 'Y Displacement') cb.actors = [] cb.scalar_bars = [] cb.directory = str( os.path.normpath(self._def_dir + os.sep + "animation{:0d}".format(ind + 1))) warpVector = vtk.vtkWarpVector() warpVector.SetInputData(pd) warpVector.Update() poly = warpVector.GetPolyDataOutput() getScalars = vtk.vtkExtractVectorComponents() getScalars.SetInputData(poly) getScalars.Update() vectorNorm = vtk.vtkVectorNorm() vectorNorm.SetInputData(poly) vectorNorm.Update() scalars = [] scalars.append(getScalars.GetVzComponent()) scalars.append(vectorNorm.GetOutput()) scalars.append(getScalars.GetVxComponent()) scalars.append(getScalars.GetVyComponent()) bounds = np.zeros(6, np.float32) pd.GetBounds(bounds) length = np.min(bounds[1::2] - bounds[0:-1:2]) * 0.2 bounds[1] = bounds[0] + length bounds[3] = bounds[2] + length bounds[5] = bounds[4] + length for j in range(4): mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(scalars[j]) mapper.SetScalarRange(scalars[j].GetScalarRange()) mapper.SetScalarModeToUsePointData() mapper.SetColorModeToMapScalars() scalar_bar = vtk.vtkScalarBarActor() scalar_bar.SetLookupTable(mapper.GetLookupTable()) scalar_bar.SetTitle(titles[j]) scalar_bar.SetLabelFormat("%3.3f") cb.scalar_bars.append(scalar_bar) actor = vtk.vtkActor() actor.SetMapper(mapper) cb.actors.append(actor) renderer = vtk.vtkRenderer() renderer.SetBackground(0., 0., 0.) renwin.AddRenderer(renderer) if j == 0: camera = renderer.GetActiveCamera() else: renderer.SetActiveCamera(camera) triad = vtk.vtkCubeAxesActor() triad.SetCamera(camera) triad.SetFlyModeToStaticTriad() triad.SetBounds(bounds) triad.GetXAxesLinesProperty().SetColor(1.0, 0.0, 0.0) triad.GetYAxesLinesProperty().SetColor(0.0, 1.0, 0.0) triad.GetZAxesLinesProperty().SetColor(0.0, 0.0, 1.0) triad.GetXAxesLinesProperty().SetLineWidth(3.0) triad.GetYAxesLinesProperty().SetLineWidth(3.0) triad.GetZAxesLinesProperty().SetLineWidth(3.0) triad.XAxisLabelVisibilityOff() triad.YAxisLabelVisibilityOff() triad.ZAxisLabelVisibilityOff() triad.XAxisTickVisibilityOff() triad.YAxisTickVisibilityOff() triad.ZAxisTickVisibilityOff() triad.XAxisMinorTickVisibilityOff() triad.YAxisMinorTickVisibilityOff() triad.ZAxisMinorTickVisibilityOff() renderer.SetViewport(xmins[j], ymins[j], xmaxs[j], ymaxs[j]) renderer.AddActor(actor) renderer.AddActor2D(scalar_bar) renderer.AddActor(triad) renderer.ResetCamera() renwin.Render() iren.AddObserver('TimerEvent', cb.execute) iren.AddObserver('KeyPressEvent', cb.Keypress) iren.Start()
def __init__(self): """ Called when the logic class is instantiated. Can be used for initializing member variables. """ ScriptedLoadableModuleLogic.__init__(self) self.inputCurveNode = None self.inputCurveNodeObservations = [] self.inputSurfacePointsNode = None self.inputSurfacePointsNodeObservations = [] self.numberOfCurveLandmarkPoints = 80 self.printThreeDViewNode = None self.printThreeDWidget = None self.printViewWidth = 1024 self.printViewHeight = 1024 self.printXResolutionDpi = 300 self.printYResolutionDpi = 300 self.printScale = 2.0 #TODO: Workaround for scaling problem, see https://github.com/SlicerFab/SlicerFab/issues/13 self.printTransparentBackground = False # Create triangulated flat disk that will be warped self.surfaceUnitDisk = vtk.vtkDiskSource() self.surfaceUnitDisk.SetOuterRadius(1.0) self.surfaceUnitDisk.SetInnerRadius(0.0) self.surfaceUnitDisk.SetCircumferentialResolution( self.numberOfCurveLandmarkPoints) self.surfaceUnitDisk.SetRadialResolution(60) self.surfaceTriangulator = vtk.vtkDelaunay2D() self.surfaceTriangulator.SetTolerance( 0.01 ) # get rid of the small triangles near the center of the unit disk self.surfaceTriangulator.SetInputConnection( self.surfaceUnitDisk.GetOutputPort()) # Prepare transform object # points on the unit disk (circumference and surface) self.surfaceTransformSourcePoints = vtk.vtkPoints() self.surfaceTransformSourceCurvePoints = vtk.vtkPoints() self.surfaceTransformSourceCurvePoints.SetNumberOfPoints( self.numberOfCurveLandmarkPoints) import math angleIncrement = 2.0 * math.pi / float( self.numberOfCurveLandmarkPoints) for pointIndex in range(self.numberOfCurveLandmarkPoints): angle = float(pointIndex) * angleIncrement self.surfaceTransformSourceCurvePoints.SetPoint( pointIndex, math.cos(angle), math.sin(angle), 0) # points on the warped surface (curve points and surface points) self.surfaceTransformTargetPoints = vtk.vtkPoints() self.surfaceTransform = vtk.vtkThinPlateSplineTransform() self.surfaceTransform.SetSourceLandmarks( self.surfaceTransformSourcePoints) self.surfaceTransform.SetTargetLandmarks( self.surfaceTransformTargetPoints) # Transform polydata self.surfaceTransformFilter = vtk.vtkTransformPolyDataFilter() self.surfaceTransformFilter.SetTransform(self.surfaceTransform) self.surfaceTransformFilter.SetInputConnection( self.surfaceTriangulator.GetOutputPort()) self.cleanPolyDataFilter = vtk.vtkCleanPolyData() self.cleanPolyDataFilter.SetInputConnection( self.surfaceTransformFilter.GetOutputPort()) # self.surfacePolyDataNormalsThin = vtk.vtkPolyDataNormals() self.surfacePolyDataNormalsThin.SetInputConnection( self.cleanPolyDataFilter.GetOutputPort()) # There are a few triangles in the triangulated unit disk with inconsistent # orientation. Enabling consistency check fixes them. self.surfacePolyDataNormalsThin.ConsistencyOn( ) # TODO: check if needed, probably not self.surfacePolyDataNormalsThin.SplittingOff( ) # this prevents stray normals at the edge TODO: check # Add thickness to warped surface (if needed) # self.surfacePolyDataNormals = vtk.vtkPolyDataNormals() # self.surfacePolyDataNormals.SetInputConnection(self.cleanPolyDataFilter.GetOutputPort()) # self.surfacePolyDataNormals.SplittingOff() # this prevents stray normals at the edge TODO: check self.surfaceOffset = vtk.vtkWarpVector() self.surfaceOffset.SetInputConnection( self.surfacePolyDataNormalsThin.GetOutputPort()) self.surfaceOffset.SetInputArrayToProcess( 0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, vtk.vtkDataSetAttributes.NORMALS) self.surfaceExtrude = vtk.vtkLinearExtrusionFilter() self.surfaceExtrude.SetInputConnection( self.surfaceOffset.GetOutputPort()) self.surfaceExtrude.SetExtrusionTypeToNormalExtrusion() self.surfacePolyDataNormalsThick = vtk.vtkPolyDataNormals() self.surfacePolyDataNormalsThick.SetInputConnection( self.surfaceExtrude.GetOutputPort()) self.surfacePolyDataNormalsThick.AutoOrientNormalsOn()
def interpolate_data(self, points, disp, stretch=None, shear=None, on_deformed=True, kernel_radius=3.0, kernel_sharpness=1.0, remove_null=True, return_deformed=True): """ Interpolate data on the mesh. This can be used for comparing experimental and simulation data together. on_deform selects whether to interpolate the data on the original or on the deformed configuration """ if stretch is None: stretch = np.array([]) if shear is None: shear = np.array([]) # We need nPts*3 data for vtk if points.shape[1] == 2: points_ = np.zeros([points.shape[0], 3]) points_[:,0:2] = points # Deform data if needed if on_deformed: points_[:,0:2] = points + disp # Generate vtk points structure with all data vtkpoints = vtk.vtkPoints() vtkpoints.SetData(numpy_support.numpy_to_vtk(points_)) vtkdisp = vtk.vtkDoubleArray() vtkdisp.SetName("disp") vtkdisp.SetNumberOfComponents(disp.shape[1]) vtkdisp.SetNumberOfTuples(disp.shape[0]) vtkdisp.SetVoidArray(disp.flatten(), disp.size, 1) vtkstretch = vtk.vtkDoubleArray() vtkstretch.SetName("stretch") vtkstretch.SetNumberOfComponents(1) vtkstretch.SetNumberOfTuples(stretch.size) vtkstretch.SetVoidArray(stretch, stretch.size, 1) shear = shear.reshape([-1, 4]) vtkshear = vtk.vtkDoubleArray() vtkshear.SetName("shear") vtkshear.SetNumberOfComponents(shear.shape[1]) vtkshear.SetNumberOfTuples(shear.shape[0]) vtkshear.SetVoidArray(shear, shear.size, 1) vtkpointset = vtk.vtkPolyData() vtkpointset.SetPoints(vtkpoints) vtkpointset.GetPointData().AddArray(vtkdisp) vtkpointset.GetPointData().AddArray(vtkstretch) vtkpointset.GetPointData().AddArray(vtkshear) # Build the locator for the interpolation locator = vtk.vtkStaticPointLocator() locator.SetDataSet(vtkpointset) locator.BuildLocator() # Build the Gaussian kernel kernel = vtk.vtkGaussianKernel() kernel.SetKernelFootprint(0) kernel.SetRadius(kernel_radius) kernel.SetSharpness(kernel_sharpness) # If the interpolation is performed on the deformed configuration, warp the data if on_deformed: disp_ = np.zeros(self.x_nodes.shape) disp_[:,0:2] = self.disp warpData = vtk.vtkDoubleArray() warpData.SetName("warp") warpData.SetNumberOfComponents(3) warpData.SetNumberOfTuples(self.x_nodes.shape[0]) warpData.SetVoidArray(disp_, self.x_nodes.shape[0], 1) self.vtkmesh.GetPointData().AddArray(warpData) self.vtkmesh.GetPointData().SetActiveVectors(warpData.GetName()) warpVector = vtk.vtkWarpVector() warpVector.SetInputData(self.vtkmesh) warpVector.Update() self.vtkmesh = warpVector.GetOutput() coarseInterpolator = vtk.vtkPointInterpolator() coarseInterpolator.SetSourceData(vtkpointset) coarseInterpolator.SetInputData(self.vtkmesh) coarseInterpolator.SetKernel(kernel) coarseInterpolator.SetLocator(locator) coarseInterpolator.PassPointArraysOff() coarseInterpolator.SetNullPointsStrategyToMaskPoints() # Get points with an invalid interpolation coarseInterpolator.Update() vtkmesh = coarseInterpolator.GetOutput() if return_deformed: self.x_nodes[:,0:2] += self.disp self.disp = numpy_support.vtk_to_numpy(vtkmesh.GetPointData().GetArray("disp")) self.stretch = numpy_support.vtk_to_numpy(vtkmesh.GetPointData().GetArray("stretch")) self.shear = numpy_support.vtk_to_numpy(vtkmesh.GetPointData().GetArray("shear")) if remove_null: not_null = (numpy_support.vtk_to_numpy(vtkmesh.GetPointData().GetArray( coarseInterpolator.GetValidPointsMaskArrayName()))).astype(bool) idlist_old = np.arange(self.x_nodes.shape[0])[not_null] self.x_nodes = self.x_nodes[not_null] self.disp = self.disp[not_null] self.stretch = self.stretch[not_null] self.shear = self.shear[not_null] idlist_new = np.arange(self.x_nodes.shape[0]) c1 = np.in1d(self.connec[:, 0], idlist_old) c2 = np.in1d(self.connec[:, 1], idlist_old) c3 = np.in1d(self.connec[:, 2], idlist_old) self.connec = self.connec[np.logical_and(np.logical_and(c1,c2),c3)] for i in idlist_new: self.connec[self.connec == idlist_old[i]] = i points = vtk.vtkPoints() points.SetData(numpy_support.numpy_to_vtk(self.x_nodes)) vtkmesh.SetPoints(points) cells = vtk.vtkCellArray() cells.SetCells(self.connec.shape[0], numpy_support.numpy_to_vtkIdTypeArray(self.connec)) vtkmesh.SetPolys(cells) self.shear = self.shear.reshape([-1, 2, 2])
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # create reader and warp data with vectors reader = vtk.vtkDataSetReader() reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/blow.vtk") reader.SetScalarsName("thickness9") reader.SetVectorsName("displacement9") castToUnstructuredGrid = vtk.vtkCastToConcrete() castToUnstructuredGrid.SetInputConnection(reader.GetOutputPort()) castToUnstructuredGrid.Update() warp = vtk.vtkWarpVector() warp.SetInputData(castToUnstructuredGrid.GetUnstructuredGridOutput()) # extract mold from mesh using connectivity connect = vtk.vtkConnectivityFilter() connect.SetInputConnection(warp.GetOutputPort()) connect.SetExtractionModeToSpecifiedRegions() connect.AddSpecifiedRegion(0) connect.AddSpecifiedRegion(1) moldMapper = vtk.vtkDataSetMapper() moldMapper.SetInputConnection(reader.GetOutputPort()) moldMapper.ScalarVisibilityOff() moldActor = vtk.vtkActor() moldActor.SetMapper(moldMapper) moldActor.GetProperty().SetColor(.2,.2,.2) moldActor.GetProperty().SetRepresentationToWireframe() # extract parison from mesh using connectivity connect2 = vtk.vtkConnectivityFilter() connect2.SetInputConnection(warp.GetOutputPort())
def execute(self, obj, event): if self.timer_count == 10: self.timer_count = 0 warpVector = vtk.vtkWarpVector() warpVector.SetInputData(pd) warpVector.SetScaleFactor(0.1 * (self.timer_count + 1)) warpVector.Update() poly = warpVector.GetPolyDataOutput() getScalars = vtk.vtkExtractVectorComponents() getScalars.SetInputData(poly) getScalars.Update() vectorNorm = vtk.vtkVectorNorm() vectorNorm.SetInputData(poly) vectorNorm.Update() scalars = [] scalars.append( getScalars.GetVzComponent()) scalars.append( vectorNorm.GetOutput()) scalars.append( getScalars.GetVxComponent()) scalars.append( getScalars.GetVyComponent()) names = ("Z", "Mag", "X", "Y") for k, a in enumerate(self.actors): calc = vtk.vtkArrayCalculator() scalars[k].GetPointData().GetScalars().SetName(names[k]) calc.SetInputData(scalars[k]) calc.AddScalarArrayName(names[k]) calc.SetResultArrayName(names[k]) calc.SetFunction( "%s * 0.1 * %f" % (names[k], self.timer_count + 1)) calc.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(calc.GetOutput()) mapper.SetScalarRange(calc.GetOutput().GetScalarRange()) mapper.SetScalarModeToUsePointData() mapper.SetColorModeToMapScalars() mapper.Update() a.SetMapper(mapper) cb.scalar_bars[k].SetLookupTable(mapper.GetLookupTable()) iren = obj iren.GetRenderWindow().Render() time.sleep(0.3) if self.key == "Up": try: os.mkdir(self.directory) except: pass w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(obj.GetRenderWindow()) w2i.Update() png = vtk.vtkPNGWriter() png.SetInputConnection(w2i.GetOutputPort()) png.SetFileName(self.directory + os.sep + "frame{:d}.png".format(self.timer_count)) png.Update() png.Write() self.timer_count += 1
def animate(self, pd, ind): """ Helper function called by **deformableRegistration** if **animate** is *True*. Spawns a window with an interactive 3-D rendering of the current analyzed object in its reference state. The displacements calculated from the deformable image registration can be applied to this object to animate the deformation by pressing the RIGHT-ARROW. Pressing the UP-ARROW will animate and also save the frames to disk. Parameters ---------- pd : vtkPolyData The current analyzed object's reference geometry. ind : int The index of the current polydata in **rsurfs**. Necessary for naming directory created if animation frames are saved. """ pd.GetPointData().SetActiveVectors("Displacement") class vtkTimerCallback(object): def __init__(self): self.timer_count = 0 def execute(self, obj, event): if self.timer_count == 10: self.timer_count = 0 warpVector = vtk.vtkWarpVector() warpVector.SetInputData(pd) warpVector.SetScaleFactor(0.1 * (self.timer_count + 1)) warpVector.Update() poly = warpVector.GetPolyDataOutput() getScalars = vtk.vtkExtractVectorComponents() getScalars.SetInputData(poly) getScalars.Update() vectorNorm = vtk.vtkVectorNorm() vectorNorm.SetInputData(poly) vectorNorm.Update() scalars = [] scalars.append( getScalars.GetVzComponent()) scalars.append( vectorNorm.GetOutput()) scalars.append( getScalars.GetVxComponent()) scalars.append( getScalars.GetVyComponent()) names = ("Z", "Mag", "X", "Y") for k, a in enumerate(self.actors): calc = vtk.vtkArrayCalculator() scalars[k].GetPointData().GetScalars().SetName(names[k]) calc.SetInputData(scalars[k]) calc.AddScalarArrayName(names[k]) calc.SetResultArrayName(names[k]) calc.SetFunction( "%s * 0.1 * %f" % (names[k], self.timer_count + 1)) calc.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(calc.GetOutput()) mapper.SetScalarRange(calc.GetOutput().GetScalarRange()) mapper.SetScalarModeToUsePointData() mapper.SetColorModeToMapScalars() mapper.Update() a.SetMapper(mapper) cb.scalar_bars[k].SetLookupTable(mapper.GetLookupTable()) iren = obj iren.GetRenderWindow().Render() time.sleep(0.3) if self.key == "Up": try: os.mkdir(self.directory) except: pass w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(obj.GetRenderWindow()) w2i.Update() png = vtk.vtkPNGWriter() png.SetInputConnection(w2i.GetOutputPort()) png.SetFileName(self.directory + os.sep + "frame{:d}.png".format(self.timer_count)) png.Update() png.Write() self.timer_count += 1 def Keypress(self, obj, event): self.key = obj.GetKeySym() if self.key == "Right" or self.key == "Up": for i in range(10): obj.CreateOneShotTimer(1) renwin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renwin) iren.Initialize() cb = vtkTimerCallback() xmins = (0, 0.5, 0, 0.5) xmaxs = (0.5, 1, 0.5, 1) ymins = (0, 0, 0.5, 0.5) ymaxs = (0.5, 0.5, 1, 1) titles = ('Z Displacement', 'Magnitude', 'X Displacement', 'Y Displacement') cb.actors = [] cb.scalar_bars = [] cb.directory = str(os.path.normpath( self._def_dir + os.sep + "animation{:0d}".format(ind + 1))) warpVector = vtk.vtkWarpVector() warpVector.SetInputData(pd) warpVector.Update() poly = warpVector.GetPolyDataOutput() getScalars = vtk.vtkExtractVectorComponents() getScalars.SetInputData(poly) getScalars.Update() vectorNorm = vtk.vtkVectorNorm() vectorNorm.SetInputData(poly) vectorNorm.Update() scalars = [] scalars.append( getScalars.GetVzComponent()) scalars.append( vectorNorm.GetOutput()) scalars.append( getScalars.GetVxComponent()) scalars.append( getScalars.GetVyComponent()) bounds = np.zeros(6, np.float32) pd.GetBounds(bounds) length = np.min(bounds[1::2] - bounds[0:-1:2]) * 0.2 bounds[1] = bounds[0] + length bounds[3] = bounds[2] + length bounds[5] = bounds[4] + length for j in range(4): mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(scalars[j]) mapper.SetScalarRange(scalars[j].GetScalarRange()) mapper.SetScalarModeToUsePointData() mapper.SetColorModeToMapScalars() scalar_bar = vtk.vtkScalarBarActor() scalar_bar.SetLookupTable(mapper.GetLookupTable()) scalar_bar.SetTitle(titles[j]) scalar_bar.SetLabelFormat("%3.3f") cb.scalar_bars.append(scalar_bar) actor = vtk.vtkActor() actor.SetMapper(mapper) cb.actors.append(actor) renderer = vtk.vtkRenderer() renderer.SetBackground(0., 0., 0.) renwin.AddRenderer(renderer) if j == 0: camera = renderer.GetActiveCamera() else: renderer.SetActiveCamera(camera) triad = vtk.vtkCubeAxesActor() triad.SetCamera(camera) triad.SetFlyModeToStaticTriad() triad.SetBounds(bounds) triad.GetXAxesLinesProperty().SetColor(1.0, 0.0, 0.0) triad.GetYAxesLinesProperty().SetColor(0.0, 1.0, 0.0) triad.GetZAxesLinesProperty().SetColor(0.0, 0.0, 1.0) triad.GetXAxesLinesProperty().SetLineWidth(3.0) triad.GetYAxesLinesProperty().SetLineWidth(3.0) triad.GetZAxesLinesProperty().SetLineWidth(3.0) triad.XAxisLabelVisibilityOff() triad.YAxisLabelVisibilityOff() triad.ZAxisLabelVisibilityOff() triad.XAxisTickVisibilityOff() triad.YAxisTickVisibilityOff() triad.ZAxisTickVisibilityOff() triad.XAxisMinorTickVisibilityOff() triad.YAxisMinorTickVisibilityOff() triad.ZAxisMinorTickVisibilityOff() renderer.SetViewport(xmins[j], ymins[j], xmaxs[j], ymaxs[j]) renderer.AddActor(actor) renderer.AddActor2D(scalar_bar) renderer.AddActor(triad) renderer.ResetCamera() renwin.Render() iren.AddObserver('TimerEvent', cb.execute) iren.AddObserver('KeyPressEvent', cb.Keypress) iren.Start()
def plot(self, struct): # creates self. data1, legend, filename, fieldname, dim, has_field, tracker, revision if not self.call_config(struct): return self.update_field_type('vector', True) self.update_legend_data() # creates self.src if not self.call_src(): return self.ini_data(self.src) # si es cell data, lo transforma a point data, porque vtkWarpScalar parece ser que no soporta cell data. if self.data1.get('fielddomain') == 'cell': self.cdtpd = vtk.vtkCellDataToPointData() self.cdtpd.SetInputConnection(self.src.GetOutputPort()) self.warpT = vtk.vtkWarpVector() self.warpT.SetInputConnection(self.cdtpd.GetOutputPort()) else: self.warpT = vtk.vtkWarpVector() self.warpT.SetInputConnection(self.src.GetOutputPort()) self.warpT.GetOutput().GetPointData().SetVectors(self.vectors) # print self.warpT #Creacion de una tabla de color lut = vtk.vtkLookupTable() lut.SetRampToLinear() lut.SetScaleToLinear() # When using vector magnitude for coloring lut.SetVectorModeToMagnitude() if self.vectors is not None: lutrange = self.vectors.GetRange(-1) lut.SetTableRange(lutrange) lut.Build() self.wireM2 = vtk.vtkDataSetMapper() self.wireM2.SetInputConnection(self.warpT.GetOutputPort()) #Definicion del campo y el rango para colorear if self.vectors is not None: self.wireM2.SelectColorArray(self.vectors.GetName()) self.wireM2.SetScalarRange(lutrange) if self.data1.get('fielddomain') == 'cell': self.wireM2.SetScalarModeToUseCellFieldData() else: self.wireM2.SetScalarModeToUsePointFieldData() self.wireM2.ScalarVisibilityOn() self.wireM2.SetLookupTable(lut) self.wireM2.Update() # print self.wireM2 self.wireA2 = vtk.vtkActor() self.wireA2.SetMapper(self.wireM2) self.wireA2.GetProperty().SetRepresentationToSurface() self.wireA2.GetProperty().SetColor(Plot.edges_color) self.add_sw_2(self.wireA2) self.add_opacity_2([self.wireA2]) # Opacity: 100%/75%/50%/25%/0% #Para pintar el wireframe original(sin desplazamiento) # self.wireM = vtk.vtkDataSetMapper() # self.wireM.SetInputConnection(self.src.GetOutputPort()) # self.wireM.ScalarVisibilityOff() # self.wireA3 = vtk.vtkActor() # self.wireA3.SetMapper(self.wireM) # self.wireA3.GetProperty().SetRepresentationToWireframe() # self.wireA3.GetProperty().SetColor(Plot.mesh_color) # self.wireA3.GetProperty().SetEdgeColor(Plot.unselected_color) # self.rens[0].AddActor(self.wireA3) self.rens[0].AddActor(self.wireA2) self.copy_params(struct) self.warpT.Update() # self.add_outline_2(self.src) self.add_outline_2(self.warpT) # reverse rainbow [red->blue] -> [blue->red] if self.vectors is not None: self.scalarrange.local_set(lutrange) self.add_scalarbar_2(lut) self.done = True
# Make sure all algorithms use the composite data pipeline cdp = vtk.vtkCompositeDataPipeline() reader.SetDefaultExecutivePrototype(cdp) reader.SetCaseFileName("" + str(VTK_DATA_ROOT) + "/Data/EnSight/RectGrid_ascii.case") reader.Update() toRectilinearGrid = vtk.vtkCastToConcrete() # toRectilinearGrid SetInputConnection [reader GetOutputPort] toRectilinearGrid.SetInputData(reader.GetOutput().GetBlock(0)) toRectilinearGrid.Update() plane = vtk.vtkRectilinearGridGeometryFilter() plane.SetInputData(toRectilinearGrid.GetRectilinearGridOutput()) plane.SetExtent(0, 100, 0, 100, 15, 15) tri = vtk.vtkTriangleFilter() tri.SetInputConnection(plane.GetOutputPort()) warper = vtk.vtkWarpVector() warper.SetInputConnection(tri.GetOutputPort()) warper.SetScaleFactor(0.05) planeMapper = vtk.vtkDataSetMapper() planeMapper.SetInputConnection(warper.GetOutputPort()) planeMapper.SetScalarRange(0.197813, 0.710419) planeActor = vtk.vtkActor() planeActor.SetMapper(planeMapper) cutPlane = vtk.vtkPlane() # eval cutPlane SetOrigin [[reader GetOutput] GetCenter] cutPlane.SetOrigin(reader.GetOutput().GetBlock(0).GetCenter()) cutPlane.SetNormal(1, 0, 0) planeCut = vtk.vtkCutter() planeCut.SetInputData(toRectilinearGrid.GetRectilinearGridOutput()) planeCut.SetCutFunction(cutPlane) cutMapper = vtk.vtkDataSetMapper()
output = plane.GetOutput() # Manually construct scalars NPts = output.GetNumberOfPoints() vectors = vtk.vtkDoubleArray() vectors.SetNumberOfComponents(3) vectors.SetNumberOfTuples(NPts) for i in range(0, NPts): vectors.SetTuple3(i, math.Random(0, 10), math.Random(0, 10), math.Random(0, 10)) output.GetPointData().SetVectors(vectors) # Output some statistics print("Number of points: {0}".format(NPts)) # Time the warping warpF = vtk.vtkWarpVector() warpF.SetInputData(output) warpF.SetScaleFactor(2.5) # For timing the various tests timer = vtk.vtkTimerLog() timer.StartTimer() warpF.Update() timer.StopTimer() time = timer.GetElapsedTime() print("Warp via vector: {0}".format(time))
def main(): fileName1, fileName2 = get_program_parameters() colors = vtk.vtkNamedColors() # Set the background color. colors.SetColor('BkgColor', [65, 99, 149, 255]) # Read a vtk file # pl3d = vtk.vtkMultiBlockPLOT3DReader() pl3d.SetXYZFileName(fileName1) pl3d.SetQFileName(fileName2) pl3d.SetScalarFunctionNumber(100) # Density pl3d.SetVectorFunctionNumber(202) # Momentum pl3d.Update() pl3dOutput = pl3d.GetOutput().GetBlock(0) # What do we know about the data? # Get the extent of the data: imin,imax, jmin,jmax, kmin,kmax extent = pl3dOutput.GetExtent() scalarRange = pl3dOutput.GetScalarRange() # Planes are specified using a imin,imax, jmin,jmax, kmin,kmax coordinate # specification. Min and max i,j,k values are clamped to 0 and maximum value. # See the variable named extent for the values. # plane = vtk.vtkStructuredGridGeometryFilter() plane.SetInputData(pl3dOutput) plane.SetExtent(10, 10, 1, extent[3], 1, extent[5]) plane2 = vtk.vtkStructuredGridGeometryFilter() plane2.SetInputData(pl3dOutput) plane2.SetExtent(30, 30, 1, extent[3], 1, extent[5]) plane3 = vtk.vtkStructuredGridGeometryFilter() plane3.SetInputData(pl3dOutput) plane3.SetExtent(45, 45, 1, extent[3], 1, extent[5]) # We use an append filter because that way we can do the warping, etc. just # using a single pipeline and actor. # appendF = vtk.vtkAppendPolyData() appendF.AddInputConnection(plane.GetOutputPort()) appendF.AddInputConnection(plane2.GetOutputPort()) appendF.AddInputConnection(plane3.GetOutputPort()) # Warp warp = vtk.vtkWarpVector() warp.SetInputConnection(appendF.GetOutputPort()) warp.SetScaleFactor(0.005) warp.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputData(warp.GetPolyDataOutput()) normals.SetFeatureAngle(45) planeMapper = vtk.vtkPolyDataMapper() planeMapper.SetInputConnection(normals.GetOutputPort()) planeMapper.SetScalarRange(scalarRange) planeActor = vtk.vtkActor() planeActor.SetMapper(planeMapper) # The outline provides context for the data and the planes. outline = vtk.vtkStructuredGridOutlineFilter() outline.SetInputData(pl3dOutput) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.GetProperty().SetColor(colors.GetColor3d('Black')) # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren.AddActor(planeActor) ren.AddActor(outlineActor) ren.SetBackground(colors.GetColor3d('BkgColor')) renWin.SetSize(512, 512) renWin.SetWindowName('VelocityProfile') iren.Initialize() renWin.Render() ren.GetActiveCamera().SetPosition(19.8562, -31.8912, 47.0755) ren.GetActiveCamera().SetFocalPoint(8.255, 0.147815, 29.7631) ren.GetActiveCamera().SetViewUp(-0.0333325, 0.465756, 0.884285) ren.GetActiveCamera().SetClippingRange(17.3078, 64.6375) renWin.Render() iren.Start()
moment_reader.Update() # --------------------------------------------------- # GET THE INITIAL SCALES FOR WARP VECTORS # --------------------------------------------------- axial_scale = get_scale(axial_reader) shear_scale = get_scale(shear_reader) moment_scale = get_scale(moment_reader) # --------------------------------------------------- # WARP VECTORS # --------------------------------------------------- # DEFORMED warp_deformed = vtk.vtkWarpVector() warp_deformed.SetInput(deformed_reader.GetOutput()) warp_deformed.SetScaleFactor(50) warp_deformed.Update() warp_deformed_mapper = vtk.vtkDataSetMapper() warp_deformed_mapper.SetInput(warp_deformed.GetOutput()) warp_deformed_actor = vtk.vtkActor() warp_deformed_actor.SetMapper(warp_deformed_mapper) warp_deformed_actor.SetVisibility(0) # AXIAL warp_axial = vtk.vtkWarpVector() warp_axial.SetInput(axial_reader.GetOutput()) warp_axial.SetScaleFactor(axial_scale) warp_axial.Update() warp_axial_mapper = vtk.vtkDataSetMapper() warp_axial_mapper.SetInput(warp_axial.GetOutput())
def main(argv): if os.name == 'nt': VTK_DATA_ROOT = "c:/VTK82/build_Release/ExternalData/Testing/" else: VTK_DATA_ROOT = "/home/jmh/" if 1: v16 = vtk.vtkMetaImageReader() v16.SetFileName("/home/jmh/github/fis/data/Abdomen/CT-Abdomen.mhd") v16.Update() elif 0: fname = os.path.join(VTK_DATA_ROOT, "Data/headsq/quarter") v16 = vtk.vtkVolume16Reader() v16.SetDataDimensions(64, 64) v16.SetDataByteOrderToLittleEndian() v16.SetImageRange(1, 93) v16.SetDataSpacing(3.2, 3.2, 1.5) v16.SetFilePrefix(fname) v16.ReleaseDataFlagOn() v16.SetDataMask(0x7fff) v16.Update() else: v16 = vtk.vtkMetaImageReader() v16.SetFileName("c:/github/fis/data/Abdomen/CT-Abdomen.mhd") v16.Update() rng = v16.GetOutput().GetScalarRange() shifter = vtk.vtkImageShiftScale() shifter.SetShift(-1.0*rng[0]) shifter.SetScale(255.0/(rng[1]-rng[0])) shifter.SetOutputScalarTypeToUnsignedChar() shifter.SetInputConnection(v16.GetOutputPort()) shifter.ReleaseDataFlagOff() shifter.Update() ImageViewer = vtk.vtkImageViewer2() ImageViewer.SetInputData(shifter.GetOutput()) ImageViewer.SetColorLevel(127) ImageViewer.SetColorWindow(255) iren = vtk.vtkRenderWindowInteractor() ImageViewer.SetupInteractor(iren) ImageViewer.Render() ImageViewer.GetRenderer().ResetCamera() ImageViewer.Render() dims = v16.GetOutput().GetDimensions() global minArea spacing = v16.GetOutput().GetSpacing() minArea = ( spacing[0] * spacing[1] ) / 0.1 # Slider screen representation SliderRepres = vtk.vtkSliderRepresentation2D() _min = ImageViewer.GetSliceMin() _max = ImageViewer.GetSliceMax() SliderRepres.SetMinimumValue(_min) SliderRepres.SetMaximumValue(_max) SliderRepres.SetValue(int((_min + _max) / 2)) SliderRepres.SetTitleText("Slice") SliderRepres.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() SliderRepres.GetPoint1Coordinate().SetValue(0.3, 0.05) SliderRepres.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() SliderRepres.GetPoint2Coordinate().SetValue(0.7, 0.05) SliderRepres.SetSliderLength(0.02) SliderRepres.SetSliderWidth(0.03) SliderRepres.SetEndCapLength(0.01) SliderRepres.SetEndCapWidth(0.03) SliderRepres.SetTubeWidth(0.005) SliderRepres.SetLabelFormat("%3.0lf") SliderRepres.SetTitleHeight(0.02) SliderRepres.SetLabelHeight(0.02) # Slider widget SliderWidget = vtk.vtkSliderWidget() SliderWidget.SetInteractor(iren) SliderWidget.SetRepresentation(SliderRepres) SliderWidget.KeyPressActivationOff() SliderWidget.SetAnimationModeToAnimate() SliderWidget.SetEnabled(True) SliderCb = vtkSliderCallback() SliderCb.SetImageViewer(ImageViewer) SliderWidget.AddObserver(vtk.vtkCommand.InteractionEvent, SliderCb.Execute) ImageViewer.SetSlice(int(SliderRepres.GetValue())) # Contour representation - responsible for placement of points, calculation of lines and contour manipulation global rep rep = vtk.vtkOrientedGlyphContourRepresentation() # vtkContourRepresentation has GetActiveNodeWorldPostion/Orientation rep.GetProperty().SetOpacity(0) #1 prop = rep.GetLinesProperty() from vtkUtils import renderLinesAsTubes from vtk.util.colors import red, green, pink, yellow renderLinesAsTubes(prop) prop.SetColor(yellow) propActive = rep.GetActiveProperty() #propActive.SetOpacity(0) # 2 renderLinesAsTubes(propActive) propActive.SetColor(green) shapeActive = rep.GetActiveCursorShape() warp = vtk.vtkWarpVector() warp.SetInputData(shapeActive) warp.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, vtk.vtkDataSetAttributes.NORMALS) scale = 0.4 warp.SetScaleFactor(scale) warp.Update() rep.SetActiveCursorShape(warp.GetOutput()) # Use vtkContourTriangulator to fill contours # Point placer imageActorPointPlacer = vtk.vtkImageActorPointPlacer() imageActorPointPlacer.SetImageActor(ImageViewer.GetImageActor()) rep.SetPointPlacer(imageActorPointPlacer) global ContourWidget # Contour widget - has a vtkWidgetEventTranslator which translate events to vtkContourWidget events ContourWidget = vtk.vtkContourWidget() ContourWidget.SetRepresentation(rep) ContourWidget.SetInteractor(iren) ContourWidget.SetEnabled(True) ContourWidget.ProcessEventsOn() ContourWidget.ContinuousDrawOn() # Can be Initialize() using polydata # Override methods that returns display position to get an overlay # (display postions) instead of computing it from world position and # the method BuildLines to interpolate using display positions # instead of world positions # Thinning of contour control points # AddFinalPointAction ContourWidget.AddObserver(vtk.vtkCommand.EndInteractionEvent, callback) if 0: # TODO: Make interior transparent contour = ContourWidget.GetContourRepresentation().GetContourRepresentationAsPolyData() tc = vtk.vtkContourTriangulator() tc.SetInputData(contour) tc.Update() # Extrusion towards camera extruder = vtk.vtkLinearExtrusionFilter() extruder.CappingOn() extruder.SetScalaFactor(1.0) extruder.SetInputData(tc.GetOutput()) extruder.SetVector(0,0,1.0) extruder.SetExtrusionTypeToNormalExtrusion() polyMapper = vtk.vtkPolyMapper() polyMapper.SetInputConnection(extruder.GetOutputPort()) polyMapper.ScalarVisibilityOn() polyMapper.Update() polyActor = vtk.vtkActor() polyActor.SetMapper(polyMapper) prop = polyActor.GetProperty() prop.SetColor(0,1,0) #prop.SetRepresentationToWireframe() renderer.AddActor(polyActor) renderer.GetRenderWindow().Render() iren.Start()
def main(): points = vtk.vtkPoints() points.InsertNextPoint(0.0, 0.0, 0.0) points.InsertNextPoint(1.0, 0.0, 0.0) points.InsertNextPoint(2.0, 0.0, 0.0) points.InsertNextPoint(3.0, 0.0, 0.0) points.InsertNextPoint(4.0, 0.0, 0.0) lines = vtk.vtkCellArray() line = vtk.vtkLine() line.GetPointIds().SetId(0, 0) line.GetPointIds().SetId(1, 1) lines.InsertNextCell(line) line.GetPointIds().SetId(0, 1) line.GetPointIds().SetId(1, 2) lines.InsertNextCell(line) line.GetPointIds().SetId(0, 2) line.GetPointIds().SetId(1, 3) lines.InsertNextCell(line) line.GetPointIds().SetId(0, 3) line.GetPointIds().SetId(1, 4) lines.InsertNextCell(line) warpData = vtk.vtkDoubleArray() warpData.SetNumberOfComponents(3) warpData.SetName("warpData") warp = [0.0, 0.0, 0.0] warp[1] = 0.0 warpData.InsertNextTuple(warp) warp[1] = 0.1 warpData.InsertNextTuple(warp) warp[1] = 0.3 warpData.InsertNextTuple(warp) warp[1] = 0.0 warpData.InsertNextTuple(warp) warp[1] = 0.1 warpData.InsertNextTuple(warp) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetLines(lines) polydata.GetPointData().AddArray(warpData) polydata.GetPointData().SetActiveVectors(warpData.GetName()) # WarpVector will use the array marked as active vector in polydata # it has to be a 3 component array # with the same number of tuples as points in polydata warpVector = vtk.vtkWarpVector() if VTK_MAJOR_VERSION <= 5: warpVector.SetInput(polydata) else: warpVector.SetInputData(polydata) warpVector.Update() mapper = vtk.vtkPolyDataMapper() if VTK_MAJOR_VERSION <= 5: mapper.SetInput(warpVector.GetPolyDataOutput()) else: mapper.SetInputData(warpVector.GetPolyDataOutput()) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(.3, .6, .3) renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindow.Render() renderWindowInteractor.Start() return
def main(): colors = vtk.vtkNamedColors() points = vtk.vtkPoints() points.InsertNextPoint(0.0, 0.0, 0.0) points.InsertNextPoint(1.0, 0.0, 0.0) points.InsertNextPoint(2.0, 0.0, 0.0) points.InsertNextPoint(3.0, 0.0, 0.0) points.InsertNextPoint(4.0, 0.0, 0.0) lines = vtk.vtkCellArray() line = vtk.vtkLine() line.GetPointIds().SetId(0, 0) line.GetPointIds().SetId(1, 1) lines.InsertNextCell(line) line.GetPointIds().SetId(0, 1) line.GetPointIds().SetId(1, 2) lines.InsertNextCell(line) line.GetPointIds().SetId(0, 2) line.GetPointIds().SetId(1, 3) lines.InsertNextCell(line) line.GetPointIds().SetId(0, 3) line.GetPointIds().SetId(1, 4) lines.InsertNextCell(line) warpData = vtk.vtkDoubleArray() warpData.SetNumberOfComponents(3) warpData.SetName("warpData") warp = [0.0, 0.0, 0.0] warp[1] = 0.0 warpData.InsertNextTuple(warp) warp[1] = 0.1 warpData.InsertNextTuple(warp) warp[1] = 0.3 warpData.InsertNextTuple(warp) warp[1] = 0.0 warpData.InsertNextTuple(warp) warp[1] = 0.1 warpData.InsertNextTuple(warp) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetLines(lines) polydata.GetPointData().AddArray(warpData) polydata.GetPointData().SetActiveVectors(warpData.GetName()) # WarpVector will use the array marked as active vector in polydata # it has to be a 3 component array # with the same number of tuples as points in polydata warpVector = vtk.vtkWarpVector() warpVector.SetInputData(polydata) warpVector.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(warpVector.GetPolyDataOutput()) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d('cobalt_green')) renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindow.SetWindowName('WarpVector') renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindow.Render() renderWindowInteractor.Start()
def main(argv): scale = 1.0 if len(argv) > 1: reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(argv[1]) reader.Update() inputPolyData = reader.GetOutput() if len(argv) > 2: scale = float(argv[2]) else: sphereSource = vtk.vtkSphereSource() sphereSource.SetPhiResolution(15) sphereSource.SetThetaResolution(15) sphereSource.Update() inputPolyData = sphereSource.GetOutput() clean = vtk.vtkCleanPolyData() clean.SetInputData(inputPolyData) # Generate normals normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(clean.GetOutputPort()) normals.SplittingOff() # Warp using the normals warp = vtk.vtkWarpVector() warp.SetInputConnection(normals.GetOutputPort()) warp.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, vtk.vtkDataSetAttributes.NORMALS) warp.SetScaleFactor(scale) warp.Modified() # Visualize the original and warped models mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(warp.GetOutputPort()) mapper.ScalarVisibilityOff() warpedActor = vtk.vtkActor() warpedActor.SetMapper(mapper) originalMapper = vtk.vtkPolyDataMapper() originalMapper.SetInputConnection(normals.GetOutputPort()) originalMapper.ScalarVisibilityOff() originalActor = vtk.vtkActor() originalActor.SetMapper(originalMapper) originalActor.GetProperty().SetInterpolationToFlat() renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(640, 480) # Create a camera for all renderers camera = vtk.vtkCamera() # Define viewport ranges # (xmin, ymin, xmax, ymax) leftViewport = (0.0, 0.0, 0.5, 1.0) rightViewport = (0.5, 0.0, 1.0, 1.0) # Setup both renderers leftRenderer = vtk.vtkRenderer() leftRenderer.SetViewport(leftViewport) leftRenderer.SetBackground(.6, .5, .4) leftRenderer.SetActiveCamera(camera) rightRenderer = vtk.vtkRenderer() rightRenderer.SetViewport(rightViewport) rightRenderer.SetBackground(.4, .5, .6) rightRenderer.SetActiveCamera(camera) leftRenderer.AddActor(originalActor) rightRenderer.AddActor(warpedActor) rightRenderer.ResetCamera() renderWindow.AddRenderer(rightRenderer) renderWindow.AddRenderer(leftRenderer) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderWindow.Render() interactor.Start()
def execute(self, obj, event): if self.timer_count == 10: self.timer_count = 0 warpVector = vtk.vtkWarpVector() warpVector.SetInputData(pd) warpVector.SetScaleFactor(0.1 * (self.timer_count + 1)) warpVector.Update() poly = warpVector.GetPolyDataOutput() getScalars = vtk.vtkExtractVectorComponents() getScalars.SetInputData(poly) getScalars.Update() vectorNorm = vtk.vtkVectorNorm() vectorNorm.SetInputData(poly) vectorNorm.Update() scalars = [] scalars.append(getScalars.GetVzComponent()) scalars.append(vectorNorm.GetOutput()) scalars.append(getScalars.GetVxComponent()) scalars.append(getScalars.GetVyComponent()) names = ("Z", "Mag", "X", "Y") for k, a in enumerate(self.actors): calc = vtk.vtkArrayCalculator() scalars[k].GetPointData().GetScalars().SetName(names[k]) calc.SetInputData(scalars[k]) calc.AddScalarArrayName(names[k]) calc.SetResultArrayName(names[k]) calc.SetFunction("%s * 0.1 * %f" % (names[k], self.timer_count + 1)) calc.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(calc.GetOutput()) mapper.SetScalarRange(calc.GetOutput().GetScalarRange()) mapper.SetScalarModeToUsePointData() mapper.SetColorModeToMapScalars() mapper.Update() a.SetMapper(mapper) cb.scalar_bars[k].SetLookupTable(mapper.GetLookupTable()) iren = obj iren.GetRenderWindow().Render() time.sleep(0.3) if self.key == "Up": try: os.mkdir(self.directory) except: pass w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(obj.GetRenderWindow()) w2i.Update() png = vtk.vtkPNGWriter() png.SetInputConnection(w2i.GetOutputPort()) png.SetFileName(self.directory + os.sep + "frame{:d}.png".format(self.timer_count)) png.Update() png.Write() self.timer_count += 1
def warp_surface(args): print("warp the surface ") reader = vmtkscripts.vmtkSurfaceReader() reader.InputFileName = args.surface reader.Execute() Surface = reader.Surface narrays = Surface.GetPointData().GetNumberOfArrays() has_normals = False for i in range(narrays): if ( Surface.GetPointData().GetArrayName(i) == "Normals"): has_normals = True break if(has_normals): normals = Surface print("already have") else: get_normals = vtk.vtkPolyDataNormals() get_normals.SetInputData(Surface) get_normals.SetFeatureAngle(30.0) # default get_normals.SetSplitting(True) get_normals.Update() get_normals.GetOutput().GetPointData().SetActiveVectors("Normals") normals = get_normals.GetOutput() print("normals generated") random = vtk.vtkRandomAttributeGenerator() random.SetInputData(normals) random.SetDataTypeToDouble() random.GeneratePointScalarsOn () random.SetComponentRange(-0.5, 0.5) random.Update() #n = random.GetOutput().GetPointData().GetNumberOfArrays() #for i in range(n): #print(random.GetOutput().GetPointData().GetArrayName(i)) calc = vtk.vtkArrayCalculator() calc.SetInputConnection(random.GetOutputPort()) calc.AddScalarArrayName("RandomPointScalars", 0) calc.AddVectorArrayName("Normals", 0, 1, 2) calc.SetFunction("Normals * RandomPointScalars") calc.SetResultArrayName("RandomLengthNormalVectors") calc.Update() warp = vtk.vtkWarpVector() warp.SetInputConnection(calc.GetOutputPort()) warp.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "RandomLengthNormalVectors"); warp.SetScaleFactor(args.fuzz_scale) warp.Update() writer = vmtkscripts.vmtkSurfaceWriter() writer.OutputFileName = args.file_out writer.Input = warp.GetOutput() writer.Execute()
gInfo.marker = -1 path = Path(args.molecule) obj_name = f'{path.stem}.obj' pygamer.writeOBJ(obj_name, mesh) # Pyvista mesh = pv.read(obj_name) shell = mesh.decimate(0.97, volume_preservation=True).extract_surface() print(f'Decimation: {len(mesh.points)} -> {len(shell.points)}') # warp each point by the normal vectors for i in range(1, int(args.distance) + 1): print(f'Expanding: {i}') shell = shell.compute_normals() warp = vtk.vtkWarpVector() warp.SetInputData(shell) warp.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, vtk.vtkDataSetAttributes.NORMALS) warp.SetScaleFactor(2) warp.Update() shell = pv.wrap(warp.GetOutput()) expanded_mesh = shell.extract_surface() clus = pyacvd.Clustering(expanded_mesh) clus.subdivide(3) clus.cluster(args.points) shell = clus.create_mesh().extract_surface() uniform = shell
def main(): file_name = get_program_parameters() colors = vtk.vtkNamedColors() # Set the colors. colors.SetColor("PlateColor", [255, 160, 140, 255]) colors.SetColor("BkgColor", [65, 99, 149, 255]) # Read a vtk file # plate = vtk.vtkPolyDataReader() plate.SetFileName(file_name) plate.Update() bounds = [0] * 6 plate.GetOutput().GetBounds(bounds) plate.SetVectorsName("mode2") normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(plate.GetOutputPort()) warp = vtk.vtkWarpVector() warp.SetInputConnection(normals.GetOutputPort()) warp.SetScaleFactor(0.5) color = vtk.vtkVectorDot() color.SetInputConnection(warp.GetOutputPort()) plateMapper = vtk.vtkDataSetMapper() plateMapper.SetInputConnection(warp.GetOutputPort()) plateActor = vtk.vtkActor() plateActor.SetMapper(plateMapper) plateActor.GetProperty().SetColor(colors.GetColor3d("PlateColor")) plateActor.RotateX(-90) # Create the outline. # outline = vtk.vtkOutlineFilter() outline.SetInputConnection(plate.GetOutputPort()) spikeMapper = vtk.vtkPolyDataMapper() spikeMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(spikeMapper) outlineActor.RotateX(-90) outlineActor.GetProperty().SetColor(colors.GetColor3d("White")) # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren.AddActor(plateActor) ren.AddActor(outlineActor) renWin.SetSize(500, 500) # Render the image. renWin.Render() ren.SetBackground(colors.GetColor3d("BkgColor")) # This closely matches the original illustration. ren.GetActiveCamera().SetPosition(-3.7, 13, 15.5) ren.ResetCameraClippingRange() renWin.Render() iren.Start()