示例#1
0
def main(cases):
    """ Pass a list of tuples containing test classes and the starting
    string of the functions used for testing.

    Example:

    main ([(vtkTestClass, 'test'), (vtkTestClass1, 'test')])
    """

    processCmdLine()

    timer = vtk.vtkTimerLog()
    s_time = timer.GetCPUTime()
    s_wall_time = time.time()    

    # run the tests
    result = test(cases)

    tot_time = timer.GetCPUTime() - s_time
    tot_wall_time = float(time.time() - s_wall_time)

    # output measurements for Dart
    print "<DartMeasurement name=\"WallTime\" type=\"numeric/double\">",
    print " %f </DartMeasurement>"%tot_wall_time
    print "<DartMeasurement name=\"CPUTime\" type=\"numeric/double\">",
    print " %f </DartMeasurement>"%tot_time

    # Delete these to eliminate debug leaks warnings.
    del cases, timer
    
    if result.wasSuccessful():
        sys.exit(0)
    else:
        sys.exit(1)
示例#2
0
文件: Testing.py 项目: neuzhong/VTK
def main(cases):
    """ Pass a list of tuples containing test classes and the starting
    string of the functions used for testing.

    Example:

    main ([(vtkTestClass, 'test'), (vtkTestClass1, 'test')])
    """

    processCmdLine()

    timer = vtk.vtkTimerLog()
    s_time = timer.GetCPUTime()
    s_wall_time = time.time()

    # run the tests
    result = test(cases)

    tot_time = timer.GetCPUTime() - s_time
    tot_wall_time = float(time.time() - s_wall_time)

    # output measurements for CDash
    print("<DartMeasurement name=\"WallTime\" type=\"numeric/double\"> "
          " %f </DartMeasurement>"%tot_wall_time)
    print("<DartMeasurement name=\"CPUTime\" type=\"numeric/double\"> "
          " %f </DartMeasurement>"%tot_time)

    # Delete these to eliminate debug leaks warnings.
    del cases, timer

    if result.wasSuccessful():
        sys.exit(0)
    else:
        sys.exit(1)
def showPointCloud(modelNodeID):

    model = slicer.mrmlScene.GetNodeByID(modelNodeID)
    polydata = model.GetPolyData()

    # Reuse the locator
    locator = vtk.vtkStaticPointLocator()
    locator.SetDataSet(polydata)
    locator.BuildLocator()

    # Remove isolated points
    removal = vtk.vtkRadiusOutlierRemoval()
    removal.SetInputData(polydata)
    removal.SetLocator(locator)
    removal.SetRadius(10)
    removal.SetNumberOfNeighbors(2)
    removal.GenerateOutliersOn()

    # Time execution
    timer = vtk.vtkTimerLog()
    timer.StartTimer()
    removal.Update()
    timer.StopTimer()
    time = timer.GetElapsedTime()
    print("Time to remove points: {0}".format(time))
    print("   Number removed: {0}".format(removal.GetNumberOfPointsRemoved()),
          " (out of: {}".format(polydata.GetNumberOfPoints()))

    # First output are the non-outliers
    remMapper = vtk.vtkPointGaussianMapper()
    remMapper.SetInputConnection(removal.GetOutputPort())
    remMapper.EmissiveOff()
    remMapper.SetScaleFactor(0.0)

    remActor = vtk.vtkActor()
    remActor.SetMapper(remMapper)

    lm = slicer.app.layoutManager()
    tdWidget = lm.threeDWidget(0)
    tdView = tdWidget.threeDView()
    rWin = tdView.renderWindow()
    rCollection = rWin.GetRenderers()
    renderer = rCollection.GetItemAsObject(0)

    # Add the actors to the renderer, set the background and size
    #
    renderer.AddActor(remActor)
