def testImage2DScalar(self): planes = ['XY', 'XZ', 'YZ'] expectedNCells = [38, 46, 42] expectedNClippedCells = [104, 104, 106] for plane, nCells, nClippedCells in zip(planes,expectedNCells,expectedNClippedCells): r = vtk.vtkRTAnalyticSource() r.SetXFreq(600); r.SetYFreq(400); r.SetZFreq(900); if plane == 'XY': r.SetWholeExtent(-5, 5, -5, 5, 0, 0) elif plane == 'XZ': r.SetWholeExtent(-5, 5, 0, 0, -5, 5) else: r.SetWholeExtent(0, 0, -5, 5, -5, 5) r.Update() c = vtk.vtkTableBasedClipDataSet() c.SetInputConnection(r.GetOutputPort()) c.SetUseValueAsOffset(0) c.SetValue(150) c.SetInsideOut(1) c.SetGenerateClippedOutput(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), nCells) self.assertEqual(c.GetClippedOutput().GetNumberOfCells(), nClippedCells)
def setup(dirname): rt = vtk.vtkRTAnalyticSource() for xfreq in range(60, 80): rt.SetXFreq(xfreq) rt.Update() write_file(rt.GetOutput(), xfreq)
def testStructured(self): rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-5, 5, -5, 5, -5, 5) rt.Update() i = rt.GetOutput() st = vtk.vtkStructuredGrid() st.SetDimensions(i.GetDimensions()) nps = i.GetNumberOfPoints() ps = vtk.vtkPoints() ps.SetNumberOfPoints(nps) for idx in xrange(nps): ps.SetPoint(idx, i.GetPoint(idx)) st.SetPoints(ps) s = vtk.vtkSphere() s.SetRadius(2) s.SetCenter(0,0,0) c = vtk.vtkTableBasedClipDataSet() c.SetInputData(st) c.SetClipFunction(s) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), 64)
def testStructured(self): rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-5, 5, -5, 5, -5, 5) rt.Update() i = rt.GetOutput() st = vtk.vtkStructuredGrid() st.SetDimensions(i.GetDimensions()) nps = i.GetNumberOfPoints() ps = vtk.vtkPoints() ps.SetNumberOfPoints(nps) for idx in range(nps): ps.SetPoint(idx, i.GetPoint(idx)) st.SetPoints(ps) s = vtk.vtkSphere() s.SetRadius(2) s.SetCenter(0,0,0) c = vtk.vtkTableBasedClipDataSet() c.SetInputData(st) c.SetClipFunction(s) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), 64)
def Wavelet(extent=(-10, 10, -10, 10, -10, 10), center=(0, 0, 0), maximum=255, x_freq=60, y_freq=30, z_freq=40, x_mag=10, y_mag=18, z_mag=5, std=0.5, subsample_rate=1): """Create a wavelet.""" wavelet_source = vtk.vtkRTAnalyticSource() wavelet_source.SetWholeExtent(*extent) wavelet_source.SetCenter(center) wavelet_source.SetMaximum(maximum) wavelet_source.SetXFreq(x_freq) wavelet_source.SetYFreq(y_freq) wavelet_source.SetZFreq(z_freq) wavelet_source.SetXMag(x_mag) wavelet_source.SetYMag(y_mag) wavelet_source.SetZMag(z_mag) wavelet_source.SetStandardDeviation(std) wavelet_source.SetSubsampleRate(subsample_rate) wavelet_source.Update() return pyvista.wrap(wavelet_source.GetOutput())
def testUnstructured(self): rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-5, 5, -5, 5, -5, 5) t = vtk.vtkThreshold() t.SetInputConnection(rt.GetOutputPort()) t.ThresholdByUpper(-10) s = vtk.vtkSphere() s.SetRadius(2) s.SetCenter(0,0,0) c = vtk.vtkTableBasedClipDataSet() c.SetInputConnection(t.GetOutputPort()) c.SetClipFunction(s) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), 64) eg = vtk.vtkEnSightGoldReader() eg.SetCaseFileName(VTK_DATA_ROOT + "/Data/EnSight/elements.case") eg.Update() pl = vtk.vtkPlane() pl.SetOrigin(3.5, 3.5, 0.5) pl.SetNormal(0, 0, 1) c.SetInputConnection(eg.GetOutputPort()) c.SetClipFunction(pl) c.SetInsideOut(1) c.Update() data = c.GetOutputDataObject(0).GetBlock(0) self.assertEqual(data.GetNumberOfCells(), 75) rw = vtk.vtkRenderWindow() ren = vtk.vtkRenderer() rw.AddRenderer(ren) mapper = vtk.vtkDataSetMapper() mapper.SetInputData(data) actor = vtk.vtkActor() actor.SetMapper(mapper) ren.AddActor(actor) ac = ren.GetActiveCamera() ac.SetPosition(-7.9, 9.7, 14.6) ac.SetFocalPoint(3.5, 3.5, 0.5) ac.SetViewUp(0.08, 0.93, -0.34) rw.Render() ren.ResetCameraClippingRange() rtTester = vtk.vtkTesting() for arg in sys.argv[1:]: rtTester.AddArgument(arg) rtTester.AddArgument("-V") rtTester.AddArgument("tableBasedClip.png") rtTester.SetRenderWindow(rw) rw.Render() rtResult = rtTester.RegressionTest(10)
def testSource(self): class MyAlgorithm(vta.VTKAlgorithm): def __init__(self): vta.VTKAlgorithm.__init__(self, nInputPorts=0, outputType='vtkImageData') self.Wavelet = vtk.vtkRTAnalyticSource() def RequestInformation(self, vtkself, request, inInfo, outInfo): self.Wavelet.UpdateInformation() wOutInfo = self.Wavelet.GetOutputInformation(0) vtkSDDP = vtk.vtkStreamingDemandDrivenPipeline outInfo.GetInformationObject(0).Set(vtkSDDP.WHOLE_EXTENT(), wOutInfo.Get(vtkSDDP.WHOLE_EXTENT()), 6) return 1 def RequestData(self, vtkself, request, inInfo, outInfo): self.Wavelet.Update() out = self.GetOutputData(outInfo, 0) out.ShallowCopy(self.Wavelet.GetOutput()) return 1 ex = vtk.vtkPythonAlgorithm() ex.SetPythonObject(MyAlgorithm()) ex.Update() w = vtk.vtkRTAnalyticSource() w.Update() output = ex.GetOutputDataObject(0) self.assertEqual(output.GetPointData().GetScalars().GetRange(),\ w.GetOutput().GetPointData().GetScalars().GetRange()) vtkSDDP = vtk.vtkStreamingDemandDrivenPipeline self.assertEqual(ex.GetOutputInformation(0).Get(vtkSDDP.WHOLE_EXTENT()),\ w.GetOutputInformation(0).Get(vtkSDDP.WHOLE_EXTENT()))
def testImage2DScalar(self): planes = ['XY', 'XZ', 'YZ'] expectedNCells = [38, 46, 42] for plane, nCells in zip(planes,expectedNCells): r = vtk.vtkRTAnalyticSource() r.SetXFreq(600); r.SetYFreq(400); r.SetZFreq(900); if plane == 'XY': r.SetWholeExtent(-5, 5, -5, 5, 0, 0) elif plane == 'XZ': r.SetWholeExtent(-5, 5, 0, 0, -5, 5) else: r.SetWholeExtent(0, 0, -5, 5, -5, 5) r.Update() c = vtk.vtkTableBasedClipDataSet() c.SetInputConnection(r.GetOutputPort()) c.SetUseValueAsOffset(0) c.SetValue(150) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), nCells)
def test_exr_export_z(self): print "\nTEST EXR" try: exr except NameError: print "OpenEXR test disabled: No OpenEXR available." return # generate a test image rw = vtk.vtkRenderWindow() rw.SetSize(1920, 1080) # test HD resolution to compare sizes r = vtk.vtkRenderer() rw.AddRenderer(r) s = vtk.vtkRTAnalyticSource() s.SetWholeExtent(-25, 25, -25, 25, -25, 25) cf = vtk.vtkContourFilter() cf.SetInputConnection(s.GetOutputPort()) cf.SetInputArrayToProcess(0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_POINTS", "RTData") cf.SetNumberOfContours(1) cf.SetValue(0, 200) cf.ComputeScalarsOn() m = vtk.vtkPolyDataMapper() m.SetInputConnection(cf.GetOutputPort()) a = vtk.vtkActor() a.SetMapper(m) r.AddActor(a) rw.Render() r.ResetCamera() # Render & capture z-buffer image = ch.vtkRenderToArray(rw, "Z") del rw # save as im pil.Image.fromarray(image).save("/tmp/test_exr.im") loaded_im = np.array(pil.Image.open("/tmp/test_exr.im")) # save as exr exr.save_depth(image, "/tmp/test_exr.exr") # load saved file and compare loaded_exr = exr.load_depth("/tmp/test_exr.exr") self.assertTrue( np.all(image == loaded_exr) and np.all(loaded_exr == loaded_im))
def testImage(self): r = vtk.vtkRTAnalyticSource() r.SetWholeExtent(-5, 5, -5, 5, -5, 5) r.Update() s = vtk.vtkSphere() s.SetRadius(2) s.SetCenter(0,0,0) c = vtk.vtkTableBasedClipDataSet() c.SetInputConnection(r.GetOutputPort()) c.SetClipFunction(s) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), 64)
def testRectilinear(self): rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-5, 5, -5, 5, -5, 5) rt.Update() i = rt.GetOutput() r = vtk.vtkRectilinearGrid() dims = i.GetDimensions() r.SetDimensions(dims) exts = i.GetExtent() orgs = i.GetOrigin() xs = vtk.vtkFloatArray() xs.SetNumberOfTuples(dims[0]) for d in range(dims[0]): xs.SetTuple1(d, orgs[0] + exts[0] + d) r.SetXCoordinates(xs) ys = vtk.vtkFloatArray() ys.SetNumberOfTuples(dims[1]) for d in range(dims[1]): ys.SetTuple1(d, orgs[1] + exts[2] + d) r.SetYCoordinates(ys) zs = vtk.vtkFloatArray() zs.SetNumberOfTuples(dims[2]) for d in range(dims[2]): zs.SetTuple1(d, orgs[2] + exts[4] + d) r.SetZCoordinates(zs) s = vtk.vtkSphere() s.SetRadius(2) s.SetCenter(0,0,0) c = vtk.vtkTableBasedClipDataSet() c.SetInputData(r) c.SetClipFunction(s) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), 64)
def testStructured2D(self): planes = ['XY', 'XZ', 'YZ'] expectedNCells = [42, 34, 68] for plane, nCells in zip(planes,expectedNCells): rt = vtk.vtkRTAnalyticSource() if plane == 'XY': rt.SetWholeExtent(-5, 5, -5, 5, 0, 0) elif plane == 'XZ': rt.SetWholeExtent(-5, 5, 0, 0, -5, 5) else: rt.SetWholeExtent(0, 0, -5, 5, -5, 5) rt.Update() i = rt.GetOutput() st = vtk.vtkStructuredGrid() st.SetDimensions(i.GetDimensions()) nps = i.GetNumberOfPoints() ps = vtk.vtkPoints() ps.SetNumberOfPoints(nps) for idx in range(nps): ps.SetPoint(idx, i.GetPoint(idx)) st.SetPoints(ps) cyl = vtk.vtkCylinder() cyl.SetRadius(2) cyl.SetCenter(0,0,0) transform = vtk.vtkTransform() transform.RotateWXYZ(45,20,1,10) cyl.SetTransform(transform) c = vtk.vtkTableBasedClipDataSet() c.SetInputData(st) c.SetClipFunction(cyl) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), nCells)
def testSource(self): class MyAlgorithm(vta.VTKAlgorithm): def __init__(self): vta.VTKAlgorithm.__init__(self, nInputPorts=0, outputType='vtkImageData') self.Wavelet = vtk.vtkRTAnalyticSource() def RequestInformation(self, vtkself, request, inInfo, outInfo): self.Wavelet.UpdateInformation() wOutInfo = self.Wavelet.GetOutputInformation(0) vtkSDDP = vtk.vtkStreamingDemandDrivenPipeline outInfo.GetInformationObject(0).Set( vtkSDDP.WHOLE_EXTENT(), wOutInfo.Get(vtkSDDP.WHOLE_EXTENT()), 6) return 1 def RequestData(self, vtkself, request, inInfo, outInfo): self.Wavelet.Update() out = self.GetOutputData(outInfo, 0) out.ShallowCopy(self.Wavelet.GetOutput()) return 1 ex = vtk.vtkPythonAlgorithm() ex.SetPythonObject(MyAlgorithm()) ex.Update() w = vtk.vtkRTAnalyticSource() w.Update() output = ex.GetOutputDataObject(0) self.assertEqual(output.GetPointData().GetScalars().GetRange(),\ w.GetOutput().GetPointData().GetScalars().GetRange()) vtkSDDP = vtk.vtkStreamingDemandDrivenPipeline self.assertEqual(ex.GetOutputInformation(0).Get(vtkSDDP.WHOLE_EXTENT()),\ w.GetOutputInformation(0).Get(vtkSDDP.WHOLE_EXTENT()))
def test_basic(self): print "\nTEST BASIC" # a VTK program rw = vtk.vtkRenderWindow() rw.SetSize(1024, 768) r = vtk.vtkRenderer() rw.AddRenderer(r) s = vtk.vtkRTAnalyticSource() s.SetWholeExtent(-25, 25, -25, 25, -25, 25) cf = vtk.vtkContourFilter() cf.SetInputConnection(s.GetOutputPort()) cf.SetInputArrayToProcess(0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_POINTS", "RTData") cf.SetNumberOfContours(1) cf.SetValue(0, 200) cf.ComputeScalarsOn() m = vtk.vtkPolyDataMapper() m.SetInputConnection(cf.GetOutputPort()) a = vtk.vtkActor() a.SetMapper(m) r.AddActor(a) rw.Render() r.ResetCamera() # Create a Cinema store fname = "/tmp/test_vtk_basic/info.json" cs = file_store.FileStore(fname) cs.add_metadata({'type': 'parametric-image-stack'}) cs.add_metadata({'store_type': 'FS'}) cs.add_metadata({'version': '0.0'}) cs.filename_pattern = "{phi}_{theta}_{contour}.png" # These are the parameters that will vary in the store cs.add_parameter("phi", store.make_parameter('phi', range(0, 200, 80))) cs.add_parameter("theta", store.make_parameter('theta', range(-180, 200, 80))) cs.add_parameter("contour", store.make_parameter('contour', [160, 200])) # These objects respond to changes in parameters during exploration con = vtk_explorers.Contour('contour', cf, 'SetValue') cam = vtk_explorers.Camera([0, 0, 0], [0, 1, 0], 150.0, r.GetActiveCamera()) # phi,theta implied # Runs through all the combinations and saves each result e = vtk_explorers.ImageExplorer(cs, ['contour', 'phi', 'theta'], [cam, con], rw) # Go. e.explore() # Manually reproduce the first entry in the store # First set the camera to {'theta': -180, 'phi': 0} doc = store.Document({'theta': -180, 'phi': 0, 'contour': 160}) con.execute(doc) cam.execute(doc) imageslice = ch.vtkRenderToArray(rw) # Load the first entry from the store cs2 = file_store.FileStore(fname) cs2.load() docs = [] for doc in cs2.find({'theta': -180, 'phi': 0, 'contour': 160}): docs.append(doc.data) # compare the two l2error = ch.compare_l2(imageslice, docs[0]) ncc = ch.compare_ncc(imageslice, docs[0]) success = (l2error < 1.0) and (ncc > 0.99) if not success: print "\n l2error: ", l2error, " ; ncc = ", ncc, "\n" self.assertTrue(success)
def main(): colors = vtk.vtkNamedColors() # Generate an image data set with multiple attribute arrays to probe and view # We will glyph these points with cones and scale/orient/color them with the # various attributes # The Wavelet Source is nice for generating a test vtkImageData set rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-2, 2, -2, 2, 0, 0) # Take the gradient of the only scalar 'RTData' to get a vector attribute grad = vtk.vtkImageGradient() grad.SetDimensionality(3) grad.SetInputConnection(rt.GetOutputPort()) # Elevation just to generate another scalar attribute that varies nicely over the data range elev = vtk.vtkElevationFilter() # Elevation values will range from 0 to 1 between the Low and High Points elev.SetLowPoint(-2, 0, 0) elev.SetHighPoint(2, 0, 0) elev.SetInputConnection(grad.GetOutputPort()) # Generate the cone for the glyphs sph = vtk.vtkConeSource() sph.SetRadius(0.1) sph.SetHeight(0.5) # Set up the glyph filter glyph = vtk.vtkGlyph3D() glyph.SetInputConnection(elev.GetOutputPort()) glyph.SetSourceConnection(sph.GetOutputPort()) glyph.ScalingOn() glyph.SetScaleModeToScaleByScalar() glyph.SetVectorModeToUseVector() glyph.OrientOn() # Tell the filter to 'clamp' the scalar range glyph.ClampingOn() # Set the overall (multiplicative) scaling factor glyph.SetScaleFactor(1) # Set the Range to 'clamp' the data to # -- see equations above for nonintuitive definition of 'clamping' # The fact that I'm setting the minimum value of the range below # the minimum of my data (real min=0.0) with the equations above # forces a minimum non-zero glyph size. glyph.SetRange(-0.5, 1) # Change these values to see effect on cone sizes # Tell glyph which attribute arrays to use for what glyph.SetInputArrayToProcess(0, 0, 0, 0, 'Elevation') # scalars glyph.SetInputArrayToProcess(1, 0, 0, 0, 'RTDataGradient') # vectors # glyph.SetInputArrayToProcess(2,0,0,0,'nothing') # normals glyph.SetInputArrayToProcess(3, 0, 0, 0, 'RTData') # colors # Calling update because I'm going to use the scalar range to set the color map range glyph.Update() coloring_by = 'RTData' mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyph.GetOutputPort()) mapper.SetScalarModeToUsePointFieldData() mapper.SetColorModeToMapScalars() mapper.ScalarVisibilityOn() mapper.SetScalarRange( glyph.GetOutputDataObject(0).GetPointData().GetArray( coloring_by).GetRange()) mapper.SelectColorArray(coloring_by) actor = vtk.vtkActor() actor.SetMapper(mapper) ren = vtk.vtkRenderer() ren.AddActor(actor) ren.SetBackground(colors.GetColor3d('MidnightBlue')) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetWindowName('ClampGlyphSizes') iren = vtk.vtkRenderWindowInteractor() istyle = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(istyle) iren.SetRenderWindow(renWin) ren.ResetCamera() renWin.Render() iren.Start()
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # create a rendering window renWin = vtk.vtkRenderWindow() renWin.SetMultiSamples(0) renWin.SetSize(200, 200) wavelet = vtk.vtkRTAnalyticSource() wavelet.SetWholeExtent(-100, 100, -100, 100, 0, 0) wavelet.SetCenter(0, 0, 0) wavelet.SetMaximum(255) wavelet.SetStandardDeviation(.5) wavelet.SetXFreq(60) wavelet.SetYFreq(30) wavelet.SetZFreq(40) wavelet.SetXMag(10) wavelet.SetYMag(18) wavelet.SetZMag(5) wavelet.SetSubsampleRate(1) # linear transform transform = vtk.vtkTransform() transform.RotateZ(35) transformFilter = vtk.vtkTransformFilter() transformFilter.SetInputConnection(wavelet.GetOutputPort()) transformFilter.SetTransform(transform) mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(transformFilter.GetOutputPort())
#!/usr/bin/env python import os, json, sys import vtk args = sys.argv[1:] temp_dir = args[args.index("-T") + 1] # Always use / to prevent windows/python issue with backslash tmp_file = temp_dir + '/wavelet_slice_3.json' expected_first_values = [75.9335, 102.695, 91.2387, 115.507, 105.995, 125.724, 118.773, 132.24, 128.255, 134.254, 133.446, 131.431, 133.843, 123.998, 129.505] # Image pipeline image1 = vtk.vtkRTAnalyticSource() image1.Update() output = image1.GetOutput() dim_ref = [value for value in output.GetDimensions()] origin_ref = [value for value in output.GetOrigin()] spacing_ref = [value for value in output.GetSpacing()] print(dim_ref) print(origin_ref) print(spacing_ref) writer = vtk.vtkJSONImageWriter() writer.SetInputData(image1.GetOutput()) writer.SetFileName(tmp_file) writer.SetArrayName("RTData") writer.SetSlice(3) writer.Write()
def main(): # Generate an image data set with multiple attribute arrays to probe and view rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-3, 3, -3, 3, -3, 3) grad = vtk.vtkImageGradient() grad.SetDimensionality(3) grad.SetInputConnection(rt.GetOutputPort()) brown = vtk.vtkBrownianPoints() brown.SetMinimumSpeed(0.5) brown.SetMaximumSpeed(1.0) brown.SetInputConnection(grad.GetOutputPort()) elev = vtk.vtkElevationFilter() elev.SetLowPoint(-3, -3, -3) elev.SetHighPoint(3, 3, 3) elev.SetInputConnection(brown.GetOutputPort()) # Updating here because I will need to probe scalar ranges before # the render window updates the pipeline elev.Update() # Set up parallel coordinates representation to be used in View rep = vtk.vtkParallelCoordinatesRepresentation() rep.SetInputConnection(elev.GetOutputPort()) rep.SetInputArrayToProcess(0, 0, 0, 0, 'RTDataGradient') rep.SetInputArrayToProcess(1, 0, 0, 0, 'RTData') rep.SetInputArrayToProcess(2, 0, 0, 0, 'Elevation') rep.SetInputArrayToProcess(3, 0, 0, 0, 'BrownianVectors') rep.SetUseCurves(0) # set to 1 to use smooth curves rep.SetLineOpacity(0.5) # Set up the Parallel Coordinates View and hook in representation view = vtk.vtkParallelCoordinatesView() view.SetRepresentation(rep) view.SetInspectMode(view.VTK_INSPECT_SELECT_DATA) view.SetBrushOperatorToReplace() view.SetBrushModeToLasso() # Create a annotation link to access selection in parallel coordinates view annotationLink = vtk.vtkAnnotationLink() # If you don't set the FieldType explicitly it ends up as UNKNOWN # (as of 21 Feb 2010) # See vtkSelectionNode doc for field and content type enum values annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point annotationLink.GetCurrentSelection().GetNode(0).SetContentType( 4) # Indices # Update before passing annotationLink to vtkExtractSelection annotationLink.Update() # Connect the annotation link to the parallel coordinates representation rep.SetAnnotationLink(annotationLink) # Extract portion of data corresponding to parallel coordinates selection extract = vtk.vtkExtractSelection() extract.SetInputConnection(0, elev.GetOutputPort()) extract.SetInputConnection(1, annotationLink.GetOutputPort(2)) def update_render_windows(obj, event): """ Handle updating of RenderWindow since it's not a "View" and so not covered by vtkViewUpdater :param obj: :param event: :return: """ # ren.ResetCamera() renWin.Render() # Set up callback to update 3d render window when selections are changed in # parallel coordinates view annotationLink.AddObserver("AnnotationChangedEvent", update_render_windows) def toggle_inspectors(obj, event): if view.GetInspectMode() == 0: view.SetInspectMode(1) else: view.SetInspectMode(0) # Set up callback to toggle between inspect modes (manip axes & select data) view.GetInteractor().AddObserver("UserEvent", toggle_inspectors) # 3D outline of image data bounds outline = vtk.vtkOutlineFilter() outline.SetInputConnection(elev.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) # Build the lookup table for the 3d data scalar colors (brown to white) lut = vtk.vtkLookupTable() lut.SetTableRange(0, 256) lut.SetHueRange(0.1, 0.1) lut.SetSaturationRange(1.0, 0.1) lut.SetValueRange(0.4, 1.0) lut.Build() # Set up the 3d rendering parameters # of the image data which is selected in parallel coordinates coloring_by = 'Elevation' dataMapper = vtk.vtkDataSetMapper() dataMapper.SetInputConnection(extract.GetOutputPort()) dataMapper.SetScalarModeToUsePointFieldData() dataMapper.SetColorModeToMapScalars() data = elev.GetOutputDataObject(0).GetPointData() dataMapper.ScalarVisibilityOn() dataMapper.SetScalarRange(data.GetArray(coloring_by).GetRange()) dataMapper.SetLookupTable(lut) dataMapper.SelectColorArray(coloring_by) dataActor = vtk.vtkActor() dataActor.SetMapper(dataMapper) dataActor.GetProperty().SetRepresentationToPoints() dataActor.GetProperty().SetPointSize(10) # Set up the 3d render window and add both actors ren = vtk.vtkRenderer() ren.AddActor(outlineActor) ren.AddActor(dataActor) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren.ResetCamera() renWin.Render() # Finalize parallel coordinates view and start interaction event loop view.GetRenderWindow().SetSize(600, 300) view.ResetCamera() view.Render() view.GetInteractor().Start()
def GetSource(dataType): s = vtk.vtkRTAnalyticSource() if dataType == 'ImageData': return s elif dataType == 'UnstructuredGrid': dst = vtk.vtkDataSetTriangleFilter() dst.SetInputConnection(s.GetOutputPort()) return dst elif dataType == 'RectilinearGrid': s.Update() input = s.GetOutput() rg = vtk.vtkRectilinearGrid() rg.SetExtent(input.GetExtent()) dims = input.GetDimensions() spacing = input.GetSpacing() x = vtk.vtkFloatArray() x.SetNumberOfTuples(dims[0]) for i in range(dims[0]): x.SetValue(i, spacing[0]*i) y = vtk.vtkFloatArray() y.SetNumberOfTuples(dims[1]) for i in range(dims[1]): y.SetValue(i, spacing[1]*i) z = vtk.vtkFloatArray() z.SetNumberOfTuples(dims[2]) for i in range(dims[2]): z.SetValue(i, spacing[2]*i) rg.SetXCoordinates(x) rg.SetYCoordinates(y) rg.SetZCoordinates(z) rg.GetPointData().ShallowCopy(input.GetPointData()) pf.SetInputData(rg) return pf elif dataType == 'StructuredGrid': s.Update() input = s.GetOutput() sg = vtk.vtkStructuredGrid() sg.SetExtent(input.GetExtent()) pts = vtk.vtkPoints() sg.SetPoints(pts) npts = input.GetNumberOfPoints() for i in range(npts): pts.InsertNextPoint(input.GetPoint(i)) sg.GetPointData().ShallowCopy(input.GetPointData()) pf.SetInputData(sg) return pf elif dataType == 'Table': s.Update() input = s.GetOutput() table = vtk.vtkTable() RTData = input.GetPointData().GetArray(0) nbTuples = RTData.GetNumberOfTuples() array = vtk.vtkFloatArray() array.SetName("RTData") array.SetNumberOfTuples(nbTuples) for i in range(0, nbTuples): array.SetTuple1(i, float(RTData.GetTuple1(i))) table.AddColumn(array) pf.SetInputData(table) return pf
# All rights reserved. # See Copyright.txt or http:#www.kitware.com/Copyright.htm for details. # # This software is distributed WITHOUT ANY WARRANTY without even # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. See the above copyright notice for more information. # #========================================================================= import vtk dim = 48 center = [float(dim) / 2.0] * 3 extent = [0, dim - 1, 0, dim - 1, 0, dim - 1] imageSource = vtk.vtkRTAnalyticSource() imageSource.SetWholeExtent(extent[0], extent[1], extent[2], extent[3], extent[4], extent[5]) imageSource.SetCenter(center) imageSource.Update() img = imageSource.GetOutput() scalarRange = img.GetScalarRange() origin = img.GetOrigin() spacing = img.GetSpacing() # create an unstructured grid by generating a point cloud and # applying Delaunay triangulation on it. vtk.vtkMath().RandomSeed(0) # vtkPointSource internally uses vtkMath::Random() pointSource = vtk.vtkPointSource() pointSource.SetCenter(center)
def main(): colors = vtk.vtkNamedColors() # Generate an example image data set with multiple attribute arrays to probe # and view. # This is where you would put your reader instead of this rt->elev pipeline... rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-3, 3, -3, 3, -3, 3) grad = vtk.vtkImageGradient() grad.SetDimensionality(3) grad.SetInputConnection(rt.GetOutputPort()) brown = vtk.vtkBrownianPoints() brown.SetMinimumSpeed(0.5) brown.SetMaximumSpeed(1.0) brown.SetInputConnection(grad.GetOutputPort()) elev = vtk.vtkElevationFilter() elev.SetLowPoint(-3, -3, -3) elev.SetHighPoint(3, 3, 3) elev.SetInputConnection(brown.GetOutputPort()) # Set up the parallel coordinates Representation to be used in the View rep = vtk.vtkParallelCoordinatesRepresentation() # Plug your reader in here for your own data rep.SetInputConnection(elev.GetOutputPort()) # List all of the attribute arrays you want plotted in parallel coordinates rep.SetInputArrayToProcess(0, 0, 0, 0, 'RTDataGradient') rep.SetInputArrayToProcess(1, 0, 0, 0, 'RTData') rep.SetInputArrayToProcess(2, 0, 0, 0, 'Elevation') rep.SetInputArrayToProcess(3, 0, 0, 0, 'BrownianVectors') rep.SetUseCurves(0) # set to 1 to use smooth curves rep.SetLineOpacity(0.5) rep.SetAxisColor(colors.GetColor3d('Gold')) rep.SetLineColor(colors.GetColor3d('MistyRose')) # Set up the Parallel Coordinates View and hook in the Representation view = vtk.vtkParallelCoordinatesView() view.SetRepresentation(rep) # Inspect Mode determines whether your interactions manipulate the axes or # select data # view.SetInspectMode(view.VTK_INSPECT_MANIPULATE_AXES) # VTK_INSPECT_MANIPULATE_AXES = 0, view.SetInspectMode( view.VTK_INSPECT_SELECT_DATA) # VTK_INSPECT_SELECT_DATA = 1 # Brush Mode determines the type of interaction you perform to select data view.SetBrushModeToLasso() # view.SetBrushModeToAngle() # view.SetBrushModeToFunction() # view.SetBrushModeToAxisThreshold() # not implemented yet (as of 21 Feb 2010) # Brush Operator determines how each new selection interaction changes # selected lines # view.SetBrushOperatorToAdd() # view.SetBrushOperatorToSubtract() # view.SetBrushOperatorToIntersect() view.SetBrushOperatorToReplace() def ToggleInspectors(obj, event): # Define the callback routine which toggles between 'Inspect Modes' if view.GetInspectMode() == 0: view.SetInspectMode(1) else: view.SetInspectMode(0) # Hook up the callback to toggle between inspect modes # (manip axes & select data) view.GetInteractor().AddObserver('UserEvent', ToggleInspectors) # Set up render window view.GetRenderWindow().SetSize(600, 300) view.GetRenderWindow().SetWindowName('ParallelCoordinatesView') view.GetRenderer().GradientBackgroundOn() view.GetRenderer().SetBackground2(colors.GetColor3d('DarkBlue')) view.GetRenderer().SetBackground(colors.GetColor3d('MidnightBlue')) view.ResetCamera() view.Render() # Start interaction event loop view.GetInteractor().Start()
def __init__(self): vta.VTKAlgorithm.__init__(self, nInputPorts=0, outputType='vtkImageData') self.Wavelet = vtk.vtkRTAnalyticSource()
def test_composite(self): print "\nTEST VTK LAYERS" # set up some processing task s = vtk.vtkRTAnalyticSource() s.SetWholeExtent(-50, 50, -50, 50, -50, 50) rw = vtk.vtkRenderWindow() r = vtk.vtkRenderer() rw.AddRenderer(r) ac1 = vtk.vtkArrayCalculator() ac1.SetInputConnection(s.GetOutputPort()) ac1.SetAttributeModeToUsePointData() ac1.AddCoordinateVectorVariable("coords", 0, 1, 2) ac1.SetResultArrayName("Coords") ac1.SetFunction("coords") ac2 = vtk.vtkArrayCalculator() ac2.SetInputConnection(ac1.GetOutputPort()) ac2.SetAttributeModeToUsePointData() ac2.AddCoordinateVectorVariable("coords", 0, 1, 2) ac2.SetResultArrayName("radii") ac2.SetFunction("mag(coords)") cf = vtk.vtkContourFilter() cf.SetInputConnection(ac2.GetOutputPort()) cf.SetInputArrayToProcess(0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_POINTS", "radii") cf.SetNumberOfContours(1) cf.ComputeScalarsOff() cf.SetValue(0, 40) m = vtk.vtkPolyDataMapper() m.SetInputConnection(cf.GetOutputPort()) a = vtk.vtkActor() a.SetMapper(m) r.AddActor(a) rw.Render() r.ResetCamera() # make a cinema data store by defining the things that vary fname = "/tmp/test_vtk_composite/info.json" cs = file_store.FileStore(fname) cs.add_metadata({'type': 'composite-image-stack'}) cs.add_metadata({'store_type': 'FS'}) cs.add_metadata({'version': '0.1'}) cs.filename_pattern = "{phi}/{theta}/{vis}.png" cs.add_parameter("phi", store.make_parameter('phi', range(0, 200, 50))) cs.add_parameter("theta", store.make_parameter('theta', range(-180, 200, 45))) cs.add_layer("vis", store.make_parameter("vis", ['contour'])) contours = [15, 30, 55, 70, 85] cs.add_control("isoval", store.make_parameter('isoval', contours)) cs.assign_parameter_dependence("isoval", "vis", ['contour']) cs.add_field( "color", store.make_field( 'color', { 'white': 'rgb', 'red': 'rgb', 'depth': 'depth', 'lum': 'luminance', 'RTData': 'value', 'point_X': 'value', 'point_Y': 'value', 'point_Z': 'value' }), "isoval", contours) # associate control points with parameters of the data store cam = vtk_explorers.Camera([0, 0, 0], [0, 1, 0], 300.0, r.GetActiveCamera()) showcontour = vtk_explorers.ActorInLayer('contour', a) layertrack = explorers.Layer('vis', [showcontour]) controltrack = vtk_explorers.Contour('isoval', cf, 'SetValue') # additional specification necessary for the color field colorChoice = vtk_explorers.ColorList() colorChoice.AddSolidColor('white', [1, 1, 1]) colorChoice.AddSolidColor('red', [1, 0, 0]) colorChoice.AddDepth('depth') colorChoice.AddLuminance('lum') colorChoice.AddValueRender('RTData', vtk.VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, 'RTData', 0, [0, 250]) colorChoice.AddValueRender('point_X', vtk.VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, 'Coords', 0, [-50, 50]) colorChoice.AddValueRender('point_Y', vtk.VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, 'Coords', 1, [-50, 50]) colorChoice.AddValueRender('point_Z', vtk.VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, 'Coords', 2, [-50, 50]) colortrack = vtk_explorers.Color('color', colorChoice, a) paramNames = ['phi', 'theta', 'vis', 'isoval', 'color'] trackList = [cam, layertrack, controltrack, colortrack] e = vtk_explorers.ImageExplorer(cs, paramNames, trackList, rw) colortrack.imageExplorer = e e.explore() cs.save()
def GetSource(dataType): s = vtk.vtkRTAnalyticSource() if dataType == 'ImageData': return s elif dataType == 'UnstructuredGrid': dst = vtk.vtkDataSetTriangleFilter() dst.SetInputConnection(s.GetOutputPort()) return dst elif dataType == 'RectilinearGrid': s.Update() input = s.GetOutput() rg = vtk.vtkRectilinearGrid() rg.SetExtent(input.GetExtent()) dims = input.GetDimensions() spacing = input.GetSpacing() x = vtk.vtkFloatArray() x.SetNumberOfTuples(dims[0]) for i in range(dims[0]): x.SetValue(i, spacing[0] * i) y = vtk.vtkFloatArray() y.SetNumberOfTuples(dims[1]) for i in range(dims[1]): y.SetValue(i, spacing[1] * i) z = vtk.vtkFloatArray() z.SetNumberOfTuples(dims[2]) for i in range(dims[2]): z.SetValue(i, spacing[2] * i) rg.SetXCoordinates(x) rg.SetYCoordinates(y) rg.SetZCoordinates(z) rg.GetPointData().ShallowCopy(input.GetPointData()) pf.SetInputData(rg) return pf elif dataType == 'StructuredGrid': s.Update() input = s.GetOutput() sg = vtk.vtkStructuredGrid() sg.SetExtent(input.GetExtent()) pts = vtk.vtkPoints() sg.SetPoints(pts) npts = input.GetNumberOfPoints() for i in range(npts): pts.InsertNextPoint(input.GetPoint(i)) sg.GetPointData().ShallowCopy(input.GetPointData()) pf.SetInputData(sg) return pf
from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # to mark the origin sphere = vtk.vtkSphereSource() sphere.SetRadius(2.0) sphereMapper = vtk.vtkPolyDataMapper() sphereMapper.SetInputConnection(sphere.GetOutputPort()) sphereMapper.ImmediateModeRenderingOn() sphereActor = vtk.vtkActor() sphereActor.SetMapper(sphereMapper) rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-50, 50, -50, 50, 0, 0) voi = vtk.vtkExtractVOI() voi.SetInputConnection(rt.GetOutputPort()) voi.SetVOI(-11, 39, 5, 45, 0, 0) voi.SetSampleRate(5, 5, 1) # Get rid of ambiguous triagulation issues. surf = vtk.vtkDataSetSurfaceFilter() surf.SetInputConnection(voi.GetOutputPort()) tris = vtk.vtkTriangleFilter() tris.SetInputConnection(surf.GetOutputPort()) mapper = vtk.vtkPolyDataMapper()
# All rights reserved. # See Copyright.txt or http:#www.kitware.com/Copyright.htm for details. # # This software is distributed WITHOUT ANY WARRANTY without even # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. See the above copyright notice for more information. # #========================================================================= import vtk dim = 48 center = [float(dim)/2.0]*3 extent = [ 0, dim - 1, 0, dim - 1, 0, dim - 1] imageSource = vtk.vtkRTAnalyticSource() imageSource.SetWholeExtent(extent[0], extent[1], extent[2], extent[3], extent[4], extent[5]) imageSource.SetCenter(center) imageSource.Update() img = imageSource.GetOutput() scalarRange = img.GetScalarRange() origin = img.GetOrigin() spacing = img.GetSpacing() # create an unstructured grid by generating a point cloud and # applying Delaunay triangulation on it. vtk.vtkMath().RandomSeed(0) # vtkPointSource internally uses vtkMath::Random() pointSource = vtk.vtkPointSource()
import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # create a rendering window renWin = vtk.vtkRenderWindow() renWin.SetMultiSamples(0) renWin.SetSize(200, 200) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) wavelet = vtk.vtkRTAnalyticSource() wavelet.SetWholeExtent(-100, 100, -100, 100, 0, 0) wavelet.SetCenter(0, 0, 0) wavelet.SetMaximum(255) wavelet.SetStandardDeviation(.5) wavelet.SetXFreq(60) wavelet.SetYFreq(30) wavelet.SetZFreq(40) wavelet.SetXMag(10) wavelet.SetYMag(18) wavelet.SetZMag(5) wavelet.SetSubsampleRate(1) warp = vtk.vtkWarpScalar() warp.SetInputConnection(wavelet.GetOutputPort())
def main(): colors = vtk.vtkNamedColors() # The Wavelet Source is nice for generating a test vtkImageData set rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-2, 2, -2, 2, 0, 0) # Take the gradient of the only scalar 'RTData' to get a vector attribute grad = vtk.vtkImageGradient() grad.SetDimensionality(3) grad.SetInputConnection(rt.GetOutputPort()) # Elevation just to generate another scalar attribute that varies nicely over the data range elev = vtk.vtkElevationFilter() # Elevation values will range from 0 to 1 between the Low and High Points elev.SetLowPoint(-2, -2, 0) elev.SetHighPoint(2, 2, 0) elev.SetInputConnection(grad.GetOutputPort()) # Create simple PolyData for glyph table cs = vtk.vtkCubeSource() cs.SetXLength(0.5) cs.SetYLength(1) cs.SetZLength(2) ss = vtk.vtkSphereSource() ss.SetRadius(0.25) cs2 = vtk.vtkConeSource() cs2.SetRadius(0.25) cs2.SetHeight(0.5) # Set up the glyph filter glyph = vtk.vtkGlyph3D() glyph.SetInputConnection(elev.GetOutputPort()) # Here is where we build the glyph table # that will be indexed into according to the IndexMode glyph.SetSourceConnection(0, cs.GetOutputPort()) glyph.SetSourceConnection(1, ss.GetOutputPort()) glyph.SetSourceConnection(2, cs2.GetOutputPort()) glyph.ScalingOn() glyph.SetScaleModeToScaleByScalar() glyph.SetVectorModeToUseVector() glyph.OrientOn() glyph.SetScaleFactor(1) # Overall scaling factor glyph.SetRange(0, 1) # Default is (0,1) # Tell it to index into the glyph table according to scalars glyph.SetIndexModeToScalar() # Tell glyph which attribute arrays to use for what glyph.SetInputArrayToProcess(0, 0, 0, 0, 'Elevation') # scalars glyph.SetInputArrayToProcess(1, 0, 0, 0, 'RTDataGradient') # vectors coloring_by = 'Elevation' mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyph.GetOutputPort()) mapper.SetScalarModeToUsePointFieldData() mapper.SetColorModeToMapScalars() mapper.ScalarVisibilityOn() # GetRange() call doesn't work because attributes weren't copied to glyphs # as they should have been... # mapper.SetScalarRange(glyph.GetOutputDataObject(0).GetPointData().GetArray(coloring_by).GetRange()) mapper.SelectColorArray(coloring_by) actor = vtk.vtkActor() actor.SetMapper(mapper) ren = vtk.vtkRenderer() ren.AddActor(actor) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() istyle = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(istyle) iren.SetRenderWindow(renWin) ren.ResetCamera() renWin.Render() iren.Start()
def GetSource(dataType): s = vtk.vtkRTAnalyticSource() # Fake serial source if rank == 0: s.Update() if dataType == 'ImageData': return s.GetOutput() elif dataType == 'UnstructuredGrid': dst = vtk.vtkDataSetTriangleFilter() dst.SetInputData(s.GetOutput()) dst.Update() return dst.GetOutput() elif dataType == 'RectilinearGrid': input = s.GetOutput() rg = vtk.vtkRectilinearGrid() rg.SetExtent(input.GetExtent()) dims = input.GetDimensions() spacing = input.GetSpacing() x = vtk.vtkFloatArray() x.SetNumberOfTuples(dims[0]) for i in range(dims[0]): x.SetValue(i, spacing[0]*i) y = vtk.vtkFloatArray() y.SetNumberOfTuples(dims[1]) for i in range(dims[1]): y.SetValue(i, spacing[1]*i) z = vtk.vtkFloatArray() z.SetNumberOfTuples(dims[2]) for i in range(dims[2]): z.SetValue(i, spacing[2]*i) rg.SetXCoordinates(x) rg.SetYCoordinates(y) rg.SetZCoordinates(z) rg.GetPointData().ShallowCopy(input.GetPointData()) return rg elif dataType == 'StructuredGrid': input = s.GetOutput() sg = vtk.vtkStructuredGrid() sg.SetExtent(input.GetExtent()) pts = vtk.vtkPoints() sg.SetPoints(pts) npts = input.GetNumberOfPoints() for i in xrange(npts): pts.InsertNextPoint(input.GetPoint(i)) sg.GetPointData().ShallowCopy(input.GetPointData()) return sg
import os, json, sys import vtk args = sys.argv[1:] temp_dir = args[args.index("-T") + 1] # Always use / to prevent windows/python issue with backslash tmp_file = temp_dir + '/wavelet_slice_3.json' expected_first_values = [ 75.9335, 102.695, 91.2387, 115.507, 105.995, 125.724, 118.773, 132.24, 128.255, 134.254, 133.446, 131.431, 133.843, 123.998, 129.505 ] # Image pipeline image1 = vtk.vtkRTAnalyticSource() image1.Update() output = image1.GetOutput() dim_ref = [value for value in output.GetDimensions()] origin_ref = [value for value in output.GetOrigin()] spacing_ref = [value for value in output.GetSpacing()] print(dim_ref) print(origin_ref) print(spacing_ref) writer = vtk.vtkJSONImageWriter() writer.SetInputData(image1.GetOutput()) writer.SetFileName(tmp_file) writer.SetArrayName("RTData") writer.SetSlice(3)
PRINT( "rtData sum:", (algs.sum(rtData) - numpy.sum(rtData2)) / (2*numpy.sum(rtData2)) ) PRINT( "rtData mean:", (algs.mean(rtData) - numpy.mean(rtData2)) / (2*numpy.mean(rtData2)) ) PRINT( "rtData var:", (algs.var(rtData) - numpy.var(rtData2)) / numpy.var(rtData2) ) PRINT( "rtData std:", (algs.std(rtData) - numpy.std(rtData2)) / numpy.std(rtData2) ) PRINT( "grad min:", algs.min(grad) - numpy.min(grad2) ) PRINT( "grad max:", algs.max(grad) - numpy.max(grad2) ) PRINT( "grad min 0:", algs.min(grad, 0) - numpy.min(grad2, 0) ) PRINT( "grad max 0:", algs.max(grad, 0) - numpy.max(grad2, 0) ) PRINT( "grad min 1:", algs.sum(algs.min(grad, 1)) - numpy.sum(numpy.min(grad2, 1)) ) PRINT( "grad max 1:", algs.sum(algs.max(grad, 1)) - numpy.sum(numpy.max(grad2, 1)) ) PRINT( "grad sum 1:", algs.sum(algs.sum(grad, 1)) - numpy.sum(numpy.sum(grad2, 1)) ) PRINT( "grad var:", (algs.var(grad) - numpy.var(grad2)) / numpy.var(grad2) ) PRINT( "grad var 0:", (algs.var(grad, 0) - numpy.var(grad2, 0)) / numpy.var(grad2, 0) ) w = vtk.vtkRTAnalyticSource() w.UpdateInformation() # Update with ghost level because gradient needs it # to be piece independent w.SetUpdateExtent(rank, size, 1) w.Update() # The parallel arrays that we care about ds = dsa.WrapDataObject(w.GetOutput()) rtData = ds.PointData['RTData'] grad = algs.gradient(rtData) ds.PointData.append(grad, 'gradient') # Crop the any ghost points out org_ext = w.GetOutput().GetExtent() ext = list(org_ext)
import sys import vtk.test.Testing try: import numpy except ImportError: print("Numpy (http://numpy.scipy.org) not found.") print("This test requires numpy!") vtk.test.Testing.skip() import vtk import vtk.numpy_interface.dataset_adapter as dsa import vtk.numpy_interface.algorithms as algs w = vtk.vtkRTAnalyticSource() bp = vtk.vtkBrownianPoints() bp.SetInputConnection(w.GetOutputPort()) bp.Update() elev = vtk.vtkElevationFilter() elev.SetInputConnection(bp.GetOutputPort()) elev.SetLowPoint(-10, 0, 0) elev.SetHighPoint(10, 0, 0) elev.SetScalarRange(0, 20) g = vtk.vtkMultiBlockDataGroupFilter() g.AddInputConnection(elev.GetOutputPort()) g.AddInputConnection(elev.GetOutputPort()) g.Update()
def test_contour(self): print "\nTEST CONTOUR" # set up some processing task s = vtk.vtkRTAnalyticSource() s.SetWholeExtent(-50, 50, -50, 50, -50, 50) cf = vtk.vtkContourFilter() cf.SetInputConnection(s.GetOutputPort()) cf.SetInputArrayToProcess(0, 0, 0, "vtkDataObject::FIELD_ASSOCIATION_POINTS", "RTData") cf.SetNumberOfContours(1) cf.SetValue(0, 100) m = vtk.vtkPolyDataMapper() m.SetInputConnection(cf.GetOutputPort()) rw = vtk.vtkRenderWindow() r = vtk.vtkRenderer() rw.AddRenderer(r) a = vtk.vtkActor() a.SetMapper(m) r.AddActor(a) rw.Render() r.ResetCamera() # make or open a cinema data store to put results in fname = "/tmp/test_vtk_contour/info.json" cs = file_store.FileStore(fname) cs.add_metadata({'type': 'parametric-image-stack'}) cs.add_metadata({'store_type': 'FS'}) cs.add_metadata({'version': '0.0'}) cs.filename_pattern = "{contour}_{color}.png" cs.add_parameter( "contour", store.make_parameter( 'contour', [0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250])) cs.add_parameter("color", store.make_parameter('color', ['white', 'red'])) colorChoice = vtk_explorers.ColorList() colorChoice.AddSolidColor('white', [1, 1, 1]) colorChoice.AddSolidColor('red', [1, 0, 0]) # associate control points with parameters of the data store g = vtk_explorers.Contour('contour', cf, 'SetValue') c = vtk_explorers.Color('color', colorChoice, a) e = vtk_explorers.ImageExplorer(cs, ['contour', 'color'], [g, c], rw) # run through all parameter combinations and put data into the store e.explore() # Now let's reproduce an entry in the store # First set the parameters to {'contour': 75} and {'color': 'white'} g.execute(store.Document({'contour': 75})) c.execute(store.Document({'color': 'white'})) imageslice = ch.vtkRenderToArray(rw) # Now load the same entry from the store cs2 = file_store.FileStore(fname) cs2.load() docs = [] for doc in cs2.find({'contour': 75, 'color': 'white'}): docs.append(doc.data) # compare the two l2error = ch.compare_l2(imageslice, docs[0]) ncc = ch.compare_ncc(imageslice, docs[0]) self.assertTrue((l2error < 1.0) and (ncc > 0.99))