コード例 #1
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)
        # initialise any mixins we might have
        NoConfigModuleMixin.__init__(self)

        self._distance = vtk.vtkImageEuclideanDistance()
        # this seems to yield more accurate results in this case
        # it would probably be better to calculate only 2d distance fields
        self._distance.ConsiderAnisotropyOff()

        self._xEndPoints = []
        self._noFlipXes = []
        self._pf1 = vtk.vtkProgrammableFilter()  # yeah
        self._pf1.SetInput(self._distance.GetOutput())
        self._pf1.SetExecuteMethod(self.pf1Execute)

        self._pf2 = vtk.vtkProgrammableFilter()
        self._pf2.SetInput(self._pf1.GetOutput())
        self._pf2.SetExecuteMethod(self.pf2Execute)

        self._mc = vtk.vtkMarchingCubes()
        self._mc.SetInput(self._pf1.GetOutput())
        self._mc.SetValue(0, 0.1)

        self._iv = vtk.vtkImplicitVolume()
        self._iv.SetVolume(self._pf2.GetOutput())

        self._cpd = vtk.vtkClipPolyData()
        self._cpd.SetClipFunction(self._iv)
        self._cpd.SetInput(self._mc.GetOutput())
        #self._cpd.InsideOutOn()

        module_utils.setup_vtk_object_progress(
            self, self._distance, 'Calculating distance field...')
        module_utils.setup_vtk_object_progress(self, self._pf1,
                                               'Signing distance field...')
        module_utils.setup_vtk_object_progress(self, self._pf2,
                                               'Creating implicit volume...')
        module_utils.setup_vtk_object_progress(self, self._mc,
                                               'Extracting isosurface...')
        module_utils.setup_vtk_object_progress(self, self._cpd,
                                               'Clipping isosurface...')

        self._iObj = self._distance
        self._oObj = self._cpd
        #self._oObj = self._pf2

        self._viewFrame = self._createViewFrame({
            'distance': self._distance,
            'pf1': self._pf1,
            'pf2': self._pf2,
            'mc': self._mc,
            'cpd': self._cpd
        })
def tessellation_callback(tessellation, size_of_cell1, tolerance1):
    input_data = tessellation.GetPolyDataInput()
    output_data = tessellation.GetPolyDataOutput()
    output_data.ShallowCopy(input_data)

    # Triangulate Surface.
    triangle_data = vtk.vtkTriangleFilter()
    triangle_data.SetInputData(output_data)
    triangle_data.Update()
    triangulated_model = triangle_data.GetOutput()

    number_of_polys = triangulated_model.GetNumberOfPolys()
    append_filter = vtk.vtkAppendPolyData()

    # Iterate over triangles.
    for i in range(0, 40):

        # Apply point generation filter.
        cell_index = i
        point_generation = vtk.vtkProgrammableFilter()
        point_generation.AddInputData(triangulated_model)
        point_generation.SetExecuteMethod(
            pointGenerationFilterBase.point_generation_callback(
                point_generation, cell_index, size_of_cell1))
        current_polydata = point_generation.GetPolyDataOutput()

        # Append current triangulation polyData to total model polyData.
        append_filter.AddInputData(current_polydata)
        append_filter.Update()

    # Triangulate current cells generated points.
    delaunay2D = vtk.vtkDelaunay2D()
    delaunay2D.SetInputData(append_filter.GetOutput())
    delaunay2D.SetSourceData(append_filter.GetOutput())
    delaunay2D.SetTolerance(tolerance1)
    delaunay2D.Update()

    # Remove degenerate triangles and remove duplicate points.
    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputData(delaunay2D.GetOutput())
    cleaner.Update()

    polygonation = vtk.vtkProgrammableFilter()
    polygonation.AddInputData(cleaner.GetOutput())
    polygonation.SetExecuteMethod(
        polygonation3DBase.polygonation_callback(polygonation))

    output_data.SetPolys(polygonation.GetOutput().GetPolys())
    output_data.SetPoints(polygonation.GetOutput().GetPoints())