def showPointCloud(modelNodeID):

    model = slicer.mrmlScene.GetNodeByID(modelNodeID)
    polydata = model.GetPolyData()

    # Reuse the locator
    locator = vtk.vtkStaticPointLocator()
    locator.SetDataSet(polydata)
    locator.BuildLocator()

    # Remove isolated points
    removal = vtk.vtkRadiusOutlierRemoval()
    removal.SetInputData(polydata)
    removal.SetLocator(locator)
    removal.SetRadius(10)
    removal.SetNumberOfNeighbors(2)
    removal.GenerateOutliersOn()

    # Time execution
    timer = vtk.vtkTimerLog()
    timer.StartTimer()
    removal.Update()
    timer.StopTimer()
    time = timer.GetElapsedTime()
    print("Time to remove points: {0}".format(time))
    print("   Number removed: {0}".format(removal.GetNumberOfPointsRemoved()),
          " (out of: {}".format(polydata.GetNumberOfPoints()))

    # First output are the non-outliers
    remMapper = vtk.vtkPointGaussianMapper()
    remMapper.SetInputConnection(removal.GetOutputPort())
    remMapper.EmissiveOff()
    remMapper.SetScaleFactor(0.0)

    remActor = vtk.vtkActor()
    remActor.SetMapper(remMapper)
    
    lm = slicer.app.layoutManager()
    tdWidget = lm.threeDWidget(0)
    tdView = tdWidget.threeDView()
    rWin = tdView.renderWindow()
    rCollection = rWin.GetRenderers()
    renderer = rCollection.GetItemAsObject(0)

    # Add the actors to the renderer, set the background and size
    #
    renderer.AddActor(remActor)
closest = vtk.vtkIdList()
closest.SetNumberOfIds(numProbes)
staticClosest = vtk.vtkIdList()
staticClosest.SetNumberOfIds(numProbes)

# Print initial statistics
print("Processing NumPts: {0}".format(numPts))
print("\n")

# Time the creation and building of the incremental point locator
locator = vtk.vtkPointLocator()
locator.SetDataSet(polydata)
locator.SetNumberOfPointsPerBucket(5)
locator.AutomaticOn()

timer = vtk.vtkTimerLog()
timer.StartTimer()
locator.BuildLocator()
timer.StopTimer()
time = timer.GetElapsedTime()
print("Build Point Locator: {0}".format(time))

# Probe the dataset with FindClosestPoint() and time it
timer.StartTimer()
for i in range (0,numProbes):
    closest.SetId(i, locator.FindClosestPoint(probePoints.GetPoint(i)))
timer.StopTimer()
opTime = timer.GetElapsedTime()
print("    Closest point probing: {0}".format(opTime))
print("    Divisions: {0}".format( locator.GetDivisions() ))
dist = vtk.vtkUnsignedDistance()
dist.SetInputData(polyData)
dist.SetRadius(0.25) #how far out to propagate distance calculation
dist.SetDimensions(res,res,res)
dist.CappingOn()
dist.AdjustBoundsOn()
dist.SetAdjustDistance(0.01)

# Extract the surface with modified flying edges
fe = vtk.vtkFlyingEdges3D()
fe.SetInputConnection(dist.GetOutputPort())
fe.SetValue(0, 0.075)
fe.ComputeNormalsOff()

# Time the execution
timer = vtk.vtkTimerLog()
timer.StartTimer()
fe.Update()
timer.StopTimer()
time = timer.GetElapsedTime()
print("Points processed: {0}".format(NPts))
print("   Time to generate and extract distance function: {0}".format(time))
print(dist)

feMapper = vtk.vtkPolyDataMapper()
feMapper.SetInputConnection(fe.GetOutputPort())

feActor = vtk.vtkActor()
feActor.SetMapper(feMapper)

# Create an outline
示例#7
0
# Compare against standard contouring
contour4 = vtk.vtkContourFilter()
contour4.SetInputConnection(extract.GetOutputPort())
contour4.SetValue(0, 0.5)
contour4.SetValue(1, 0.75)

cont4Mapper = vtk.vtkPolyDataMapper()
cont4Mapper.SetInputConnection(contour4.GetOutputPort())
cont4Mapper.ScalarVisibilityOff()

cont4Actor = vtk.vtkActor()
cont4Actor.SetMapper(cont4Mapper)
cont4Actor.GetProperty().SetColor(.8, .4, .4)

# Timing comparisons
timer = vtk.vtkTimerLog()

timer.StartTimer()
stree.BuildTree()
timer.StopTimer()
streetime = timer.GetElapsedTime()

timer.StartTimer()
contour.Update()
timer.StopTimer()
time = timer.GetElapsedTime()

timer.StartTimer()
contourST.Update()
timer.StopTimer()
timeST = timer.GetElapsedTime()
示例#8
0
 def __init__(self, renderer):
     self._renderer = renderer
     self._timerLog = vtkTimerLog()
     self._numberOfTrials = 10
示例#9
0
    def examine(self, fileLists):
        """ Returns a list of DICOMLoadable instances
    corresponding to ways of interpreting the
    fileLists parameter.

    Top-level examine() calls various individual strategies implemented in examineFiles*().
    """

        self.detailedLogging = settingsValue('DICOM/detailedLogging',
                                             False,
                                             converter=toBool)
        timer = vtk.vtkTimerLog()
        timer.StartTimer()

        loadables = []
        allfiles = []
        for files in fileLists:
            loadables += self.examineFiles(files)

            # this strategy sorts the files into groups
            loadables += self.examineFilesIPPAcqTime(files)

            allfiles += files

        # here all files are lumped into one list for the situations when
        # individual frames should be parsed from series
        loadables += self.examineFilesMultiseries(allfiles)
        if len(allfiles) > len(files):
            # only examineFilesIPPAcqTime again if there are multiple file groups
            loadables += self.examineFilesIPPAcqTime(allfiles)

        # this strategy sorts the files into groups
        loadables += self.examineFilesIPPInstanceNumber(allfiles)

        # If Sequences module is available then duplicate all the loadables
        # for loading them as volume sequence.
        # A slightly higher confidence value is set for volume sequence loadables,
        # therefore by default data will be loaded as volume sequence.

        if hasattr(slicer.modules, 'sequences'):

            seqLoadables = []
            for loadable in loadables:
                seqLoadable = DICOMLib.DICOMLoadable()
                seqLoadable.files = loadable.files
                seqLoadable.tooltip = loadable.tooltip.replace(
                    ' frames MultiVolume by ', ' frames Volume Sequence by ')
                seqLoadable.name = loadable.name.replace(
                    ' frames MultiVolume by ', ' frames Volume Sequence by ')
                seqLoadable.multivolume = loadable.multivolume
                seqLoadable.selected = loadable.selected

                seqLoadable.confidence = loadable.confidence

                seqLoadable.loadAsVolumeSequence = True
                seqLoadables.append(seqLoadable)

            # Among all selected loadables, the ones that are listed first will be selected by default,
            # therefore we need to prepend loadables if sequence format is preferred.
            # Determine from settings loading into sequence node should have higher confidence (selected by default).
            settings = qt.QSettings()
            sequenceFormatPreferred = (settings.value(
                "DICOM/PreferredMultiVolumeImportFormat",
                "default") == "sequence")
            if sequenceFormatPreferred:
                # prepend
                loadables[0:0] = seqLoadables
            else:
                # append
                loadables += seqLoadables

        timer.StopTimer()
        if self.detailedLogging:
            logging.debug(
                f"MultiVolumeImporterPlugin: found {len(loadables)} loadables in {len(allfiles)} files in {timer.GetElapsedTime():.1f}sec."
            )

        return loadables
示例#10
0
closest = vtk.vtkIdList()
closest.SetNumberOfIds(numProbes)
staticClosest = vtk.vtkIdList()
staticClosest.SetNumberOfIds(numProbes)

# Print initial statistics
print("Processing NumPts: {0}".format(numPts))
print("\n")

# Time the creation and building of the incremental point locator
locator = vtk.vtkPointLocator()
locator.SetDataSet(polydata)
locator.SetNumberOfPointsPerBucket(5)
locator.AutomaticOn()

timer = vtk.vtkTimerLog()
timer.StartTimer()
locator.BuildLocator()
timer.StopTimer()
time = timer.GetElapsedTime()
print("Build Point Locator: {0}".format(time))

# Probe the dataset with FindClosestPoint() and time it
timer.StartTimer()
for i in range (0,numProbes):
    closest.SetId(i, locator.FindClosestPoint(probePoints.GetPoint(i)))