コード例 #3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkProgrammableFilter(), 'Processing.',
         ('vtkDataSet',), ('vtkDataSet',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
コード例 #4
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkProgrammableFilter(),
                                       'Processing.', ('vtkDataSet', ),
                                       ('vtkDataSet', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
コード例 #5
0
ファイル: vexport.py プロジェクト: DavideBaroliUniLu/siconos
        def __init__(self, instance, data_name='velocity', data_size=6):

            self._instance = instance
            self._data_name = data_name
            self._data_size = data_size
            self._connector = vtk.vtkProgrammableFilter()
            self._connector.SetExecuteMethod(self.method)
            self._data = numpy.zeros(data_size)
            self._vtk_data = vtk.vtkFloatArray()
            self._vtk_data.SetName(data_name)
            self._vtk_data.SetNumberOfComponents(data_size)
            self._vtk_data.SetNumberOfTuples(1)
コード例 #6
0
def create_pipeline():
    reader = get_mesh_source(mesh_file_name)

    pf = vtk.vtkProgrammableFilter()
    pf.SetInputConnection(reader.GetOutputPort())
    algo = PluginAlgorithm(pf)
    pf.SetExecuteMethod(algo)

    renWin, iren = create_scene(pf, reader)

    # some additional customization
    renWin.SetWindowName("Demo plugin")

    renWin.Render()
    time.sleep(3)

    iren.Start()
def main():

    # Read in data set.
    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName("quadMeshFullc4080.vtp")
    reader.Update()

    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInputConnection(reader.GetOutputPort())
    cleaner.Update()

    # Apply tessellation filter.
    tessellation = vtk.vtkProgrammableFilter()
    tessellation.AddInputConnection(cleaner.GetOutputPort())
    tessellation.SetExecuteMethod(
        tessellation_callback(tessellation, 250, 0.008))

    # Set up mapper.
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(tessellation.GetOutput())
    mapper.ScalarVisibilityOff()

    # Set up actor.
    actor = vtk.vtkLODActor()
    actor.SetMapper(mapper)

    # Render.
    ren = vtk.vtkRenderer()
    ren_win = vtk.vtkRenderWindow()
    ren_win.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(ren_win)

    # Add the actors to the renderer, set the background and size.
    ren.AddActor(actor)
    ren.SetBackground(0.1, 0.2, 0.4)
    ren_win.SetSize(800, 800)

    # Start event.
    iren.Initialize()
    ren_win.Render()
    iren.Start()
コード例 #8
0
    def make_models(self):
        """
        make models
        """
        # We create a 100 by 100 point plane to sample
        self.plane = vtk.vtkPlaneSource()
        self.plane.SetXResolution(self.resolution)
        self.plane.SetYResolution(self.resolution)

        # We transform the plane by a factor of 10 on X and Y and 1 Z
        transform = vtk.vtkTransform()
        transform.Scale(10, 10, 1)
        transF = vtk.vtkTransformPolyDataFilter()
        transF.SetInputConnection(self.plane.GetOutputPort())
        transF.SetTransform(transform)

        # Compute Bessel function and derivatives. We'll use a programmable filter
        # for this. Note the unusual GetPolyDataInput() & GetOutputPort() methods.
        besselF = vtk.vtkProgrammableFilter()
        besselF.SetInputConnection(transF.GetOutputPort())

        # The SetExecuteMethod takes a Python function as an argument
        # In here is where all the processing is done.
        def bessel():
            inputs = besselF.GetPolyDataInput()
            numPts = inputs.GetNumberOfPoints()
            newPts = vtk.vtkPoints()
            derivs = vtk.vtkFloatArray()

            for i in xrange(0, numPts):
                x = inputs.GetPoint(i)
                x0, x1 = x[:2]

                r = sqrt(x0*x0+x1*x1)
                x2 = exp(-r)*cos(self.factor*r)
                deriv = -exp(-r)*(cos(self.factor*r)+self.factor*sin(self.factor*r))

                newPts.InsertPoint(i, x0, x1, x2)
                derivs.InsertValue(i, deriv)

            besselF.GetPolyDataOutput().CopyStructure(inputs)
            besselF.GetPolyDataOutput().SetPoints(newPts)
            besselF.GetPolyDataOutput().GetPointData().SetScalars(derivs)

        besselF.SetExecuteMethod(bessel)

        # We warp the plane based on the scalar values calculated above
        warp = vtk.vtkWarpScalar()
        warp.SetInputConnection(besselF.GetOutputPort())
        warp.XYPlaneOn()
        warp.SetScaleFactor(self.scale_factor)

        # We create a mapper and actor as usual. In the case we adjust the
        # scalar range of the mapper to match that of the computed scalars
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(warp.GetOutputPort())
        mapper.SetScalarRange(besselF.GetPolyDataOutput().GetScalarRange())
        carpet = vtk.vtkActor()
        carpet.SetMapper(mapper)

        self.surface_actor = carpet

        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(warp.GetOutputPort())

        outline_mapper = vtk.vtkPolyDataMapper()
        outline_mapper.SetInputConnection(outline.GetOutputPort())

        self.outline_actor = vtk.vtkActor()
        self.outline_actor.SetMapper(outline_mapper)
        self.outline_actor.GetProperty().SetColor(0, 0, 0)

        self.warp_geometry = warp
コード例 #9
0
ファイル: expcos.py プロジェクト: MBrill/VTKExamples
plane.SetYResolution(100)

#
# We transform the plane by a factor of 10 on X and Y
#
transform = vtk.vtkTransform()
transform.Scale(10, 10, 1)
transF = vtk.vtkTransformPolyDataFilter()
transF.SetPolyDataInput(plane.GetPolyDataOutput)
transF.SetTransform(transform)

#
# Compute Bessel function and derivatives. We'll use a programmable filter
# for this. Note the unusual GetInput() & GetOutput() methods.
#
besselF = vtk.vtkProgrammableFilter()
besselF.SetInput(transf.GetOutput())
besselF.SetExecuteMethode(besel)


#
# The SetExecuteMethod takes a Tcl proc as an argument
# In here is where all the processing is done.
#
def bessel():
    input = besselF.GetPolyDataInput()
    numPts = input.GetNumberOfPoints()
    newPts = vtk.vtkPoints()
    derivs = vtk.vtkFloatArray()
    
コード例 #10
0
    def _setup_pipeline(self):
        ren = vtk.vtkRenderer()
        ren.SetBackground(1.0, 1.0, 1.0)

        color_points = vtk.vtkProgrammableFilter()

        def callback_color_points():
            input_ = color_points.GetInput()
            output = color_points.GetOutput()
            output.ShallowCopy(input_)

            lookup = vtk.vtkFloatArray()
            lookup.SetNumberOfValues(input_.GetNumberOfPoints())
            npy_lookup = vtk_to_numpy(lookup)
            npy_lookup.flat = self._k.astype(
                np.float32) / (COLORMAP.shape[0] - 1)

            output.GetPointData().SetScalars(lookup)

        color_points.SetExecuteMethod(callback_color_points)

        source = vtk.vtkCubeSource()

        vertices_glyph = vtk.vtkGlyph3D()
        vertices_glyph.SetInputConnection(color_points.GetOutputPort())
        vertices_glyph.SetSourceConnection(source.GetOutputPort())
        vertices_glyph.SetScaleModeToDataScalingOff()
        vertices_glyph.SetColorModeToColorByScalar()

        vertices_mapper = vtk.vtkPolyDataMapper()
        vertices_mapper.SetInputConnection(vertices_glyph.GetOutputPort())
        vertices_mapper.SetLookupTable(LUT)

        vertices_actor = vtk.vtkActor()
        vertices_actor.SetMapper(vertices_mapper)
        vertices_actor.GetProperty().SetColor(*COLORMAP[0, :3])
        vertices_actor.PickableOff()
        vertices_actor.VisibilityOff()
        ren.AddActor(vertices_actor)

        color_faces = vtk.vtkProgrammableFilter()

        def callback_color_faces():
            input_ = color_faces.GetInput()
            output = color_faces.GetOutput()
            output.ShallowCopy(input_)

            lookup = vtk.vtkFloatArray()
            lookup.SetNumberOfValues(input_.GetNumberOfPolys())
            npy_lookup = vtk_to_numpy(lookup)

            labelled_T = self._k[self.T]
            for i in xrange(input_.GetNumberOfPolys()):
                l = np.argmax(np.bincount(labelled_T[i]))
                npy_lookup[i] = float(l) / (COLORMAP.shape[0] - 1)

            output.GetCellData().SetScalars(lookup)

        color_faces.SetExecuteMethod(callback_color_faces)

        model_mapper = vtk.vtkPolyDataMapper()
        model_mapper.SetInputConnection(color_faces.GetOutputPort())
        model_mapper.SetLookupTable(LUT)

        model_actor = vtk.vtkActor()
        model_actor.SetMapper(model_mapper)
        model_actor.GetProperty().SetColor(*COLORMAP[0, :3])
        model_actor.VisibilityOff()
        ren.AddActor(model_actor)

        render_window = vtk.vtkRenderWindow()
        render_window.AddRenderer(ren)
        render_window.SetSize(400, 400)
        self.SetRenderWindow(render_window)

        visible = vtk.vtkSelectVisiblePoints()
        visible.SetRenderer(ren)

        picker = vtk.vtkAreaPicker()

        def callback_picker(obj, event):
            props = obj.GetProp3Ds()
            if props.GetNumberOfItems() <= 0:
                return

            extract_geometry = vtk.vtkExtractGeometry()
            extract_geometry.SetImplicitFunction(picker.GetFrustum())
            extract_geometry.SetInput(visible.GetInput())
            extract_geometry.Update()

            unstructured_grid = extract_geometry.GetOutput()
            if unstructured_grid.GetPoints().GetNumberOfPoints() <= 0:
                return

            i = vtk_to_numpy(unstructured_grid.GetPointData().GetArray('i'))

            if self.select_only_visible:
                visible.Update()

                if visible.GetOutput().GetPoints().GetNumberOfPoints() <= 0:
                    return

                i = np.intersect1d(
                    i,
                    vtk_to_numpy(
                        visible.GetOutput().GetPointData().GetArray('i')))

                if i.shape[0] <= 0:
                    return

            self.set_labels(self.current_label, i)

        picker.AddObserver('EndPickEvent', callback_picker)

        iren = self.GetInteractor()
        iren.SetRenderWindow(render_window)
        iren.SetPicker(picker)

        style = vtk.vtkInteractorStyleRubberBandPick()
        style.SetCurrentRenderer(ren)
        iren.SetInteractorStyle(style)

        self.pipeline = locals()

        self.setSizePolicy(QtGui.QSizePolicy.Expanding,
                           QtGui.QSizePolicy.Expanding)
コード例 #11
0
from __future__ import print_function

import vtk
from vtk.util.misc import vtkGetTempDir
VTK_TEMP_DIR = vtkGetTempDir()

contr = vtk.vtkMultiProcessController.GetGlobalController()
if not contr:
    nranks = 1
    rank = 0
else:
    nranks = contr.GetNumberOfProcesses()
    rank = contr.GetLocalProcessId()

pf = vtk.vtkProgrammableFilter()


def execute():
    info = pf.GetOutputInformation(0)
    et = vtk.vtkExtentTranslator()
    et.SetWholeExtent(
        info.Get(vtk.vtkStreamingDemandDrivenPipeline.WHOLE_EXTENT()))
    et.SetPiece(
        info.Get(vtk.vtkStreamingDemandDrivenPipeline.UPDATE_PIECE_NUMBER()))
    et.SetNumberOfPieces(
        info.Get(
            vtk.vtkStreamingDemandDrivenPipeline.UPDATE_NUMBER_OF_PIECES()))
    et.PieceToExtent()
    output = pf.GetOutput()
    input = pf.GetInput()
    output.ShallowCopy(input)
コード例 #12
0
reader.SetFilePrefix("" + str(VTK_DATA_ROOT) + "/Data/headsq/quarter")
reader.SetDataMask(0x7fff)
reader.SetDataSpacing(1.6,1.6,1.5)
clipper = vtk.vtkImageClip()
clipper.SetInputConnection(reader.GetOutputPort())
clipper.SetOutputWholeExtent(30,36,30,36,30,36)
clipper2 = vtk.vtkImageClip()
clipper2.SetInputConnection(reader.GetOutputPort())
clipper2.SetOutputWholeExtent(30,36,30,36,30,36)
tris = vtk.vtkDataSetTriangleFilter()
tris.SetInputConnection(clipper.GetOutputPort())
tris2 = vtk.vtkDataSetTriangleFilter()
tris2.SetInputConnection(clipper2.GetOutputPort())
geom = vtk.vtkGeometryFilter()
geom.SetInputConnection(tris.GetOutputPort())
pf = vtk.vtkProgrammableFilter()
pf.SetInputConnection(tris2.GetOutputPort())
def remove_ghosts():
    input = pf.GetInput()
    output = pf.GetOutputDataObject(0)
    output.ShallowCopy(input)
    output.RemoveGhostCells()
pf.SetExecuteMethod(remove_ghosts)
edges = vtk.vtkExtractEdges()
edges.SetInputConnection(pf.GetOutputPort())
mapper1 = vtk.vtkPolyDataMapper()
mapper1.SetInputConnection(geom.GetOutputPort())
mapper1.ScalarVisibilityOn()
mapper1.SetScalarRange(0,1200)
mapper1.SetPiece(PIECE)
mapper1.SetNumberOfPieces(NUMBER_OF_PIECES)
コード例 #13
0
    def testDeciPlane(self):

        # Create the RenderWindow, Renderer and both Actors
        #
        ren1 = vtk.vtkRenderer()
        ren2 = vtk.vtkRenderer()
        ren3 = vtk.vtkRenderer()
        ren4 = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren1)
        renWin.AddRenderer(ren2)
        renWin.AddRenderer(ren3)
        renWin.AddRenderer(ren4)

        # Create the data -- a plane with a couple of bumps
        #
        plane = vtk.vtkPlaneSource()
        plane.SetXResolution(10)
        plane.SetYResolution(10)

        tf = vtk.vtkTriangleFilter()
        tf.SetInputConnection(plane.GetOutputPort())
        tf.Update()

        def adjustPointsProc():
            input = adjustPoints.GetPolyDataInput()
            inPts = input.GetPoints()
            numPts = input.GetNumberOfPoints()
            newPts = vtk.vtkPoints()
            newPts.SetNumberOfPoints(numPts)

            for i in range(0, numPts):
                newPts.SetPoint(i, inPts.GetPoint(i))

            pt = input.GetPoint(17)
            newPts.SetPoint(17, pt[0], pt[1], 0.25)
            pt = inPts.GetPoint(50)
            newPts.SetPoint(50, pt[0], pt[1], 1.0)
            pt = inPts.GetPoint(77)
            newPts.SetPoint(77, pt[0], pt[1], 0.125)

            adjustPoints.GetPolyDataOutput().CopyStructure(input)
            adjustPoints.GetPolyDataOutput().SetPoints(newPts)


        # This filter modifies the point coordinates in a couple of spots
        #
        adjustPoints = vtk.vtkProgrammableFilter()
        adjustPoints.SetInputConnection(tf.GetOutputPort())
        # The SetExecuteMethod takes a python procedure as an argument
        # In here is where all the processing is done.
        adjustPoints.SetExecuteMethod(adjustPointsProc())
        #adjustPoints.Update()

        # Now remove the extreme peak in the center
        gf = vtk.vtkGeometryFilter()
        gf.SetInputData(adjustPoints.GetPolyDataOutput())
        gf.ExtentClippingOn()
        gf.SetExtent(-100, 100, -100, 100, -1, 0.9)

        # Create a table of decimation conditions
        #
        boundaryVertexDeletion = ["On", "Off"]
        accumulates = ["On", "Off"]

        deci = dict()
        mapper = dict()
        plane = dict()

        #sz = len(boundaryVertexDeletion)
        for topology in boundaryVertexDeletion:
            for accumulate in accumulates:
        #        idx = i * sz + j
                idx = topology + accumulate
                deci.update({idx: vtk.vtkDecimatePro()})
                deci[idx].SetInputConnection(gf.GetOutputPort())
                deci[idx].SetTargetReduction(.95)
                if topology == "On":
                    deci[idx].BoundaryVertexDeletionOn()
                elif topology == "Off":
                    deci[idx].BoundaryVertexDeletionOff()
                if accumulate == "On":
                    deci[idx].AccumulateErrorOn()
                elif accumulate == "Off":
                    deci[idx].AccumulateErrorOff()
                mapper.update({idx: vtk.vtkPolyDataMapper()})
                mapper[idx].SetInputConnection(deci[idx].GetOutputPort())
                plane.update({idx: vtk.vtkActor()})
                plane[idx].SetMapper(mapper[idx])

        # Add the actors to the renderer, set the background and size
        #
        ren1.SetViewport(0, .5, .5, 1)
        ren2.SetViewport(.5, .5, 1, 1)
        ren3.SetViewport(0, 0, .5, .5)
        ren4.SetViewport(.5, 0, 1, .5)

        ren1.AddActor(plane["OnOn"])
        ren2.AddActor(plane["OnOff"])
        ren3.AddActor(plane["OffOn"])
        ren4.AddActor(plane["OffOff"])

        camera = vtk.vtkCamera()
        ren1.SetActiveCamera(camera)
        ren2.SetActiveCamera(camera)
        ren3.SetActiveCamera(camera)
        ren4.SetActiveCamera(camera)

        ren1.GetActiveCamera().SetPosition(-0.128224, 0.611836, 2.31297)
        ren1.GetActiveCamera().SetFocalPoint(0, 0, 0.125)
        ren1.GetActiveCamera().SetViewAngle(30)
        ren1.GetActiveCamera().SetViewUp(0.162675, 0.952658, -0.256864)

        ren1.SetBackground(0, 0, 0)
        ren2.SetBackground(0, 0, 0)
        ren3.SetBackground(0, 0, 0)
        ren4.SetBackground(0, 0, 0)

        renWin.SetSize(500, 500)

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()

        img_file = "deciPlane.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
コード例 #14
0
ファイル: generateProbeData.py プロジェクト: zenotech/cinema
                newArray.SetValue(idx * 3 + 2, int(value / 256 / 256))

            # if idx % progress == 0:
            #    count = count + 1
            #    print count
            #    # sys.stdout.write('.')
            #    # sys.stdout.flush()
            #    #sys. "\rProcessing %s: %d     %s" % (array.GetName(), count, "/-\\|"[count%4])

        print


# Pipeline
writer = vtkPNGWriter()
reader = vtkXMLImageDataReader()
filter = vtkProgrammableFilter()
filter.SetExecuteMethod(unfoldData)

# Loop over files to process
idx = 0
for fileName in fileNames:
    directory = outputDir + ('/%d/' % idx)

    # Make sure the destination directory exist
    if not os.path.exists(directory):
        os.makedirs(directory)

    reader.SetFileName(basePath + '/' + fileName)
    reader.Update()

    filter.SetInputData(reader.GetOutput())
コード例 #15
0
ファイル: deciPlane.py プロジェクト: 0004c/VTK
    def testDeciPlane(self):

        # Create the RenderWindow, Renderer and both Actors
        #
        ren1 = vtk.vtkRenderer()
        ren2 = vtk.vtkRenderer()
        ren3 = vtk.vtkRenderer()
        ren4 = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren1)
        renWin.AddRenderer(ren2)
        renWin.AddRenderer(ren3)
        renWin.AddRenderer(ren4)

        # Create the data -- a plane with a couple of bumps
        #
        plane = vtk.vtkPlaneSource()
        plane.SetXResolution(10)
        plane.SetYResolution(10)

        tf = vtk.vtkTriangleFilter()
        tf.SetInputConnection(plane.GetOutputPort())
        tf.Update()

        def adjustPointsProc():
            input = adjustPoints.GetPolyDataInput()
            inPts = input.GetPoints()
            numPts = input.GetNumberOfPoints()
            newPts = vtk.vtkPoints()
            newPts.SetNumberOfPoints(numPts)

            for i in range(0, numPts):
                newPts.SetPoint(i, inPts.GetPoint(i))

            pt = input.GetPoint(17)
            newPts.SetPoint(17, pt[0], pt[1], 0.25)
            pt = inPts.GetPoint(50)
            newPts.SetPoint(50, pt[0], pt[1], 1.0)
            pt = inPts.GetPoint(77)
            newPts.SetPoint(77, pt[0], pt[1], 0.125)

            adjustPoints.GetPolyDataOutput().CopyStructure(input)
            adjustPoints.GetPolyDataOutput().SetPoints(newPts)


        # This filter modifies the point coordinates in a couple of spots
        #
        adjustPoints = vtk.vtkProgrammableFilter()
        adjustPoints.SetInputConnection(tf.GetOutputPort())
        # The SetExecuteMethod takes a python procedure as an argument
        # In here is where all the processing is done.
        adjustPoints.SetExecuteMethod(adjustPointsProc())
        #adjustPoints.Update()

        # Now remove the extreme peak in the center
        gf = vtk.vtkGeometryFilter()
        gf.SetInputData(adjustPoints.GetPolyDataOutput())
        gf.ExtentClippingOn()
        gf.SetExtent(-100, 100, -100, 100, -1, 0.9)

        # Create a table of decimation conditions
        #
        boundaryVertexDeletion = ["On", "Off"]
        accumulates = ["On", "Off"]

        deci = dict()
        mapper = dict()
        plane = dict()

        #sz = len(boundaryVertexDeletion)
        for topology in boundaryVertexDeletion:
            for accumulate in accumulates:
        #        idx = i * sz + j
                idx = topology + accumulate
                deci.update({idx: vtk.vtkDecimatePro()})
                deci[idx].SetInputConnection(gf.GetOutputPort())
                deci[idx].SetTargetReduction(.95)
                if topology == "On":
                    deci[idx].BoundaryVertexDeletionOn()
                elif topology == "Off":
                    deci[idx].BoundaryVertexDeletionOff()
                if accumulate == "On":
                    deci[idx].AccumulateErrorOn()
                elif accumulate == "Off":
                    deci[idx].AccumulateErrorOff()
                mapper.update({idx: vtk.vtkPolyDataMapper()})
                mapper[idx].SetInputConnection(deci[idx].GetOutputPort())
                plane.update({idx: vtk.vtkActor()})
                plane[idx].SetMapper(mapper[idx])

        # Add the actors to the renderer, set the background and size
        #
        ren1.SetViewport(0, .5, .5, 1)
        ren2.SetViewport(.5, .5, 1, 1)
        ren3.SetViewport(0, 0, .5, .5)
        ren4.SetViewport(.5, 0, 1, .5)

        ren1.AddActor(plane["OnOn"])
        ren2.AddActor(plane["OnOff"])
        ren3.AddActor(plane["OffOn"])
        ren4.AddActor(plane["OffOff"])

        camera = vtk.vtkCamera()
        ren1.SetActiveCamera(camera)
        ren2.SetActiveCamera(camera)
        ren3.SetActiveCamera(camera)
        ren4.SetActiveCamera(camera)

        ren1.GetActiveCamera().SetPosition(-0.128224, 0.611836, 2.31297)
        ren1.GetActiveCamera().SetFocalPoint(0, 0, 0.125)
        ren1.GetActiveCamera().SetViewAngle(30)
        ren1.GetActiveCamera().SetViewUp(0.162675, 0.952658, -0.256864)

        ren1.SetBackground(0, 0, 0)
        ren2.SetBackground(0, 0, 0)
        ren3.SetBackground(0, 0, 0)
        ren4.SetBackground(0, 0, 0)

        renWin.SetSize(500, 500)

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()

        img_file = "deciPlane.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
コード例 #16
0
 def __init__(self) :
   self.Filter = vtk.vtkProgrammableFilter()
   self.Filter.SetExecuteMethod(self.ExecMethod)
コード例 #17
0
 def __init__(self):
     self.Filter = vtk.vtkProgrammableFilter()
     self.Filter.SetExecuteMethod(self.ExecMethod)
コード例 #18
0
ファイル: scenes.py プロジェクト: alexlib/PyDataNYC2015
def bessel_surface():
    """
    programmable surface
    """

    # We create a 100 by 100 point plane to sample
    plane = vtk.vtkPlaneSource()
    plane.SetXResolution(100)
    plane.SetYResolution(100)

    # We transform the plane by a factor of 10 on X and Y
    transform = vtk.vtkTransform()
    transform.Scale(10, 10, 1)
    transF = vtk.vtkTransformPolyDataFilter()
    transF.SetInputConnection(plane.GetOutputPort())
    transF.SetTransform(transform)

    # Compute Bessel function and derivatives. We'll use a programmable filter
    # for this. Note the unusual GetPolyDataInput() & GetOutputPort() methods.
    besselF = vtk.vtkProgrammableFilter()
    besselF.SetInputConnection(transF.GetOutputPort())

    # The SetExecuteMethod takes a Python function as an argument
    # In here is where all the processing is done.
    def bessel():
        inputs = besselF.GetPolyDataInput()
        numPts = inputs.GetNumberOfPoints()
        newPts = vtk.vtkPoints()
        derivs = vtk.vtkFloatArray()

        for i in xrange(0, numPts):
            x = inputs.GetPoint(i)
            x0, x1 = x[:2]

            r = sqrt(x0*x0+x1*x1)
            x2 = exp(-r)*cos(10.0*r)
            deriv = -exp(-r)*(cos(10.0*r)+10.0*sin(10.0*r))

            newPts.InsertPoint(i, x0, x1, x2)
            derivs.InsertValue(i, deriv)

        besselF.GetPolyDataOutput().CopyStructure(inputs)
        besselF.GetPolyDataOutput().SetPoints(newPts)
        besselF.GetPolyDataOutput().GetPointData().SetScalars(derivs)

    besselF.SetExecuteMethod(bessel)

    # We warp the plane based on the scalar values calculated above
    warp = vtk.vtkWarpScalar()
    warp.SetInputConnection(besselF.GetOutputPort())
    warp.XYPlaneOn()
    warp.SetScaleFactor(0.5)

    # We create a mapper and actor as usual. In the case we adjust the
    # scalar range of the mapper to match that of the computed scalars
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(warp.GetOutputPort())
    mapper.SetScalarRange(besselF.GetPolyDataOutput().GetScalarRange())
    carpet = vtk.vtkActor()
    carpet.SetMapper(mapper)

    return carpet