timer.StopTimer()
opTime = timer.GetElapsedTime()
print("    Closest point probing: {0}".format(opTime))
print("    Divisions: {0}".format( locator.GetDivisions() ))
示例#11
0
def main(argc, argv):
    if (argc != 7):
        print("Usage: " + argv[0] + " Theta Phi MaximumPeels " +
              "OcclusionRatio ForceDepthSortingFlag " +
              "DoNotUseAnyDepthRelatedAlgorithmFlag" + "\n")
        print("100 100 50 0.1 0 0")
        return -1

    colors = vtk.vtkNamedColors()

    theta = int(argv[1])
    phi = int(argv[2])
    maxPeels = int(argv[3])
    occulusionRatio = float(argv[4])
    forceDepthSort = int(argv[5]) == 1
    withoutAnyDepthThings = (argv[6]) == 1

    # Generate a translucent sphere poly data set that partially overlaps:
    translucentGeometry = GenerateOverlappingBunchOfSpheres(theta, phi)

    # generate a basic Mapper and Actor
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(translucentGeometry.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetOpacity(0.5)  # translucent !!!
    actor.GetProperty().SetColor(colors.GetColor3d("Crimson"))
    actor.RotateX(-72)  # put the objects in a position where it is easy to see
    # different overlapping regions

    # Create the RenderWindow, Renderer and RenderWindowInteractor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(600, 400)
    renderWindow.AddRenderer(renderer)
    renderWindow.SetWindowName("CorrectlyRenderTranslucentGeometry")

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add the actors to the renderer, set the background and size
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("SlateGray"))

    # Setup view geometry
    renderer.ResetCamera()
    renderer.GetActiveCamera().Zoom(2.2)  # so the object is larger
    renderWindow.Render()

    # Answer the key question: Does this box support GPU Depth Peeling?
    useDepthPeeling = IsDepthPeelingSupported(renderWindow, renderer, True)
    print("DEPTH PEELING SUPPORT: " + {1: "YES", 0: "NO"}[useDepthPeeling])

    success = 0

    # Use depth peeling if available and not explicitly prohibited, otherwise we
    # use manual depth sorting
    print("\n" + "CHOSEN MODE: ")
    if (useDepthPeeling and ~forceDepthSort and ~withoutAnyDepthThings):  # GPU
        print("*** DEPTH PEELING ***")
        # Setup GPU depth peeling with configured parameters
        success = ~SetupEnvironmentForDepthPeeling(renderWindow, renderer,
                                                   maxPeels, occulusionRatio)
    elif (~withoutAnyDepthThings):
        print("*** DEPTH SORTING ***")
        # Setup CPU depth sorting filter
        depthSort = vtk.vtkDepthSortPolyData()
        depthSort.SetInputConnection(translucentGeometry.GetOutputPort())
        depthSort.SetDirectionToBackToFront()
        depthSort.SetVector(1, 1, 1)
        depthSort.SetCamera(renderer.GetActiveCamera())
        depthSort.SortScalarsOff()  # do not really need this here
        # Bring it to the mapper's input
        mapper.SetInputConnection(depthSort.GetOutputPort())
        depthSort.Update()
    else:
        print("*** NEITHER DEPTH PEELING NOR DEPTH SORTING ***")

    # Initialize interaction
    renderWindowInteractor.Initialize()

    # Check the average frame rate when rotating the actor
    endCount = 100
    clock = vtk.vtkTimerLog()
    # Set a user transform for successively rotating the camera position
    transform = vtk.vtkTransform()
    transform.Identity()
    transform.RotateY(2.0)  # rotate 2 degrees around Y-axis at each iteration
    camera = renderer.GetActiveCamera()
    # Start test
    clock.StartTimer()
    for i in range(endCount):
        camPos = camera.GetPosition()
        camPos = transform.TransformPoint(camPos)
        camera.SetPosition(camPos)
        renderWindow.Render()
    clock.StopTimer()
    frameRate = endCount / clock.GetElapsedTime()
    print("AVERAGE FRAME RATE: " + str(frameRate) + " fps")

    # Start interaction
    renderWindowInteractor.Start()

    return success