コード例 #19
0
    def __init__(self, module_manager):
        # initialise our base class
        ModuleBase.__init__(self, module_manager)
        # initialise any mixins we might have
        NoConfigModuleMixin.__init__(self)


        self._distance = vtk.vtkImageEuclideanDistance()
        # this seems to yield more accurate results in this case
        # it would probably be better to calculate only 2d distance fields
        self._distance.ConsiderAnisotropyOff()

        self._xEndPoints = []
        self._noFlipXes = []
        self._pf1 = vtk.vtkProgrammableFilter() # yeah
        self._pf1.SetInput(self._distance.GetOutput())
        self._pf1.SetExecuteMethod(self.pf1Execute)

        self._pf2 = vtk.vtkProgrammableFilter()
        self._pf2.SetInput(self._pf1.GetOutput())
        self._pf2.SetExecuteMethod(self.pf2Execute)

        self._mc = vtk.vtkMarchingCubes()
        self._mc.SetInput(self._pf1.GetOutput())
        self._mc.SetValue(0,0.1)

        self._iv = vtk.vtkImplicitVolume()
        self._iv.SetVolume(self._pf2.GetOutput())

        self._cpd = vtk.vtkClipPolyData()
        self._cpd.SetClipFunction(self._iv)
        self._cpd.SetInput(self._mc.GetOutput())
        #self._cpd.InsideOutOn()

        module_utils.setup_vtk_object_progress(self, self._distance,
                                           'Calculating distance field...')
        module_utils.setup_vtk_object_progress(self, self._pf1,
                                           'Signing distance field...')
        module_utils.setup_vtk_object_progress(self, self._pf2,
                                           'Creating implicit volume...')
        module_utils.setup_vtk_object_progress(self, self._mc,
                                           'Extracting isosurface...')
        module_utils.setup_vtk_object_progress(self, self._cpd,
                                           'Clipping isosurface...')
        
        
        
        

        self._iObj = self._distance
        self._oObj = self._cpd
        #self._oObj = self._pf2
        
        self._viewFrame = self._createViewFrame({'distance' :
                                                 self._distance,
                                                 'pf1' :
                                                 self._pf1,
                                                 'pf2' :
                                                 self._pf2,
                                                 'mc' :
                                                 self._mc,
                                                 'cpd' :
                                                 self._cpd})
コード例 #20
0
ファイル: Terrain.py プロジェクト: GearsAD/semisorted_arnerve
    def __init__(self, renderer, surfaceSize):
        '''
        Initialize the terrain. This is derived from the expCos.py example on the vtk.org website, link is above.
        '''
        # Call the parent constructor
        super(Terrain,self).__init__(renderer)
                
        # We create a 'surfaceSize' by 'surfaceSize' point plane to sample
        plane = vtk.vtkPlaneSource()
        plane.SetXResolution(surfaceSize)
        plane.SetYResolution(surfaceSize)
        
        # We transform the plane by a factor of 'surfaceSize' on X and Y
        transform = vtk.vtkTransform()
        transform.Scale(surfaceSize, surfaceSize, 1)
        transF = vtk.vtkTransformPolyDataFilter()
        transF.SetInputConnection(plane.GetOutputPort())
        transF.SetTransform(transform)
        
        # Compute the function that we use for the height generation. 
        # [Original comment] Note the unusual GetPolyDataInput() & GetOutputPort() methods.
        surfaceF = vtk.vtkProgrammableFilter()
        surfaceF.SetInputConnection(transF.GetOutputPort())
        
        # [Original comment] The SetExecuteMethod takes a Python function as an argument
        # In here is where all the processing is done.
        def bessel():
            input = surfaceF.GetPolyDataInput()
            numPts = input.GetNumberOfPoints()
            newPts = vtk.vtkPoints()
            derivs = vtk.vtkFloatArray()
        
            for i in range(0, numPts):
                x = input.GetPoint(i) 
                x, z = x[:2] # Get the XY plane point, which we'll make an XZ plane point so that's it a ground surface - this is a convenient point to remap it...
        
                # Now do your surface construction here, which we'll just make an arbitrary wavy surface for now.
                y = sin(x / float(surfaceSize) * 6.282) * cos(z / float(surfaceSize) * 6.282)
        
                newPts.InsertPoint(i, x, y, z)
                derivs.InsertValue(i, y)
        
            surfaceF.GetPolyDataOutput().CopyStructure(input)
            surfaceF.GetPolyDataOutput().SetPoints(newPts)
            surfaceF.GetPolyDataOutput().GetPointData().SetScalars(derivs)
        
        surfaceF.SetExecuteMethod(bessel)
        
        
        # We warp the plane based on the scalar values calculated above
        warp = vtk.vtkWarpScalar()
        warp.SetInputConnection(surfaceF.GetOutputPort())
        warp.XYPlaneOn()

        # Set the range of the colour mapper to the function min/max we used to generate the terrain.
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(warp.GetOutputPort())
        mapper.SetScalarRange(-1, 1)

        # Make our terrain wireframe so that it doesn't occlude the whole scene
        self.vtkActor.GetProperty().SetRepresentationToWireframe()
        
        # Finally assign this to the parent class actor so that it draws.
        self.vtkActor.SetMapper(mapper)
        
        # [HACK] Got tired of picking terrain [Alucard]
        self.vtkActor.PickableOff()
            
コード例 #21
0
#!/Users/seb/Work/code/ParaView/build/bin/pvpython

import sys
from vtk import vtkMetaImageReader, vtkProgrammableFilter, vtkUnsignedCharArray, vtkJPEGWriter, vtkPNGWriter

basePath = '/Users/seb/Work/projects/NE-Phase2/'

reader = vtkMetaImageReader()
reader.SetFileName("/Users/seb/Work/projects/NE-Phase2/Patient05.mha")
reader.Update()

writer = vtkJPEGWriter() # vtkJPEGWriter()

filter = vtkProgrammableFilter()

def unfoldData():
   inputDS = filter.GetInputDataObject(0, 0)
   outputDS = filter.GetImageDataOutput()

   dims = inputDS.GetDimensions()

   # dims[1] * dims[2]
   nbSlices = (dims[1] * dims[2]) / 2048
   outputDS.SetDimensions(dims[0], dims[1] * dims[2] / nbSlices, nbSlices)
   outputDS.SetOrigin(0,0,0)
   outputDS.SetSpacing(1,1,1)

   for arrayIdx in range(inputDS.GetPointData().GetNumberOfArrays()):
      array = inputDS.GetPointData().GetArray(arrayIdx)

      size = dims[0] * dims[1] * dims[2]
コード例 #22
0
ファイル: expCos.py プロジェクト: Armand0s/homemade_vtk
# We create a 100 by 100 point plane to sample
plane = vtk.vtkPlaneSource()
plane.SetXResolution(100)
plane.SetYResolution(100)

# We transform the plane by a factor of 10 on X and Y
transform = vtk.vtkTransform()
transform.Scale(10, 10, 1)
transF = vtk.vtkTransformPolyDataFilter()
transF.SetInputConnection(plane.GetOutputPort())
transF.SetTransform(transform)

# Compute Bessel function and derivatives. We'll use a programmable filter
# for this. Note the unusual GetPolyDataInput() & GetOutputPort() methods.
besselF = vtk.vtkProgrammableFilter()
besselF.SetInputConnection(transF.GetOutputPort())

# The SetExecuteMethod takes a Python function as an argument
# In here is where all the processing is done.
def bessel():
    input = besselF.GetPolyDataInput()
    numPts = input.GetNumberOfPoints()
    newPts = vtk.vtkPoints()
    derivs = vtk.vtkFloatArray()

    for i in range(0, numPts):
        x = input.GetPoint(i)
        x0, x1 = x[:2]

        r = sqrt(x0*x0+x1*x1)