示例#1
0
    def plot(self, struct):

        # creates self. data1, legend, filename, fieldname, dim, has_field, tracker, revision
        if not self.call_config(struct):
            return

        # creates self.src
        if not self.call_src():
            return

        self.bounds = self.src.GetOutput().GetBounds()

        # si es cell data, lo transforma a point data, porque vtkWarpScalar parece ser que no soporta cell data.
        if self.data1.get('fielddomain') == 'cell':
            self.cdtpd = vtk.vtkCellDataToPointData()
            self.cdtpd.SetInputConnection(self.src.GetOutputPort())
            self.warpT = vtk.vtkWarpScalar()
            self.warpT.SetInputConnection(self.cdtpd.GetOutputPort())
        else:
            self.warpT = vtk.vtkWarpScalar()
            self.warpT.SetInputConnection(self.src.GetOutputPort())

        self.wireM2 = vtk.vtkDataSetMapper()
        self.wireM2.SetInputConnection(self.warpT.GetOutputPort())

        #self.wireM2.SetScalarRange(self.cdtpd.GetOutput().GetScalarRange())

        # reverse rainbow [red->blue] -> [blue->red]
        self.look = self.wireM2.GetLookupTable()

        #        self.wireM2.ScalarVisibilityOff()

        self.wireA2 = vtk.vtkActor()
        self.wireA2.SetMapper(self.wireM2)
        self.wireA2.GetProperty().SetRepresentationToSurface()
        self.wireA2.GetProperty().SetColor(Plot.edges_color)

        self.add_sw_2(self.wireA2)
        self.add_opacity_2([self.wireA2])  # Opacity: 100%/75%/50%/25%/0%
        self.rens[0].AddActor(self.wireA2)

        self.maxrange = self.src.GetOutput().GetScalarRange()[1]

        self.copy_params(struct)

        self.warpT.Update()
        #        self.add_outline_2(self.src)
        self.add_outline_2(self.warpT)

        self.scalarrange.local_set(self.src.GetOutput().GetScalarRange())

        self.add_scalarbar_2(self.look)

        self.done = True
示例#2
0
    def Domain(self, dim, opacity=0.2, lut=None, warp=False):
        """Create domain or faces."""
        domain = vtk.vtkGeometryFilter()
        domain.SetInput(self.vtkgrid[dim])
        domain.Update()
        mapper = vtk.vtkPolyDataMapper()
        if warp:
            warp = vtk.vtkWarpScalar()
            warp.SetInput(domain.GetOutput())
            warp.SetScaleFactor(1/2.0/self.vmax)
            mapper.SetInput(warp.GetOutput())
        else:
            normals = vtk.vtkPolyDataNormals()
            normals.SetInput(domain.GetOutput())
            mapper.SetInput(normals.GetOutput())

        if lut is None:
            lut = self.lut
        if self.dim == 3:
            mapper.SetLookupTable(self.lut)
            mapper.SetScalarRange(self.vmin, self.vmax)
        else:
            mapper.SetLookupTable(self.lut)
            mapper.SetScalarRange(self.vmin, self.vmax)
        if dim == 0:
            mapper.SetLookupTable(self.blue)
            mapper.SetScalarRange(0.0, 1.0)
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        if not self.color and self.dim == 2:
            opacity = 1-(1-opacity)/2.0
        actor.GetProperty().SetOpacity(opacity)
        return actor
示例#3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkWarpScalar(), 'Processing.',
         ('vtkPointSet',), ('vtkPointSet',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
示例#4
0
def create_warp_scalar(probe_filter):
    """take a probe_filter and generate a warp scalar for warp delaunay"""

    warp_scalar = vtk.vtkWarpScalar()
    warp_scalar.SetInputConnection(probe_filter.GetOutputPort())
    warp_scalar.Update()

    return warp_scalar
示例#5
0
def createWarpPolyData(image, scale=1.0):
    geometry = vtk.vtkImageDataGeometryFilter()
    geometry.SetInput(image)
    warp = vtk.vtkWarpScalar()
    warp.SetInput(geometry.GetOutput())
    warp.SetScaleFactor(scale)
    warp.Update()
    return warp.GetOutput()
示例#6
0
文件: filters.py 项目: paralab/GRVis
def WarpByScalar(source, varName, scaleFactor=10.0):
    warpByScalar = vtk.vtkWarpScalar()
    warpByScalar.SetInputConnection(source.GetOutputPort())
    warpByScalar.SetScaleFactor(scaleFactor)
    #use the scalars themselves
    warpByScalar.UseNormalOn()
    warpByScalar.SetNormal(0, 0, 1)
    warpByScalar.Update()
    return warpByScalar
示例#7
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkWarpScalar(),
                                       'Processing.', ('vtkPointSet', ),
                                       ('vtkPointSet', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
示例#8
0
def render_image(png_reader):
    square = 8
    color_map = vtk.vtkLookupTable()
    color_map.SetNumberOfColors(16)
    color_map.SetHueRange(0, 0.667)

    magnitude = vtk.vtkImageMagnitude()
    magnitude.SetInput(png_reader.GetOutput())

    geometry = vtk.vtkImageDataGeometryFilter()
    geometry.SetInput(magnitude.GetOutput())

    warp = vtk.vtkWarpScalar()
    warp.SetInput(geometry.GetOutput())
    warp.SetScaleFactor(0.25)

    merge = vtk.vtkMergeFilter()
    merge.SetGeometry(warp.GetOutput())
    merge.SetScalars(png_reader.GetOutput())

    elevation_mtHood = vtk.vtkElevationFilter()
    elevation_mtHood.SetInput(merge.GetOutput())
    elevation_mtHood.SetLowPoint(0, 0, 0)
    elevation_mtHood.SetHighPoint(0, 0, 50)

    mapper_3D_mtHood = vtk.vtkDataSetMapper()
    mapper_3D_mtHood.SetInput(elevation_mtHood.GetOutput())
    mapper_3D_mtHood.SetLookupTable(color_map)

    mapper_2D_mtHood = vtk.vtkPolyDataMapper2D()
    mapper_2D_mtHood.SetInput(elevation_mtHood.GetOutput())
    mapper_2D_mtHood.SetLookupTable(color_map)
    
    actor_2D_mtHood = vtk.vtkActor2D()
    actor_2D_mtHood.SetMapper(mapper_2D_mtHood)
    actor_2D_mtHood.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
    actor_2D_mtHood.GetPositionCoordinate().SetValue(0.25,0.25)
    
    actor_3D_mtHood = vtk.vtkActor()
    actor_3D_mtHood.SetMapper(mapper_3D_mtHood)


    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor_3D_mtHood)
    renderer.SetBackground(.5, .5, .5)

    renderWindow.SetSize(600, 600)
    renderWindow.Render()
    renderWindowInteractor.Start()
def render_image(png_reader):
    colorLookup = vtk.vtkLookupTable()
    colorLookup.SetNumberOfColors(256)
    colorLookup.SetTableRange(0, 255)
    for ii in range(0, 256):
        colorLookup.SetTableValue(ii, 0, 0, 0, 1)

    magnitude = vtk.vtkImageMagnitude()
    magnitude.SetInput(png_reader.GetOutput())

    geometry = vtk.vtkImageDataGeometryFilter()
    geometry.SetInput(magnitude.GetOutput())

    warp = vtk.vtkWarpScalar()
    warp.SetInput(geometry.GetOutput())
    warp.SetScaleFactor(0.25)

    merge = vtk.vtkMergeFilter()
    merge.SetGeometry(warp.GetOutput())
    merge.SetGeometry(warp.GetOutput())
    merge.SetScalars(png_reader.GetOutput())

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInput(merge.GetOutput())
    mapper.ScalarVisibilityOn()
    mapper.SetLookupTable(colorLookup)
    # mapper.SetScalarRange(0,255)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.SetBackground(0.5, 0.5, 0.5)

    renderWindow.SetSize(600, 600)
    renderWindow.Render()
    renderWindowInteractor.Start()
def render_image(png_reader):
    colorLookup = vtk.vtkLookupTable()
    colorLookup.SetNumberOfColors(256)
    colorLookup.SetTableRange(0, 255)
    for ii in range(0, 256):
        colorLookup.SetTableValue(ii, 0, 0, 0, 1)

    magnitude = vtk.vtkImageMagnitude()
    magnitude.SetInput(png_reader.GetOutput())

    geometry = vtk.vtkImageDataGeometryFilter()
    geometry.SetInput(magnitude.GetOutput())

    warp = vtk.vtkWarpScalar()
    warp.SetInput(geometry.GetOutput())
    warp.SetScaleFactor(0.25)

    merge = vtk.vtkMergeFilter()
    merge.SetGeometry(warp.GetOutput())
    merge.SetGeometry(warp.GetOutput())
    merge.SetScalars(png_reader.GetOutput())

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInput(merge.GetOutput())
    mapper.ScalarVisibilityOn()
    mapper.SetLookupTable(colorLookup)
    #mapper.SetScalarRange(0,255)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    renderer.SetBackground(.5, .5, .5)

    renderWindow.SetSize(600, 600)
    renderWindow.Render()
    renderWindowInteractor.Start()
示例#11
0
    def warp_by_scalar(dataset, scalars=None, scale_factor=1.0, normal=None,
                       in_place=False):
        """
        Warp the dataset's points by a point data scalar array's values.
        This modifies point coordinates by moving points along point normals by
        the scalar amount times the scale factor.

        Parameters
        ----------
        scalars : str, optional
            Name of scalars to warb by. Defaults to currently active scalars.

        scale_factor : float, optional
            A scalaing factor to increase the scaling effect

        normal : np.array, list, tuple of length 3
            User specified normal. If given, data normals will be ignored and
            the given normal will be used to project the warp.

        in_place : bool
            If True, the points of the give dataset will be updated.
        """
        if scalars is None:
            field, scalars = dataset.active_scalar_info
        arr, field = get_scalar(dataset, scalars, preference='point', info=True)
        if field != vtki.POINT_DATA_FIELD:
            raise AssertionError('Dataset can only by warped by a point data array.')
        # Run the algorithm
        alg = vtk.vtkWarpScalar()
        alg.SetInputDataObject(dataset)
        alg.SetInputArrayToProcess(0, 0, 0, field, scalars) # args: (idx, port, connection, field, name)
        alg.SetScaleFactor(scale_factor)
        if normal is not None:
            alg.SetNormal(normal)
            alg.SetUseNormal(True)
        alg.Update()
        output = _get_output(alg)
        if in_place:
            dataset.points = output.points
            return
        return output
示例#12
0
    def __init__(self, parent, visualizer, **kws):
        """
		Initialization
		"""
        VisualizationModule.__init__(self, parent, visualizer, **kws)

        self.descs = {
            "Normals": "Smooth surface with normals",
            "FeatureAngle": "Feature angle of normals",
            "Slice": "Select slice to be warped",
            "Scale": "Scale factor for warping"
        }

        self.luminance = vtk.vtkImageLuminance()

        #DataGeometry filter, image to polygons
        self.geometry = vtk.vtkImageDataGeometryFilter()

        self.colorMapper = None
        #warp scalars!
        self.warp = vtk.vtkWarpScalar()
        self.warp.SetScaleFactor(-0.1)

        #merge image and new warped data
        self.merge = vtk.vtkMergeFilter()

        self.normals = vtk.vtkPolyDataNormals()
        self.normals.SetFeatureAngle(90)
        #first the mapper
        self.mapper = vtk.vtkPolyDataMapper()

        #make the actor from the mapper
        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)

        self.renderer = self.parent.getRenderer()
        self.renderer.AddActor(self.actor)

        #        iactor = self.wxrenwin.GetRenderWindow().GetInteractor()
        self.filterDesc = "Visualize 2D slice as 3D map"
	def __init__(self, parent, visualizer, **kws):
		"""
		Initialization
		"""     
		VisualizationModule.__init__(self, parent, visualizer, **kws)   

		self.descs = {"Normals": "Smooth surface with normals", "FeatureAngle": "Feature angle of normals",
		"Slice": "Select slice to be warped", "Scale": "Scale factor for warping"}

		self.luminance = vtk.vtkImageLuminance()
		
		#DataGeometry filter, image to polygons
		self.geometry = vtk.vtkImageDataGeometryFilter()
		
		self.colorMapper = None
		#warp scalars!
		self.warp = vtk.vtkWarpScalar()
		self.warp.SetScaleFactor(-0.1)
		
		#merge image and new warped data
		self.merge = vtk.vtkMergeFilter()
		
		self.normals = vtk.vtkPolyDataNormals()        
		self.normals.SetFeatureAngle (90)
		#first the mapper
		self.mapper = vtk.vtkPolyDataMapper()
		
		#make the actor from the mapper
		self.actor = vtk.vtkActor()
		self.actor.SetMapper(self.mapper)

		self.renderer = self.parent.getRenderer()
		self.renderer.AddActor(self.actor)

#        iactor = self.wxrenwin.GetRenderWindow().GetInteractor()
		self.filterDesc = "Visualize 2D slice as 3D map"
示例#14
0
def main():
    fileName = get_program_parameters()

    colors = vtk.vtkNamedColors()
    # Set the background color. Match those in VTKTextbook.pdf.
    bkg = map(lambda x: x / 256.0, [60, 93, 144])
    colors.SetColor("BkgColor", *bkg)

    # Read in an image and compute a luminance value. The image is extracted
    # as a set of polygons (vtkImageDataGeometryFilter). We then will
    # warp the plane using the scalar (luminance) values.
    #
    reader = vtk.vtkBMPReader()
    reader.SetFileName(fileName)
    # Convert the image to a grey scale.
    luminance = vtk.vtkImageLuminance()
    luminance.SetInputConnection(reader.GetOutputPort())
    # Pass the data to the pipeline as polygons.
    geometry = vtk.vtkImageDataGeometryFilter()
    geometry.SetInputConnection(luminance.GetOutputPort())
    # Warp the data in a direction perpendicular to the image plane.
    warp = vtk.vtkWarpScalar()
    warp.SetInputConnection(geometry.GetOutputPort())
    warp.SetScaleFactor(-0.1)

    # Use vtkMergeFilter to combine the original image with the warped geometry.
    merge = vtk.vtkMergeFilter()
    merge.SetGeometryConnection(warp.GetOutputPort())
    merge.SetScalarsConnection(reader.GetOutputPort())
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(merge.GetOutputPort())
    mapper.SetScalarRange(0, 255)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    # Create the rendering window, renderer, and interactive renderer.
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the actors to the renderer, set the background and size.
    ren.AddActor(actor)
    ren.ResetCamera()
    ren.SetBackground(colors.GetColor3d("BkgColor"))
    # ren.GetActiveCamera().Azimuth(20)
    # ren.GetActiveCamera().Elevation(30)
    # ren.ResetCameraClippingRange()
    # ren.GetActiveCamera().Zoom(1.3)
    ren.GetActiveCamera().SetPosition(-100, -130, 325)
    ren.GetActiveCamera().SetFocalPoint(105, 114, -29)
    ren.GetActiveCamera().SetViewUp(0.51, 0.54, 0.67)
    ren.ResetCameraClippingRange()

    renWin.SetSize(512, 512)

    # Render the image.
    iren.Initialize()
    renWin.Render()
    iren.Start()
示例#15
0
probeTube.SetNumberOfSides(5)
probeTube.SetRadius(.05)
probeMapper = vtk.vtkPolyDataMapper()
probeMapper.SetInputConnection(probeTube.GetOutputPort())
probeMapper.SetScalarRange(output.GetScalarRange())
probeActor = vtk.vtkActor()
probeActor.SetMapper(probeMapper)
displayLine = vtk.vtkLineSource()
displayLine.SetPoint1(0, 0, 0)
displayLine.SetPoint2(1, 0, 0)
displayLine.SetResolution(probeLine.GetResolution())
displayMerge = vtk.vtkMergeFilter()
displayMerge.SetGeometryConnection(displayLine.GetOutputPort())
displayMerge.SetScalarsData(probe.GetPolyDataOutput())
displayMerge.Update()
displayWarp = vtk.vtkWarpScalar()
displayWarp.SetInputData(displayMerge.GetPolyDataOutput())
displayWarp.SetNormal(0, 1, 0)
displayWarp.SetScaleFactor(.000001)
displayWarp.Update()
displayMapper = vtk.vtkPolyDataMapper()
displayMapper.SetInputData(displayWarp.GetPolyDataOutput())
displayMapper.SetScalarRange(output.GetScalarRange())
displayActor = vtk.vtkActor()
displayActor.SetMapper(displayMapper)
outline = vtk.vtkStructuredGridOutlineFilter()
outline.SetInputData(output)
outlineMapper = vtk.vtkPolyDataMapper()
outlineMapper.SetInputConnection(outline.GetOutputPort())
outlineActor = vtk.vtkActor()
outlineActor.SetMapper(outlineMapper)
  def set_initial_display(self):
    if self.renwininter is None:
      self.renwininter = MEQ_QVTKRenderWindowInteractor(self.winsplitter)
      self.renwininter.setWhatsThis(rendering_control_instructions)
      self.renwin = self.renwininter.GetRenderWindow()
      self.inter = self.renwin.GetInteractor()
      self.winsplitter.insertWidget(0,self.renwininter)
      self.winsplitter.addWidget(self.v_box_controls)
      self.winsplitter.setSizes([500,100])
      self.renwininter.show()

# Paul Kemper suggested the following:
      camstyle = vtk.vtkInteractorStyleTrackballCamera()
      self.renwininter.SetInteractorStyle(camstyle)


    self.extents =  self.image_array.GetDataExtent()
    self.spacing = self.image_array.GetDataSpacing()
    self.origin = self.image_array.GetDataOrigin()

# An outline is shown for context.
    if self.warped_surface:
      self.index_selector.initWarpContextmenu()
      sx, sy, sz = self.image_array.GetDataSpacing()
      xMin, xMax, yMin, yMax, zMin, zMax = self.image_array.GetDataExtent()
      xMin = sx * xMin
      xMax = sx * xMax
      yMin = sy * yMin
      yMax = sy * yMax
      self.scale_factor = 0.5 * ((xMax-xMin) + (yMax-yMin)) / (self.data_max - self.data_min)
      zMin = self.data_min * self.scale_factor
      zMax = self.data_max * self.scale_factor
      self.outline = vtk.vtkOutlineSource();
      self.outline.SetBounds(xMin, xMax, yMin, yMax, zMin, zMax)
    else:
      self.index_selector.init3DContextmenu()
      self.outline = vtk.vtkOutlineFilter()
      self.outline.SetInput(self.image_array.GetOutput())
    outlineMapper = vtk.vtkPolyDataMapper();
    outlineMapper.SetInput(self.outline.GetOutput() );
    outlineActor = vtk.vtkActor();
    outlineActor.SetMapper(outlineMapper);

# create blue to red color table
    self.lut = vtk.vtkLookupTable()
    self.lut.SetHueRange(0.6667, 0.0)
    self.lut.SetNumberOfColors(256)
    self.lut.Build()

# here is where the 2-D image gets warped
    if self.warped_surface:
      geometry = vtk.vtkImageDataGeometryFilter()
      geometry.SetInput(self.image_array.GetOutput())
      self.warp = vtk.vtkWarpScalar()
      self.warp.SetInput(geometry.GetOutput())
      self.warp.SetScaleFactor(self.scale_factor)
      self.mapper = vtk.vtkPolyDataMapper();
      self.mapper.SetInput(self.warp.GetPolyDataOutput())
      self.mapper.SetScalarRange(self.data_min,self.data_max)
      self.mapper.SetLookupTable(self.lut)
      self.mapper.ImmediateModeRenderingOff()
      warp_actor = vtk.vtkActor()
#     warp_actor.SetScale(2,1,1)
      warp_actor.SetMapper(self.mapper)

      min_range = 0.5 * self.scale_factor
      max_range = 2.0 * self.scale_factor
      self.index_selector.set_emit(False)
      self.index_selector.setMaxValue(max_range,False)
      self.index_selector.setMinValue(min_range)
      self.index_selector.setTickInterval( (max_range - min_range) / 10 )
      self.index_selector.setRange(max_range, False)
      self.index_selector.setValue(self.scale_factor)
      self.index_selector.setLabel('display gain')
      self.index_selector.hideNDControllerOption()
      self.index_selector.reset_scale_toggle()
      self.index_selector.set_emit(True)
    else:
# set up ImagePlaneWidgets ...

# The shared picker enables us to use 3 planes at one time
# and gets the picking order right
      picker = vtk.vtkCellPicker()
      picker.SetTolerance(0.005)

# get locations for initial slices
      xMin, xMax, yMin, yMax, zMin, zMax =  self.extents
      x_index = (xMax-xMin) / 2
      y_index = (yMax-yMin) / 2
      z_index = (zMax-zMin) / 2

# The 3 image plane widgets are used to probe the dataset.
      self.planeWidgetX = vtk.vtkImagePlaneWidget()
      self.planeWidgetX.DisplayTextOn()
      self.planeWidgetX.SetInput(self.image_array.GetOutput())
      self.planeWidgetX.SetPlaneOrientationToXAxes()
      self.planeWidgetX.SetSliceIndex(x_index)
      self.planeWidgetX.SetPicker(picker)
      self.planeWidgetX.SetKeyPressActivationValue("x")
      self.planeWidgetX.SetLookupTable(self.lut)
      self.planeWidgetX.TextureInterpolateOff()
      self.planeWidgetX.SetResliceInterpolate(0)

      self.planeWidgetY = vtk.vtkImagePlaneWidget()
      self.planeWidgetY.DisplayTextOn()
      self.planeWidgetY.SetInput(self.image_array.GetOutput())
      self.planeWidgetY.SetPlaneOrientationToYAxes()
      self.planeWidgetY.SetSliceIndex(y_index)
      self.planeWidgetY.SetPicker(picker)
      self.planeWidgetY.SetKeyPressActivationValue("y")
      self.planeWidgetY.SetLookupTable(self.planeWidgetX.GetLookupTable())
      self.planeWidgetY.TextureInterpolateOff()
      self.planeWidgetY.SetResliceInterpolate(0)

      self.planeWidgetZ = vtk.vtkImagePlaneWidget()
      self.planeWidgetZ.DisplayTextOn()
      self.planeWidgetZ.SetInput(self.image_array.GetOutput())
      self.planeWidgetZ.SetPlaneOrientationToZAxes()
      self.planeWidgetZ.SetSliceIndex(z_index)
      self.planeWidgetZ.SetPicker(picker)
      self.planeWidgetZ.SetKeyPressActivationValue("z")
      self.planeWidgetZ.SetLookupTable(self.planeWidgetX.GetLookupTable())
      self.planeWidgetZ.TextureInterpolateOff()
      self.planeWidgetZ.SetResliceInterpolate(0)
    
      self.current_widget = self.planeWidgetZ
      self.mode_widget = self.planeWidgetZ
      self.index_selector.set_emit(False)
      self.index_selector.setMinValue(zMin)
      self.index_selector.setMaxValue(zMax,False)
      self.index_selector.setTickInterval( (zMax-zMin) / 10 )
      self.index_selector.setRange(zMax, False)
      self.index_selector.setValue(z_index)
      self.index_selector.setLabel('Z axis')
      self.index_selector.reset_scale_toggle()
      self.index_selector.set_emit(True)

# create scalar bar for display of intensity range
    self.scalar_bar = vtk.vtkScalarBarActor()
    self.scalar_bar.SetLookupTable(self.lut)
    self.scalar_bar.SetOrientationToVertical()
    self.scalar_bar.SetWidth(0.1)
    self.scalar_bar.SetHeight(0.8)
    self.scalar_bar.SetTitle("Intensity")
    self.scalar_bar.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
    self.scalar_bar.GetPositionCoordinate().SetValue(0.01, 0.1)


# Create the RenderWindow and Renderer
    self.ren = vtk.vtkRenderer()
    self.renwin.AddRenderer(self.ren)
    
# Add the outline actor to the renderer, set the background color and size
    if self.warped_surface:
      self.ren.AddActor(warp_actor)
    self.ren.AddActor(outlineActor)
    self.ren.SetBackground(0.1, 0.1, 0.2)
    self.ren.AddActor2D(self.scalar_bar)

# Create a text property for cube axes
    tprop = vtk.vtkTextProperty()
    tprop.SetColor(1, 1, 1)
    tprop.ShadowOn()

# Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
# draw the axes.  Add the actor to the renderer.
    self.axes = vtk.vtkCubeAxesActor2D()
    if self.warped_surface:
      if zMin < 0.0 and zMax > 0.0:
        zLoc = 0.0
      else:
        zLoc = zMin 
      self.axes.SetBounds(xMin, xMax, yMin, yMax, zLoc, zLoc)
      self.axes.SetZLabel(" ")
    else:
      self.axes.SetInput(self.image_array.GetOutput())
      self.axes.SetZLabel("Z")
    self.axes.SetCamera(self.ren.GetActiveCamera())
    self.axes.SetLabelFormat("%6.4g")
    self.axes.SetFlyModeToOuterEdges()
    self.axes.SetFontFactor(0.8)
    self.axes.SetAxisTitleTextProperty(tprop)
    self.axes.SetAxisLabelTextProperty(tprop)
    self.axes.SetXLabel("X")
    self.axes.SetYLabel("Y")
    self.ren.AddProp(self.axes)

# Set the interactor for the widgets
    if not self.warped_surface:
      self.planeWidgetX.SetInteractor(self.inter)
      self.planeWidgetX.On()
      self.planeWidgetY.SetInteractor(self.inter)
      self.planeWidgetY.On()
      self.planeWidgetZ.SetInteractor(self.inter)
      self.planeWidgetZ.On()

    self.initialize_camera()
示例#17
0
def runExtrusionExample(seg,
                        dsm,
                        dtm,
                        dest,
                        debug=False,
                        label=None,
                        no_dec=False,
                        no_render=False):
    # Read the terrain data
    dtmReader = vtk.vtkGDALRasterReader()
    dtmReader.SetFileName(dtm)
    dtmReader.Update()

    # Range of terrain data
    lo = dtmReader.GetOutput().GetScalarRange()[0]
    hi = dtmReader.GetOutput().GetScalarRange()[1]
    bds = dtmReader.GetOutput().GetBounds()
    #print("Bounds: {0}".format(bds))
    extent = dtmReader.GetOutput().GetExtent()
    #print("Extent: {0}".format(extent))
    origin = dtmReader.GetOutput().GetOrigin()
    #print("Origin: {0}".format(origin))
    spacing = dtmReader.GetOutput().GetSpacing()
    #print("Spacing: {0}".format(spacing))

    # Convert the terrain into a polydata.
    surface = vtk.vtkImageDataGeometryFilter()
    surface.SetInputConnection(dtmReader.GetOutputPort())

    # Make sure the polygons are planar, so need to use triangles.
    tris = vtk.vtkTriangleFilter()
    tris.SetInputConnection(surface.GetOutputPort())

    # Warp the surface by scalar values
    warp = vtk.vtkWarpScalar()
    warp.SetInputConnection(tris.GetOutputPort())
    warp.SetScaleFactor(1)
    warp.UseNormalOn()
    warp.SetNormal(0, 0, 1)
    warp.Update()

    # Read the segmentation of buildings
    segmentationReader = vtk.vtkGDALRasterReader()
    segmentationReader.SetFileName(seg)
    segmentationReader.Update()
    segmentation = segmentationReader.GetOutput()
    scalarName = segmentation.GetPointData().GetScalars().GetName()
    segmentationNp = dsa.WrapDataObject(segmentation)
    scalars = segmentationNp.PointData[scalarName]
    labels = numpy.unique(scalars)
    print("All labels: {}".format(labels))

    if (debug):
        segmentationWriter = vtk.vtkXMLImageDataWriter()
        segmentationWriter.SetFileName("segmentation.vti")
        segmentationWriter.SetInputConnection(
            segmentationReader.GetOutputPort())
        segmentationWriter.Update()

        segmentation = segmentationReader.GetOutput()
        sb = segmentation.GetBounds()
        print("segmentation bounds: \t{}".format(sb))

    # Extract polygons
    contours = vtk.vtkDiscreteFlyingEdges2D()
    #contours = vtk.vtkMarchingSquares()
    contours.SetInputConnection(segmentationReader.GetOutputPort())
    if (label):
        labels = label
    contours.SetNumberOfContours(len(labels))
    for i in range(len(labels)):
        contours.SetValue(i, labels[i])
    #print("DFE: {0}".format(contours.GetOutput()))

    if (debug):
        contoursWriter = vtk.vtkXMLPolyDataWriter()
        contoursWriter.SetFileName("contours.vtp")
        contoursWriter.SetInputConnection(contours.GetOutputPort())
        contoursWriter.Update()
        contoursData = contours.GetOutput()
        cb = contoursData.GetBounds()
        print("contours bounds: \t{}".format(cb))

    if (not no_dec):
        # combine lines into a polyline
        stripperContours = vtk.vtkStripper()
        stripperContours.SetInputConnection(contours.GetOutputPort())
        stripperContours.SetMaximumLength(3000)

        if (debug):
            stripperWriter = vtk.vtkXMLPolyDataWriter()
            stripperWriter.SetFileName("stripper.vtp")
            stripperWriter.SetInputConnection(stripperContours.GetOutputPort())
            stripperWriter.Update()

        # decimate polylines
        decimateContours = vtk.vtkDecimatePolylineFilter()
        decimateContours.SetMaximumError(0.01)
        decimateContours.SetInputConnection(stripperContours.GetOutputPort())

        if (debug):
            decimateWriter = vtk.vtkXMLPolyDataWriter()
            decimateWriter.SetFileName("decimate.vtp")
            decimateWriter.SetInputConnection(decimateContours.GetOutputPort())
            decimateWriter.Update()

        contours = decimateContours

    # Create loops
    loops = vtk.vtkContourLoopExtraction()
    loops.SetInputConnection(contours.GetOutputPort())

    if (debug):
        loopsWriter = vtk.vtkXMLPolyDataWriter()
        loopsWriter.SetFileName("loops.vtp")
        loopsWriter.SetInputConnection(loops.GetOutputPort())
        loopsWriter.Update()

    # Read the DSM
    dsmReader = vtk.vtkGDALRasterReader()
    dsmReader.SetFileName(dsm)
    dsmReader.Update()

    fit = vtk.vtkFitToHeightMapFilter()
    fit.SetInputConnection(loops.GetOutputPort())
    fit.SetHeightMapConnection(dsmReader.GetOutputPort())
    fit.UseHeightMapOffsetOn()
    fit.SetFittingStrategyToPointMaximumHeight()

    # Extrude polygon down to surface
    extrude = vtk.vtkTrimmedExtrusionFilter()
    #extrude.SetInputData(polygons)
    extrude.SetInputConnection(fit.GetOutputPort())
    extrude.SetTrimSurfaceConnection(warp.GetOutputPort())
    extrude.SetExtrusionDirection(0, 0, 1)
    extrude.CappingOn()

    extrudeWriter = vtk.vtkXMLPolyDataWriter()
    extrudeWriter.SetFileName(dest)
    extrudeWriter.SetInputConnection(extrude.GetOutputPort())
    extrudeWriter.Update()

    if (not no_render):
        # Create the RenderWindow, Renderer
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)

        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)

        # Create pipeline. Load terrain data.
        lut = vtk.vtkLookupTable()
        lut.SetHueRange(0.6, 0)
        lut.SetSaturationRange(1.0, 0)
        lut.SetValueRange(0.5, 1.0)

        # Show the terrain
        dtmMapper = vtk.vtkPolyDataMapper()
        dtmMapper.SetInputConnection(warp.GetOutputPort())
        dtmMapper.SetScalarRange(lo, hi)
        dtmMapper.SetLookupTable(lut)

        dtmActor = vtk.vtkActor()
        dtmActor.SetMapper(dtmMapper)

        # show the buildings
        trisExtrude = vtk.vtkTriangleFilter()
        trisExtrude.SetInputConnection(extrude.GetOutputPort())

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(trisExtrude.GetOutputPort())
        mapper.ScalarVisibilityOff()

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        # Render it
        ren.AddActor(dtmActor)
        ren.AddActor(actor)

        ren.GetActiveCamera().Elevation(-60)
        ren.ResetCamera()

        renWin.Render()
        iren.Start()
示例#18
0
    def render(self, **args):
        """ main function to render all required objects """

        gridData = args.get('gridData', True)
        drawSurface = args.get('drawSurface', True)
        drawAxes = args.get('drawAxes', True)
        drawColorBar = args.get('drawColorBar', True)
        drawLegend = args.get('drawLegend', True)
        wireSurface = args.get('wireSurface', False)
        drawBox = args.get('drawBox', True)
        scaleFactor = args.get('scaleFactor', (1, 1, 1))
        autoscale = args.get('autoScale', True)
        colorMap = args.get('colorMap', 'rainbow')
        reverseMap = args.get('reverseMap', False)
        drawGrid = args.get('drawGrid', False)
        resolution = args.get('gridResolution', 10)
        xtics = args.get('xtics', 0)
        ytics = args.get('ytics', 0)
        ztics = args.get('ztics', 0)
        planeGrid = args.get('planeGrid', True)
        xCutterOn = args.get('XCutterOn', True)
        yCutterOn = args.get('YCutterOn', True)
        zCutterOn = args.get('ZCutterOn', True)
        xCutterPos = args.get('XCutterPos', None)
        yCutterPos = args.get('YCutterPos', None)
        zCutterPos = args.get('ZCutterPos', None)

        self.parseRenderArgs(**args)

        if gridData:
            geometry = vtk.vtkStructuredGridGeometryFilter()
        else:
            geometry = vtk.vtkRectilinearGridGeometryFilter()

        geometry.SetInputData(self.gridfunc)
        geometry.SetExtent(self.gridfunc.GetExtent())

        if gridData:
            wzscale = self.computeScale(self.gridfunc)
            self.out = geometry.GetOutput()
        else:
            geometry.SetExtent(self.gridfunc.GetExtent())
            geometry.GetOutput().SetPoints(self.Points)
            geometry.GetOutput().GetPointData().SetScalars(self.Colors)
            geometry.GetOutput().Update()

            self.out = geometry.GetOutput()
            self.out.SetPoints(self.Points)
            self.out.GetPointData().SetScalars(self.Colors)
            self.out.Update()
            wzscale = self.computeScale(self.out)

        x = self.XScale if autoscale else self.XScale * scaleFactor[0]
        y = self.YScale if autoscale else self.YScale * scaleFactor[1]
        z = 0.5 * self.ZScale if autoscale else self.ZScale * scaleFactor[2]

        transform = vtk.vtkTransform()
        transform.Scale(x, y, z)
        trans = vtk.vtkTransformPolyDataFilter()
        trans.SetInputConnection(geometry.GetOutputPort())
        trans.SetTransform(transform)

        localScale = wzscale if wzscale < 1 else 1 / wzscale

        self.warp = vtk.vtkWarpScalar()
        self.warp.XYPlaneOn()
        self.warp.SetInputConnection(trans.GetOutputPort())
        self.warp.SetNormal(0, 0, 1)
        self.warp.UseNormalOn()
        self.warp.SetScaleFactor(localScale)

        tmp = self.gridfunc.GetScalarRange()

        # map gridfunction
        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection(self.warp.GetOutputPort())

        # calculate ranges
        if self.customZRange:
            self.mapper.SetScalarRange(*self.customZRange)
        elif self.autoZRange:
            mx = max(abs(tmp[0]), abs(tmp[1]))
            self.mapper.SetScalarRange(-mx, mx)
        else:
            self.mapper.SetScalarRange(tmp[0], tmp[1])

        wireActor = None
        bounds = self.mapper.GetBounds()

        # wire mapper
        if planeGrid:
            if not gridData:
                self.plane = vtk.vtkRectilinearGridGeometryFilter()
                self.plane.SetInput(self.gridfunc)
                self.plane.SetExtent(self.gridfunc.GetExtent())
                x_, y_ = x, y
            else:
                self.plane = vtk.vtkPlaneSource()
                self.plane.SetXResolution(resolution)
                self.plane.SetYResolution(resolution)
                x_, y_ = bounds[1] - bounds[0], bounds[3] - bounds[2]

            pltr = vtk.vtkTransform()
            pltr.Translate((bounds[1] - bounds[0]) / 2. - (0 - bounds[0]),
                           (bounds[3] - bounds[2]) / 2. - (0 - bounds[2]), bounds[4])
            pltr.Scale(x_, y_, 1)
            pltran = vtk.vtkTransformPolyDataFilter()
            pltran.SetInputConnection(self.plane.GetOutputPort())
            pltran.SetTransform(pltr)

            cmap = self.buildColormap('black-white', True)

            rgridMapper = vtk.vtkPolyDataMapper()
            rgridMapper.SetInputConnection(pltran.GetOutputPort())
            rgridMapper.SetLookupTable(cmap)

            wireActor = vtk.vtkActor()
            wireActor.SetMapper(rgridMapper)
            wireActor.GetProperty().SetRepresentationToWireframe()
            wireActor.GetProperty().SetColor(self.fgColor)

        # xcutter actor
        xactor = None
        if xCutterOn:
            xactor = self.makeXCutter(bounds, scaleFactor, xCutterPos)

        # ycutter actor
        yactor = None
        if yCutterOn:
            yactor = self.makeYCutter(bounds, scaleFactor, yCutterPos)

        # zcutter actor
        zactor = None
        if zCutterOn:
            zactor = self.makeZCutter(bounds, scaleFactor, zCutterPos)

        # create plot surface actor
        surfplot = vtk.vtkActor()
        surfplot.SetMapper(self.mapper)
        if wireSurface:
            surfplot.GetProperty().SetRepresentationToWireframe()

        # color map
        clut = self.buildColormap(colorMap, reverseMap)
        self.mapper.SetLookupTable(clut)

        # create outline
        outlinefilter = vtk.vtkOutlineFilter()
        outlinefilter.SetInputConnection(self.warp.GetOutputPort())

        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outlinefilter.GetOutputPort())
        outline = vtk.vtkActor()
        outline.SetMapper(outlineMapper)
        outline.GetProperty().SetColor(self.fgColor)

        # make axes
        zax, axes = self.makeAxes(outline, outlinefilter)

        # setup axes
        xaxis = axes.GetXAxisActor2D()
        yaxis = axes.GetYAxisActor2D()
        zaxis = axes.GetZAxisActor2D()

        xaxis.SetLabelFormat(self.config.XLabelsFormat())
        xaxis.SetAdjustLabels(1)
        xaxis.SetNumberOfMinorTicks(xtics)

        yaxis.SetLabelFormat(self.config.YLabelsFormat())
        yaxis.SetNumberOfMinorTicks(ytics)
        yaxis.SetAdjustLabels(1)

        zaxis.SetLabelFormat(self.config.ZLabelsFormat())
        zaxis.SetNumberOfMinorTicks(ztics)
        zaxis.SetAdjustLabels(1)

        # create colorbar
        colorbar = self.makeColorbar()

        # renderer
        if drawSurface:
            self.renderer.AddActor(surfplot)
            self.actors.append(surfplot)
        if drawGrid:
            self.renderer.AddViewProp(zax)
            self.actors.append(zax)
        if planeGrid:
            self.renderer.AddActor(wireActor)
            self.actors.append(wireActor)
        if drawBox:
            self.renderer.AddActor(outline)
            self.actors.append(outline)
        if drawAxes:
            self.renderer.AddViewProp(axes)
            self.actors.append(axes)
        if drawColorBar or drawLegend:
            self.renderer.AddActor(colorbar)
            self.actors.append(colorbar)

        self.colorbar = colorbar
        self._addPlaneCutters(xactor, yactor, zactor, xCutterOn, yCutterOn, zCutterOn)
示例#19
0
output = plane.GetOutput()

# Manually construct scalars
NPts = output.GetNumberOfPoints()
scalars = vtk.vtkDoubleArray()
scalars.SetNumberOfComponents(1)
scalars.SetNumberOfTuples(NPts)

for i in range(0,NPts):
    scalars.SetTuple1(i, math.Random(0,10))

output.GetPointData().SetScalars(scalars)

# Output some statistics
print("Number of points: {0}".format(NPts))

# Time the warping
warpF = vtk.vtkWarpScalar()
warpF.SetInputData(output)
warpF.SetScaleFactor(2.5);

# For timing the various tests
timer = vtk.vtkTimerLog()

timer.StartTimer()
warpF.Update()
timer.StopTimer()
time = timer.GetElapsedTime()
print("Warp via scalar: {0}".format(time))
示例#20
0
probeTube.SetNumberOfSides(5)
probeTube.SetRadius(.05)
probeMapper = vtk.vtkPolyDataMapper()
probeMapper.SetInputConnection(probeTube.GetOutputPort())
probeMapper.SetScalarRange(output.GetScalarRange())
probeActor = vtk.vtkActor()
probeActor.SetMapper(probeMapper)
displayLine = vtk.vtkLineSource()
displayLine.SetPoint1(0,0,0)
displayLine.SetPoint2(1,0,0)
displayLine.SetResolution(probeLine.GetResolution())
displayMerge = vtk.vtkMergeFilter()
displayMerge.SetGeometryConnection(displayLine.GetOutputPort())
displayMerge.SetScalarsData(probe.GetPolyDataOutput())
displayMerge.Update()
displayWarp = vtk.vtkWarpScalar()
displayWarp.SetInputData(displayMerge.GetPolyDataOutput())
displayWarp.SetNormal(0,1,0)
displayWarp.SetScaleFactor(.000001)
displayWarp.Update()
displayMapper = vtk.vtkPolyDataMapper()
displayMapper.SetInputData(displayWarp.GetPolyDataOutput())
displayMapper.SetScalarRange(output.GetScalarRange())
displayActor = vtk.vtkActor()
displayActor.SetMapper(displayMapper)
outline = vtk.vtkStructuredGridOutlineFilter()
outline.SetInputData(output)
outlineMapper = vtk.vtkPolyDataMapper()
outlineMapper.SetInputConnection(outline.GetOutputPort())
outlineActor = vtk.vtkActor()
outlineActor.SetMapper(outlineMapper)
示例#21
0
def main(argv):
  if len(argv) < 2:
    print "usage: ",argv[0]," <data> [flat]"
    exit(1)
  data_fn = argv[1]
  flat = False
  if len(argv) > 2:
    flat = True
  
  mapper = vtk.vtkPolyDataMapper()
  if data_fn.find('.vtk') != -1:
    reader = vtk.vtkPolyDataReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
    trianglize = vtk.vtkDelaunay2D()
    trianglize.SetInput(data)
    trianglize.Update()
    mapper.SetInputConnection(trianglize.GetOutputPort())
  elif data_fn.find('.pgm') != -1:
    reader = vtk.vtkPNMReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
    geometry = vtk.vtkImageDataGeometryFilter()
    geometry.SetInputConnection(reader.GetOutputPort())
    geometry.Update()
    if flat:
      merge = vtk.vtkMergeFilter()
      merge.SetGeometry(geometry.GetOutput())
      merge.SetScalars(data)
      mapper.SetInputConnection(merge.GetOutputPort())
    else:
      warp = vtk.vtkWarpScalar()
      warp.SetInputConnection(geometry.GetOutputPort())
      warp.SetScaleFactor(0.3) # looked good
      warp.Update()
      merge = vtk.vtkMergeFilter()
      merge.SetGeometry(warp.GetOutput())
      merge.SetScalars(data)
      mapper.SetInputConnection(merge.GetOutputPort())
  elif data_fn.find('.dcm') != -1:
    reader =vtk.vtkDICOMImageReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
    geometry = vtk.vtkImageDataGeometryFilter()
    geometry.SetInput(data)
    geometry.Update()
    if flat:
      mapper.SetInputConnection(geometry.GetOutputPort())
    else:
      warp = vtk.vtkWarpScalar()
      warp.SetInputConnection(geometry.GetOutputPort())
      warp.Update()
      mapper.SetInputConnection(warp.GetOutputPort())
  else:
    print "unrecognized data file:",data_fn
    exit(1)
  
  lut = vtk.vtkLookupTable()
  lut.SetNumberOfColors(10)
  lut.SetHueRange(0.5,0.3)
  lut.SetSaturationRange(0.6,0.5)
  lut.SetValueRange(1.0,0.5)
  lut.Build()

  mapper.ImmediateModeRenderingOff()
  mapper.SetLookupTable(lut)
 
  actor = vtk.vtkActor()
  actor.SetMapper(mapper)
  
  renderer = vtk.vtkRenderer()
  renderWindow = vtk.vtkRenderWindow()
  renderWindow.SetSize(700,700)
  renderWindow.AddRenderer(renderer)
 
  renderer.AddActor(actor)
  renderer.SetBackground(0.4,0.3,0.2)

  interactor = vtk.vtkRenderWindowInteractor()
  interactor.SetRenderWindow(renderWindow)
  
  renderWindow.Render()
  interactor.Start()
示例#22
0
def main(argv):
  if len(argv) < 2:
    print "usage: ",argv[0]," <data>"
    exit(1)
  data_fn = argv[1]
  
  mapper = vtk.vtkPolyDataMapper()
  if data_fn.find('.vtk') != -1:
    reader = vtk.vtkPolyDataReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
    trianglize = vtk.vtkDelaunay2D()
    trianglize.SetInput(data)
    trianglize.Update()
    mapper.SetInputConnection(trianglize.GetOutputPort())
  elif data_fn.find('.pgm') != -1:
    reader = vtk.vtkPNMReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
    trianglize = vtk.vtkImageDataGeometryFilter()
    trianglize.SetInput(data)
    trianglize.Update()
    warp = vtk.vtkWarpScalar()
    warp.SetScaleFactor(0.2) # arbitrary choice
    warp.SetInputConnection(trianglize.GetOutputPort())
    warp.Update()
    mapper.SetInputConnection(warp.GetOutputPort())
  elif data_fn.find('.dcm') != -1:
    reader =vtk.vtkDICOMImageReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
    trianglize = vtk.vtkImageDataGeometryFilter()
    trianglize.SetInput(data)
    trianglize.Update()
    warp = vtk.vtkWarpScalar()
    #warp.SetScaleFactor(0.2) # arbitrary choice
    warp.SetInputConnection(trianglize.GetOutputPort())
    warp.Update()
    mapper.SetInputConnection(warp.GetOutputPort())
  else:
    print "unrecognized data file:",data_fn
    exit(1)
  
 
  actor = vtk.vtkActor()
  actor.SetMapper(mapper)
  
  renderer = vtk.vtkRenderer()
  renderWindow = vtk.vtkRenderWindow()
  renderWindow.SetSize(700,700)
  renderWindow.AddRenderer(renderer)
  renderWindow.SetWindowName("heightfield")
 
  renderer.AddActor(actor)
  renderer.SetBackground(0.4,0.3,0.2)

  interactor = vtk.vtkRenderWindowInteractor()
  interactor.SetRenderWindow(renderWindow)
  
  renderWindow.Render()
  interactor.Start()
def compute_vonMisesStress_for_MV(inputfilename, outputfilename):
	# ======================================================================
	# get system arguments -------------------------------------------------
	# Path to input file and name of the output file
	#inputfilename = sys.argv[1]
	#outputfilename = sys.argv[2]
	
	print " "
	print "=================================================================================================="
	print "=== Execute Python script to analyze MV geometry in order for the HiFlow3-based MVR-Simulation ==="
	print "=================================================================================================="
	print " "
	
	# ======================================================================
	# Read file
	if inputfilename[-4] == 'p':
		reader = vtk.vtkXMLPUnstructuredGridReader()
		reader.SetFileName(inputfilename)
		reader.Update()
	else:
		reader = vtk.vtkXMLUnstructuredGridReader()
		reader.SetFileName(inputfilename)
		reader.Update()
	
	print "Reading input files: DONE."
	
	# ======================================================================
	# Compute displacement vector
	calc = vtk.vtkArrayCalculator()
	calc.SetInput(reader.GetOutput())
	calc.SetAttributeModeToUsePointData()
	calc.AddScalarVariable('x', 'u0', 0)
	calc.AddScalarVariable('y', 'u1', 0)
	calc.AddScalarVariable('z', 'u2', 0)
	calc.SetFunction('x*iHat+y*jHat+z*kHat')
	calc.SetResultArrayName('DisplacementSolutionVector')
	calc.Update()
	
	# ======================================================================
	# Compute strain tensor
	derivative = vtk.vtkCellDerivatives()
	derivative.SetInput(calc.GetOutput())
	derivative.SetTensorModeToComputeStrain()
	derivative.Update()
	
	# ======================================================================
	# Compute von Mises stress
	calc = vtk.vtkArrayCalculator()
	calc.SetInput(derivative.GetOutput())
	calc.SetAttributeModeToUseCellData()
	calc.AddScalarVariable('Strain_0', 'Strain', 0)
	calc.AddScalarVariable('Strain_1', 'Strain', 1)
	calc.AddScalarVariable('Strain_2', 'Strain', 2)
	calc.AddScalarVariable('Strain_3', 'Strain', 3)
	calc.AddScalarVariable('Strain_4', 'Strain', 4)
	calc.AddScalarVariable('Strain_5', 'Strain', 5)
	calc.AddScalarVariable('Strain_6', 'Strain', 6)
	calc.AddScalarVariable('Strain_7', 'Strain', 7)
	calc.AddScalarVariable('Strain_8', 'Strain', 8)
	calc.SetFunction('sqrt( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))^2 + (2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8))^2 + (2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8))^2 - ( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8)) ) - ( (2*700*Strain_0 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8)) ) - ( (2*700*Strain_4 + 28466*(Strain_0+Strain_4+Strain_8))*(2*700*Strain_8 + 28466*(Strain_0+Strain_4+Strain_8)) ) + 3 * ((2*700*Strain_3)^2 + (2*700*Strain_6)^2 + (2*700*Strain_7)^2) )')
	calc.SetResultArrayName('vonMisesStress_forMV_mu700_lambda28466')
	calc.Update()
	
	print "Computation of displacement vectors, Cauchy strain and vom Mises stress: DONE."
	
	# ======================================================================
	# Define dummy variable; get output of calc filter
	dummy = calc.GetOutput()
	
	# Get point data arrays u0, u1 and u2
	pointData_u0 = dummy.GetPointData().GetArray('u0')
	pointData_u1 = dummy.GetPointData().GetArray('u1')
	pointData_u2 = dummy.GetPointData().GetArray('u2')
	
	# Set scalars
	dummy.GetPointData().SetScalars(pointData_u0)
	
	# ======================================================================
	# Warp by scalar u0
	warpScalar = vtk.vtkWarpScalar()
	warpScalar.SetInput(dummy)
	warpScalar.SetNormal(1.0,0.0,0.0)
	warpScalar.SetScaleFactor(1.0)
	warpScalar.SetUseNormal(1)
	warpScalar.Update()
	
	# Get output and set scalars
	dummy = warpScalar.GetOutput()
	dummy.GetPointData().SetScalars(pointData_u1)
	
	# ======================================================================
	# Warp by scalar u1
	warpScalar = vtk.vtkWarpScalar()
	warpScalar.SetInput(dummy)
	warpScalar.SetNormal(0.0,1.0,0.0)
	warpScalar.SetScaleFactor(1.0)
	warpScalar.SetUseNormal(1)
	warpScalar.Update()
	
	# Get output and set scalars
	dummy = warpScalar.GetOutput()
	dummy.GetPointData().SetScalars(pointData_u2)
	
	# ======================================================================
	# Warp by scalar u2
	warpScalar = vtk.vtkWarpScalar()
	warpScalar.SetInput(dummy)
	warpScalar.SetNormal(0.0,0.0,1.0)
	warpScalar.SetScaleFactor(1.0)
	warpScalar.SetUseNormal(1)
	warpScalar.Update()
	
	# Get ouput and add point data arrays that got deleted earlier
	dummy = warpScalar.GetOutput()
	dummy.GetPointData().AddArray(pointData_u0)
	dummy.GetPointData().AddArray(pointData_u1)
	
	# ======================================================================
	# Write output to vtu
	writer = vtk.vtkXMLUnstructuredGridWriter()
	writer.SetDataModeToAscii()
	writer.SetFileName(outputfilename)
	writer.SetInput(dummy)
	writer.Write()
	
	# ======================================================================
	print "Writing Extended VTU incl. von Mises Stress information: DONE."
	print "=============================================================="
	print " "
示例#24
0
mesh_flat.SetTransform(flattener)
mesh_flat.Update()
mesh_flat = mesh_flat.GetOutput()

# do the work
if opts.verbose: print "Interpolating"
probe = vtk.vtkProbeFilter()
probe.SetInput(mesh_flat)  # the input is the new mesh
probe.SetSource(data_flat)  # the source is the data
probe.Update()
probe = probe.GetOutput()
if opts.verbose: print "Done interpolating"

# warp output using elevation values
if probe.GetPointData().GetArray("Elevation"):
    to_output = vtk.vtkWarpScalar()
    to_output.SetInput(probe)
    to_output.SetInputArrayToProcess(0, 0, 0, 0, "Elevation")
    to_output.Update()
    to_output = to_output.GetOutput()
else:
    to_output = probe

if opts.verbose: print "Adding provenance"
command_used = vtk.vtkStringArray()
command_used.SetName("provenance")
command_used.InsertNextValue(" ".join(sys.argv))
to_output.GetFieldData().AddArray(command_used)

# Converting to vtr PREPMESH format
data = to_output
示例#25
0
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
示例#26
0
    def __init__(self):
        # Create the RenderWindow, Renderer and both Actors
        self.renderer = vtk.vtkRenderer()
        self.renWin = vtk.vtkRenderWindow()
        self.renWin.AddRenderer(self.renderer)
        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renWin)
        self.iren.SetInteractorStyle(vtk.vtkInteractorStyleSwitch())
        self.iren.GetInteractorStyle().SetCurrentStyleToTrackballCamera()
        # Start by loading some data.
        input_fname = sys.argv[1]
        if len(sys.argv) > 2:  # selector have been provided
            self.selector = sys.argv[2]
            self.data = np.load(input_fname, mmap_mode='r')
            assert self.select_slice()
        else:  # selector have NOT been provided
            self.selector = False
            self.data = np.load(input_fname)
            if not (
                    self.data.ndim == 2
            ):  # If dim not compatible with elevation, ask for a selector
                print('Incompatible data dimentionality : ', self.data.shape)
                self.selector = raw_input(
                    'Enter selector to cast input as 2D array (e.g. [42,:,:]) -> '
                )
                assert self.select_slice()

        convertor = npy_converter()
        self.image = convertor.convert(self.data)

        self.mi, self.ma = self.image.GetScalarRange()

        self.warp_factor = 0.
        self.warp_step = 0.001

        geometry = vtk.vtkImageDataGeometryFilter()
        if vtk.vtkVersion.GetVTKMajorVersion() < 6:
            geometry.SetInput(self.image)
        else:
            geometry.SetInputData(self.image)

        self.warp = vtk.vtkWarpScalar()
        self.warp.SetInputConnection(geometry.GetOutputPort())
        self.warp.SetScaleFactor(1)
        self.warp.UseNormalOn()
        self.warp.SetNormal(1, 0, 0)
        self.warp.Update()

        lut = vtk.vtkLookupTable()
        lut.SetTableRange(self.image.GetScalarRange())
        lut.SetNumberOfColors(256)
        lut.SetHueRange(0.7, 0)
        lut.Build()

        merge = vtk.vtkMergeFilter()
        if vtk.vtkVersion.GetVTKMajorVersion() < 6:
            merge.SetGeometry(self.warp.GetOutput())
            merge.SetScalars(self.image)
        else:
            merge.SetGeometryInputData(self.warp.GetOutput())
            merge.SetScalarsData(self.image)
        merge.Update()

        self.outline = vtk.vtkOutlineFilter()
        self.outline.SetInputConnection(merge.GetOutputPort())
        self.outline.Update()

        outlineMapper = vtk.vtkPolyDataMapper()
        if vtk.vtkVersion.GetVTKMajorVersion() < 6:
            outlineMapper.SetInputConnection(self.outline.GetOutputPort())
        else:
            outlineMapper.SetInputData(self.outline.GetOutputDataObject(0))

        box = vtk.vtkActor()
        box.SetMapper(outlineMapper)
        box.GetProperty().SetColor(0, 0, 0)

        self.renderer.AddActor(box)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetLookupTable(lut)
        mapper.SetScalarRange(self.image.GetScalarRange())
        mapper.SetInputConnection(merge.GetOutputPort())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().ShadingOff()
        self.renderer.AddActor(actor)

        scalarBar = vtk.vtkScalarBarActor()
        scalarBar.SetTitle("")
        scalarBar.SetWidth(0.1)
        scalarBar.SetHeight(0.9)
        scalarBar.SetLookupTable(lut)
        #self.renderer.AddActor2D(scalarBar)

        self.build_axes()

        self.warp.SetScaleFactor(self.warp_factor)
        self.warp.Update()
        self.outline.Update()

        self.renderer.ResetCameraClippingRange()

        self.renderer.SetBackground(1, 1, 1)
        self.renWin.SetSize(500, 500)

        self.camera = self.renderer.GetActiveCamera()
        self.center_on_actor(actor)

        self.iren.AddObserver("CharEvent", self.on_keyboard_input)
        self.iren.Initialize()
        self.renWin.Render()
        self.iren.Start()
示例#27
0
#streamer.SetStartPosition(0.18474886E+01, 0.12918899E+00, 0.00000000E+00)
streamer.SetSource(seedFilter.GetOutput())
streamer.SetMaximumPropagation(160000.0)
#streamer.SetMaximumPropagationUnitToTimeUnit()
streamer.SetInitialIntegrationStep(1.0)
#streamer.SetInitialIntegrationStepUnitToCellLengthUnit()
streamer.SetIntegrationDirectionToBoth()
streamer.SetIntegrator(integ)
#
streamTube = vtk.vtkTubeFilter()
streamTube.SetInputConnection(streamer.GetOutputPort())
#streamTube.SetInputArrayToProcess(1,0,0,vtkDataObject::FIELD_ASSOCIATION_POINTS, vectors)
streamTube.SetRadius(10000.0)
streamTube.SetNumberOfSides(12)

streamWarp = vtk.vtkWarpScalar()
streamWarp.SetInputConnection(streamTube.GetOutputPort())
streamWarp.SetNormal(0.0,0.0,1.0)
streamWarp.UseNormalOn()
streamWarp.SetScaleFactor(10000.0)

mapStreamTube = vtk.vtkPolyDataMapper()
mapStreamTube.SetInputConnection(streamWarp.GetOutputPort())
#mapStreamTube.SetInputConnection(streamer.GetOutputPort())
#mapStreamTube.SetInputConnection(streamTube.GetOutputPort())
mapStreamTube.SetScalarRange(meshReader.GetOutput().GetPointData().GetScalars().GetRange())

mapStreamTube.SetLookupTable(lut)
streamTubeActor = vtk.vtkActor()
streamTubeActor.SetMapper(mapStreamTube)
streamTubeActor.GetProperty().SetColor(0.0,0.0,0.0)
示例#28
0
def main():
    colors = vtk.vtkNamedColors()

    # Create the RenderWindow, Renderer and Interactor.
    #
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # create plane to warp
    plane = vtk.vtkPlaneSource()
    plane.SetResolution(300, 300)

    transform = vtk.vtkTransform()
    transform.Scale(10.0, 10.0, 1.0)

    transF = vtk.vtkTransformPolyDataFilter()
    transF.SetInputConnection(plane.GetOutputPort())
    transF.SetTransform(transform)
    transF.Update()

    # Compute the Bessel function and derivatives. This portion could be
    # encapsulated into source or filter object.
    #
    inputPd = transF.GetOutput()
    numPts = inputPd.GetNumberOfPoints()

    newPts = vtk.vtkPoints()
    newPts.SetNumberOfPoints(numPts)

    derivs = vtk.vtkDoubleArray()
    derivs.SetNumberOfTuples(numPts)

    bessel = vtk.vtkPolyData()
    bessel.CopyStructure(inputPd)
    bessel.SetPoints(newPts)
    bessel.GetPointData().SetScalars(derivs)

    x = [0.0] * 3
    for i in range(0, numPts):
        inputPd.GetPoint(i, x)
        r = math.sqrt(float(x[0] * x[0]) + x[1] * x[1])
        x[2] = math.exp(-r) * math.cos(10.0 * r)
        newPts.SetPoint(i, x)
        deriv = -math.exp(-r) * (math.cos(10.0 * r) +
                                 10.0 * math.sin(10.0 * r))
        derivs.SetValue(i, deriv)

    # Warp the plane.
    warp = vtk.vtkWarpScalar()
    warp.SetInputData(bessel)
    warp.XYPlaneOn()
    warp.SetScaleFactor(0.5)

    # Mapper and actor.
    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(warp.GetOutputPort())
    tmp = bessel.GetScalarRange()
    mapper.SetScalarRange(tmp[0], tmp[1])

    carpet = vtk.vtkActor()
    carpet.SetMapper(mapper)

    # Assign our actor to the renderer.
    ren.AddActor(carpet)
    ren.SetBackground(colors.GetColor3d("Beige"))
    renWin.SetSize(640, 480)

    # draw the resulting scene
    ren.ResetCamera()
    ren.GetActiveCamera().Zoom(1.4)
    ren.GetActiveCamera().Elevation(-55)
    ren.GetActiveCamera().Azimuth(25)
    ren.ResetCameraClippingRange()

    renWin.Render()
    iren.Start()
示例#29
0
lo = Scale * demModel.GetElevationBounds()[0]
hi = Scale * demModel.GetElevationBounds()[1]

demActor = vtk.vtkLODActor()

# create a pipeline for each lod mapper
shrink16 = vtk.vtkImageShrink3D()
shrink16.SetShrinkFactors(16, 16, 1)
shrink16.SetInputConnection(demModel.GetOutputPort())
shrink16.AveragingOn()

geom16 = vtk.vtkImageDataGeometryFilter()
geom16.SetInputConnection(shrink16.GetOutputPort())
geom16.ReleaseDataFlagOn()

warp16 = vtk.vtkWarpScalar()
warp16.SetInputConnection(geom16.GetOutputPort())
warp16.SetNormal(0, 0, 1)
warp16.UseNormalOn()
warp16.SetScaleFactor(Scale)
warp16.ReleaseDataFlagOn()

elevation16 = vtk.vtkElevationFilter()
elevation16.SetInputConnection(warp16.GetOutputPort())
elevation16.SetLowPoint(0, 0, lo)
elevation16.SetHighPoint(0, 0, hi)
elevation16.SetScalarRange(lo, hi)
elevation16.ReleaseDataFlagOn()

normals16 = vtk.vtkPolyDataNormals()
normals16.SetInputConnection(elevation16.GetOutputPort())
示例#30
0
    N = 72
    image_data.SetDimensions(N, N, 1)
    try:
        method = image_data.SetScalarComponentFromFloat
    except AttributeError:
        method = image_data.SetScalarComponentFromDouble
    for i in range(N):
        for j in range(N):
            a = float(i) / N
            b = float(j) / N
            v = 0.5 + 0.5 * cos(13 * a) * cos(8 * b + 3 * a * a)
            v = v**2
            method(i, j, 0, 0, v)
    geometry_filter = vtk.vtkImageDataGeometryFilter()
    geometry_filter.SetInput(image_data)
    warp = vtk.vtkWarpScalar()
    warp.SetInput(geometry_filter.GetOutput())
    warp.SetScaleFactor(8.1)
    normal_filter = vtk.vtkPolyDataNormals()
    normal_filter.SetInput(warp.GetOutput())
    data_mapper = vtk.vtkDataSetMapper()
    data_mapper.SetInput(normal_filter.GetOutput())
    data_actor = vtk.vtkActor()
    data_actor.SetMapper(data_mapper)
    renderer.AddActor(data_actor)

    table = vtk.vtkLookupTable()
    data_mapper.SetLookupTable(table)

    # the actual gradient editor code.
    def on_color_table_changed():
lo = Scale * demModel.GetElevationBounds()[0]
hi = Scale * demModel.GetElevationBounds()[1]

demActor = vtk.vtkLODActor()

# create a pipeline for each lod mapper
shrink16 = vtk.vtkImageShrink3D()
shrink16.SetShrinkFactors(16, 16, 1)
shrink16.SetInputConnection(demModel.GetOutputPort())
shrink16.AveragingOn()

geom16 = vtk.vtkImageDataGeometryFilter()
geom16.SetInputConnection(shrink16.GetOutputPort())
geom16.ReleaseDataFlagOn()

warp16 = vtk.vtkWarpScalar()
warp16.SetInputConnection(geom16.GetOutputPort())
warp16.SetNormal(0, 0, 1)
warp16.UseNormalOn()
warp16.SetScaleFactor(Scale)
warp16.ReleaseDataFlagOn()

elevation16 = vtk.vtkElevationFilter()
elevation16.SetInputConnection(warp16.GetOutputPort())
elevation16.SetLowPoint(0, 0, lo)
elevation16.SetHighPoint(0, 0, hi)
elevation16.SetScalarRange(lo, hi)
elevation16.ReleaseDataFlagOn()

normals16 = vtk.vtkPolyDataNormals()
normals16.SetInputConnection(elevation16.GetOutputPort())
示例#32
0
    def elevation(self, data):
        self.data = data
        
        
        self.settings = wx.Panel(self)
        
        self.plot_type= self.type = 'elevation'
        
        self.image = self.array_to_2d_imagedata()
        
        geometry = vtk.vtkImageDataGeometryFilter()  
        if vtk.vtkVersion.GetVTKMajorVersion()<6:
            geometry.SetInput(self.image)
        else:
            geometry.SetInputData(self.image)
            
        self.warp = vtk.vtkWarpScalar()
        self.warp.SetInputConnection(geometry.GetOutputPort())
        self.warp.SetScaleFactor(1)
        self.warp.UseNormalOn()
        self.warp.SetNormal(0,0,1)
        self.warp.Update()
        
        lut =vtk.vtkLookupTable()
        lut.SetTableRange(self.image.GetScalarRange())
        lut.SetNumberOfColors(256)
        lut.SetHueRange(0.7, 0)
        lut.Build()
        
        merge=vtk.vtkMergeFilter()
        if vtk.vtkVersion.GetVTKMajorVersion()<6:
            merge.SetGeometry(self.warp.GetOutput())
            merge.SetScalars(self.image)
        else:
            merge.SetGeometryInputData(self.warp.GetOutput())
            merge.SetScalarsData(self.image)
        merge.Update()
        
        self.outline = vtk.vtkOutlineFilter()
        self.outline.SetInputConnection(merge.GetOutputPort())
        self.outline.Update()
        
        outlineMapper = vtk.vtkPolyDataMapper()
        if vtk.vtkVersion.GetVTKMajorVersion()<6:
            outlineMapper.SetInputConnection(self.outline.GetOutputPort())
        else:
            outlineMapper.SetInputData(self.outline.GetOutputDataObject(0))
        
        box=vtk.vtkActor()
        box.SetMapper(outlineMapper)
        box.GetProperty().SetColor(0,0,0)
        
        self.renderer.AddActor(box)
        self.actor_list.append(box)
        
        mapper=vtk.vtkPolyDataMapper()
        mapper.SetLookupTable(lut)
        mapper.SetScalarRange(self.image.GetScalarRange())
        mapper.SetInputConnection(merge.GetOutputPort())
        
        actor=vtk.vtkActor()
        actor.SetMapper(mapper)
        self.renderer.AddActor(actor)
        self.actor_list.append(actor)
        
        scalarBar = vtk.vtkScalarBarActor()
        scalarBar.SetTitle("")
        scalarBar.SetWidth(0.1)
        scalarBar.SetHeight(0.9)
        scalarBar.SetLookupTable(lut)
        self.renderer.AddActor2D(scalarBar)
        self.actor_list.append(scalarBar)
        
        self.build_axes(noZaxis = True)
        
        self.center_on_actor(actor)
        self.iren.Render()
        self.warp.SetScaleFactor(0)
        self.warp.Update()
        self.outline.Update()
        
        self.renderer.ResetCameraClippingRange()
        self.iren.Render()
        
        
        sb0 = wx.StaticBox(self.settings, wx.ID_ANY, label = "Scaling Panel")
        Sizer0 = wx.StaticBoxSizer(sb0, wx.HORIZONTAL)
        

        content1 = wx.StaticText(self.settings, -1, "X")
        
        self.x_Offset = wx.TextCtrl(self.settings, wx.ID_ANY, size = (45,27),style = wx.TE_PROCESS_ENTER )
        self.Bind(wx.EVT_TEXT_ENTER, self.x_spacing_onmove ,self.x_Offset)
        self.x_Offset.SetValue('1.0')
        
        
        self.x_slider = wx.Slider(self.settings,id=wx.ID_ANY,value=100,minValue=0,maxValue=200, style= wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)
        self.x_slider.Bind(wx.EVT_SCROLL, self.x_spacing_onmove)
        content2 = wx.StaticText(self.settings, -1, "Y")
        
        self.y_Offset = wx.TextCtrl(self.settings, wx.ID_ANY,size = (45,27), style = wx.TE_PROCESS_ENTER )
        self.Bind(wx.EVT_TEXT_ENTER, self.y_spacing_onmove ,self.y_Offset)
        self.y_Offset.SetValue('1.0')
        
        self.y_slider = wx.Slider(self.settings,id=wx.ID_ANY,value=100,minValue=0,maxValue=200, style= wx.SL_AUTOTICKS | wx.SL_HORIZONTAL | wx.SL_LABELS)
        self.y_slider.Bind(wx.EVT_SCROLL, self.y_spacing_onmove)
        
        sb1 = wx.StaticBox(self.settings, wx.ID_ANY, label = "Elevation Panel")
        Sizer1 = wx.StaticBoxSizer(sb1, wx.HORIZONTAL)
        
        content3 = wx.StaticText(self.settings, -1, "Warp")
        
        
        self.z_Offset = wx.TextCtrl(self.settings, wx.ID_ANY, size = (45,27),style = wx.TE_PROCESS_ENTER )
        self.Bind(wx.EVT_TEXT_ENTER, self.z_spacing_onmove ,self.z_Offset)
        self.z_Offset.SetValue('1.0')
        
        
        self.z_slider = wx.Slider(self.settings,id=wx.ID_ANY,value=0,minValue=0,maxValue=100, style= wx.SL_HORIZONTAL )
        self.z_slider.Bind(wx.EVT_SCROLL, self.z_spacing_onmove)
        
        # build sizer
        Sizer0.Add(content1, proportion=0, flag = wx.ALIGN_BOTTOM)
        Sizer0.Add(self.x_Offset,proportion=0, flag= wx.ALIGN_CENTER_VERTICAL)
        Sizer0.Add(self.x_slider,proportion=1, flag= wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
        Sizer0.Add((20, -1),proportion= 0, flag= wx.ALIGN_CENTER_VERTICAL)
        Sizer0.Add(content2, proportion=0, flag = wx.ALIGN_CENTER_VERTICAL)
        Sizer0.Add(self.y_Offset,proportion=0, flag= wx.ALIGN_BOTTOM)
        Sizer0.Add(self.y_slider,proportion=1, flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
        
        Sizer1.Add(content3, proportion=0, flag = wx.ALIGN_CENTER_VERTICAL)
        Sizer1.Add(self.z_Offset,proportion=0, flag= wx.ALIGN_CENTER_VERTICAL)
        Sizer1.Add(self.z_slider,proportion=1, flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND) 
        
        self.save_fig  = wx.Button(self.settings, wx.ID_ANY, label="Save current view")
        self.save_fig.Bind(wx.EVT_BUTTON, self.Screen_shot)
        
        Sizer = wx.BoxSizer(wx.VERTICAL)
        
        HSizer = wx.BoxSizer(wx.HORIZONTAL)
        
        HSizer.Add(Sizer0, 1, wx.EXPAND, 0)
        HSizer.Add(Sizer1, 1, wx.EXPAND, 0)
        
        
        Sizer.Add(HSizer, 0, wx.EXPAND, 0)
        Sizer.Add(self.save_fig, 0, wx.EXPAND, 0)
       
        self.settings.SetSizer(Sizer)
        Sizer.Fit(self.settings)
        self.settings.Layout()
        
        self._mgr.AddPane(self.settings, wxaui.AuiPaneInfo().Center().Dock().Bottom().CloseButton(False).CaptionVisible(False))
        self._mgr.Update()
示例#33
0
def main(args):
    parser = argparse.ArgumentParser(
        description=
        'Render a DSM from a DTM and polygons representing buildings.')
    parser.add_argument("--input_vtp_path",
                        type=str,
                        help="Input buildings polygonal file (.vtp)")
    parser.add_argument(
        "--input_obj_paths",
        nargs="*",
        help="List of input building (.obj) file paths.  "
        "Building object files start "
        "with a digit, road object files start with \"Road\". "
        "All obj files start with comments specifying the offsets "
        "that are added the coordinats. There are three comment lines, "
        "one for each coordinate: \"#c offset: value\" where c is x, y and z.")
    parser.add_argument("input_dtm", help="Input digital terain model (DTM)")
    parser.add_argument("output_dsm",
                        help="Output digital surface model (DSM)")
    parser.add_argument("--render_png",
                        action="store_true",
                        help="Do not save the DSM, render into a PNG instead.")
    parser.add_argument(
        "--render_cls",
        action="store_true",
        help="Render a buildings mask: render buildings label (6), "
        "background (2) and no DTM.")
    parser.add_argument("--buildings_only",
                        action="store_true",
                        help="Do not use the DTM, use only the buildings.")
    parser.add_argument("--debug",
                        action="store_true",
                        help="Save intermediate results")
    args = parser.parse_args(args)

    # open the DTM
    dtm = gdal.Open(args.input_dtm, gdal.GA_ReadOnly)
    if not dtm:
        raise RuntimeError("Error: Failed to open DTM {}".format(
            args.input_dtm))

    dtmDriver = dtm.GetDriver()
    dtmDriverMetadata = dtmDriver.GetMetadata()
    dsm = None
    dtmBounds = [0.0, 0.0, 0.0, 0.0]
    if dtmDriverMetadata.get(gdal.DCAP_CREATE) == "YES":
        print("Create destination image "
              "size:({}, {}) ...".format(dtm.RasterXSize, dtm.RasterYSize))
        # georeference information
        projection = dtm.GetProjection()
        transform = dtm.GetGeoTransform()
        gcpProjection = dtm.GetGCPProjection()
        gcps = dtm.GetGCPs()
        options = ["COMPRESS=DEFLATE"]
        # ensure that space will be reserved for geographic corner coordinates
        # (in DMS) to be set later
        if (dtmDriver.ShortName == "NITF" and not projection):
            options.append("ICORDS=G")
        if args.render_cls:
            eType = gdal.GDT_Byte
        else:
            eType = gdal.GDT_Float32
        dsm = dtmDriver.Create(args.output_dsm,
                               xsize=dtm.RasterXSize,
                               ysize=dtm.RasterYSize,
                               bands=1,
                               eType=eType,
                               options=options)
        if (projection):
            # georeference through affine geotransform
            dsm.SetProjection(projection)
            dsm.SetGeoTransform(transform)
        else:
            # georeference through GCPs
            dsm.SetGCPs(gcps, gcpProjection)
            gdal.GCPsToGeoTransform(gcps, transform)
        corners = [[0, 0], [0, dtm.RasterYSize],
                   [dtm.RasterXSize, dtm.RasterYSize], [dtm.RasterXSize, 0]]
        geoCorners = numpy.zeros((4, 2))
        for i, corner in enumerate(corners):
            geoCorners[i] = [
                transform[0] + corner[0] * transform[1] +
                corner[1] * transform[2], transform[3] +
                corner[0] * transform[4] + corner[1] * transform[5]
            ]
        dtmBounds[0] = numpy.min(geoCorners[:, 0])
        dtmBounds[1] = numpy.max(geoCorners[:, 0])
        dtmBounds[2] = numpy.min(geoCorners[:, 1])
        dtmBounds[3] = numpy.max(geoCorners[:, 1])

        if args.render_cls:
            # label for no building
            dtmRaster = numpy.full([dtm.RasterYSize, dtm.RasterXSize], 2)
            nodata = 0
        else:
            print("Reading the DTM {} size: ({}, {})\n"
                  "\tbounds: ({}, {}), ({}, {})...".format(
                      args.input_dtm, dtm.RasterXSize, dtm.RasterYSize,
                      dtmBounds[0], dtmBounds[1], dtmBounds[2], dtmBounds[3]))
            dtmRaster = dtm.GetRasterBand(1).ReadAsArray()
            nodata = dtm.GetRasterBand(1).GetNoDataValue()
        print("Nodata: {}".format(nodata))
    else:
        raise RuntimeError(
            "Driver {} does not supports Create().".format(dtmDriver))

    # read the buildings polydata, set Z as a scalar and project to XY plane
    print("Reading the buildings ...")
    # labels for buildings and elevated roads
    labels = [6, 17]
    if (args.input_vtp_path and os.path.isfile(args.input_vtp_path)):
        polyReader = vtk.vtkXMLPolyDataReader()
        polyReader.SetFileName(args.input_vtp_path)
        polyReader.Update()
        polyVtkList = [polyReader.GetOutput()]
    elif (args.input_obj_paths):
        # buildings start with numbers
        # optional elevated roads start with Road*.obj
        bldg_re = re.compile(".*/?[0-9][^/]*\\.obj")
        bldg_files = [f for f in args.input_obj_paths if bldg_re.match(f)]
        print(bldg_files)
        road_re = re.compile(".*/?Road[^/]*\\.obj")
        road_files = [f for f in args.input_obj_paths if road_re.match(f)]
        files = [bldg_files, road_files]
        files = [x for x in files if x]
        print(road_files)
        if len(files) >= 2:
            print("Found {} buildings and {} roads".format(
                len(files[0]), len(files[1])))
        elif len(files) == 1:
            print("Found {} buildings".format(len(files[0])))
        else:
            raise RuntimeError("No OBJ files found in {}".format(
                args.input_obj_paths))
        polyVtkList = []
        for category in range(len(files)):
            append = vtk.vtkAppendPolyData()
            for i, fileName in enumerate(files[category]):
                offset = [0.0, 0.0, 0.0]
                gdal_utils.read_offset(fileName, offset)
                print("Offset: {}".format(offset))
                transform = vtk.vtkTransform()
                transform.Translate(offset[0], offset[1], offset[2])

                objReader = vtk.vtkOBJReader()
                objReader.SetFileName(fileName)
                transformFilter = vtk.vtkTransformFilter()
                transformFilter.SetTransform(transform)
                transformFilter.SetInputConnection(objReader.GetOutputPort())
                append.AddInputConnection(transformFilter.GetOutputPort())
            append.Update()
            polyVtkList.append(append.GetOutput())
    else:
        raise RuntimeError(
            "Must provide either --input_vtp_path, or --input_obj_paths")

    arrayName = "Elevation"
    append = vtk.vtkAppendPolyData()
    for category in range(len(polyVtkList)):
        poly = dsa.WrapDataObject(polyVtkList[category])
        polyElevation = poly.Points[:, 2]
        if args.render_cls:
            # label for buildings
            polyElevation[:] = labels[category]
        polyElevationVtk = numpy_support.numpy_to_vtk(polyElevation)
        polyElevationVtk.SetName(arrayName)
        poly.PointData.SetScalars(polyElevationVtk)
        append.AddInputDataObject(polyVtkList[category])
    append.Update()

    # Create the RenderWindow, Renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.OffScreenRenderingOn()
    renWin.SetSize(dtm.RasterXSize, dtm.RasterYSize)
    renWin.SetMultiSamples(0)
    renWin.AddRenderer(ren)

    # show the buildings
    trisBuildingsFilter = vtk.vtkTriangleFilter()
    trisBuildingsFilter.SetInputDataObject(append.GetOutput())
    trisBuildingsFilter.Update()

    p2cBuildings = vtk.vtkPointDataToCellData()
    p2cBuildings.SetInputConnection(trisBuildingsFilter.GetOutputPort())
    p2cBuildings.PassPointDataOn()
    p2cBuildings.Update()
    buildingsScalarRange = p2cBuildings.GetOutput().GetCellData().GetScalars(
    ).GetRange()

    if (args.debug):
        polyWriter = vtk.vtkXMLPolyDataWriter()
        polyWriter.SetFileName("p2c.vtp")
        polyWriter.SetInputConnection(p2cBuildings.GetOutputPort())
        polyWriter.Write()

    buildingsMapper = vtk.vtkPolyDataMapper()
    buildingsMapper.SetInputDataObject(p2cBuildings.GetOutput())

    buildingsActor = vtk.vtkActor()
    buildingsActor.SetMapper(buildingsMapper)
    ren.AddActor(buildingsActor)

    if (args.render_png):
        print("Render into a PNG ...")
        # Show the terrain.
        print("Converting the DTM into a surface ...")
        # read the DTM as a VTK object
        dtmReader = vtk.vtkGDALRasterReader()
        dtmReader.SetFileName(args.input_dtm)
        dtmReader.Update()
        dtmVtk = dtmReader.GetOutput()

        # Convert the terrain into a polydata.
        surface = vtk.vtkImageDataGeometryFilter()
        surface.SetInputDataObject(dtmVtk)

        # Make sure the polygons are planar, so need to use triangles.
        tris = vtk.vtkTriangleFilter()
        tris.SetInputConnection(surface.GetOutputPort())

        # Warp the surface by scalar values
        warp = vtk.vtkWarpScalar()
        warp.SetInputConnection(tris.GetOutputPort())
        warp.SetScaleFactor(1)
        warp.UseNormalOn()
        warp.SetNormal(0, 0, 1)
        warp.Update()
        dsmScalarRange = warp.GetOutput().GetPointData().GetScalars().GetRange(
        )

        dtmMapper = vtk.vtkPolyDataMapper()
        dtmMapper.SetInputConnection(warp.GetOutputPort())
        dtmActor = vtk.vtkActor()
        dtmActor.SetMapper(dtmMapper)
        ren.AddActor(dtmActor)

        ren.ResetCamera()
        camera = ren.GetActiveCamera()
        camera.ParallelProjectionOn()
        camera.SetParallelScale((dtmBounds[3] - dtmBounds[2]) / 2)

        if (args.buildings_only):
            scalarRange = buildingsScalarRange
        else:
            scalarRange = [
                min(dsmScalarRange[0], buildingsScalarRange[0]),
                max(dsmScalarRange[1], buildingsScalarRange[1])
            ]
        lut = vtk.vtkColorTransferFunction()
        lut.AddRGBPoint(scalarRange[0], 0.23, 0.30, 0.75)
        lut.AddRGBPoint((scalarRange[0] + scalarRange[1]) / 2, 0.86, 0.86,
                        0.86)
        lut.AddRGBPoint(scalarRange[1], 0.70, 0.02, 0.15)

        dtmMapper.SetLookupTable(lut)
        dtmMapper.SetColorModeToMapScalars()
        buildingsMapper.SetLookupTable(lut)
        if (args.buildings_only):
            ren.RemoveActor(dtmActor)

        renWin.Render()
        windowToImageFilter = vtk.vtkWindowToImageFilter()
        windowToImageFilter.SetInput(renWin)
        windowToImageFilter.SetInputBufferTypeToRGBA()
        windowToImageFilter.ReadFrontBufferOff()
        windowToImageFilter.Update()

        writerPng = vtk.vtkPNGWriter()
        writerPng.SetFileName(args.output_dsm + ".png")
        writerPng.SetInputConnection(windowToImageFilter.GetOutputPort())
        writerPng.Write()
    else:
        print("Render into a floating point buffer ...")

        ren.ResetCamera()
        camera = ren.GetActiveCamera()
        camera.ParallelProjectionOn()
        camera.SetParallelScale((dtmBounds[3] - dtmBounds[2]) / 2)
        distance = camera.GetDistance()
        focalPoint = [(dtmBounds[0] + dtmBounds[1]) * 0.5,
                      (dtmBounds[3] + dtmBounds[2]) * 0.5,
                      (buildingsScalarRange[0] + buildingsScalarRange[1]) * 0.5
                      ]
        position = [focalPoint[0], focalPoint[1], focalPoint[2] + distance]
        camera.SetFocalPoint(focalPoint)
        camera.SetPosition(position)

        valuePass = vtk.vtkValuePass()
        valuePass.SetRenderingMode(vtk.vtkValuePass.FLOATING_POINT)
        # use the default scalar for point data
        valuePass.SetInputComponentToProcess(0)
        valuePass.SetInputArrayToProcess(
            vtk.VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, arrayName)
        passes = vtk.vtkRenderPassCollection()
        passes.AddItem(valuePass)
        sequence = vtk.vtkSequencePass()
        sequence.SetPasses(passes)
        cameraPass = vtk.vtkCameraPass()
        cameraPass.SetDelegatePass(sequence)
        ren.SetPass(cameraPass)
        # We have to render the points first, otherwise we get a segfault.
        renWin.Render()
        valuePass.SetInputArrayToProcess(
            vtk.VTK_SCALAR_MODE_USE_CELL_FIELD_DATA, arrayName)
        renWin.Render()
        elevationFlatVtk = valuePass.GetFloatImageDataArray(ren)
        valuePass.ReleaseGraphicsResources(renWin)

        print("Writing the DSM ...")
        elevationFlat = numpy_support.vtk_to_numpy(elevationFlatVtk)
        # VTK X,Y corresponds to numpy cols,rows. VTK stores arrays
        # in Fortran order.
        elevationTranspose = numpy.reshape(elevationFlat,
                                           [dtm.RasterXSize, dtm.RasterYSize],
                                           "F")
        # changes from cols, rows to rows,cols.
        elevation = numpy.transpose(elevationTranspose)
        # numpy rows increase as you go down, Y for VTK images increases as you go up
        elevation = numpy.flip(elevation, 0)
        if args.buildings_only:
            dsmElevation = elevation
        else:
            # elevation has nans in places other than buildings
            dsmElevation = numpy.fmax(dtmRaster, elevation)
        dsm.GetRasterBand(1).WriteArray(dsmElevation)
        if nodata:
            dsm.GetRasterBand(1).SetNoDataValue(nodata)
示例#34
0
文件: dem.py 项目: 151706061/VTK
demModel.Update()
catch.catch(globals(),"""#demModel.Print()""")
lo = expr.expr(globals(), locals(),["Scale","*","lindex(demModel.GetElevationBounds(),0)"])
hi = expr.expr(globals(), locals(),["Scale","*","lindex(demModel.GetElevationBounds(),1)"])
demActor = vtk.vtkLODActor()
# create a pipeline for each lod mapper
lods = "4 8 16"
for lod in lods.split():
    locals()[get_variable_name("shrink", lod, "")] = vtk.vtkImageShrink3D()
    locals()[get_variable_name("shrink", lod, "")].SetShrinkFactors(expr.expr(globals(), locals(),["int","(","lod",")"]),expr.expr(globals(), locals(),["int","(","lod",")"]),1)
    locals()[get_variable_name("shrink", lod, "")].SetInputConnection(demModel.GetOutputPort())
    locals()[get_variable_name("shrink", lod, "")].AveragingOn()
    locals()[get_variable_name("geom", lod, "")] = vtk.vtkImageDataGeometryFilter()
    locals()[get_variable_name("geom", lod, "")].SetInputConnection(locals()[get_variable_name("shrink", lod, "")].GetOutputPort())
    locals()[get_variable_name("geom", lod, "")].ReleaseDataFlagOn()
    locals()[get_variable_name("warp", lod, "")] = vtk.vtkWarpScalar()
    locals()[get_variable_name("warp", lod, "")].SetInputConnection(locals()[get_variable_name("geom", lod, "")].GetOutputPort())
    locals()[get_variable_name("warp", lod, "")].SetNormal(0,0,1)
    locals()[get_variable_name("warp", lod, "")].UseNormalOn()
    locals()[get_variable_name("warp", lod, "")].SetScaleFactor(Scale)
    locals()[get_variable_name("warp", lod, "")].ReleaseDataFlagOn()
    locals()[get_variable_name("elevation", lod, "")] = vtk.vtkElevationFilter()
    locals()[get_variable_name("elevation", lod, "")].SetInputConnection(locals()[get_variable_name("warp", lod, "")].GetOutputPort())
    locals()[get_variable_name("elevation", lod, "")].SetLowPoint(0,0,lo)
    locals()[get_variable_name("elevation", lod, "")].SetHighPoint(0,0,hi)
    locals()[get_variable_name("elevation", lod, "")].SetScalarRange(lo,hi)
    locals()[get_variable_name("elevation", lod, "")].ReleaseDataFlagOn()
    locals()[get_variable_name("toPoly", lod, "")] = vtk.vtkCastToConcrete()
    locals()[get_variable_name("toPoly", lod, "")].SetInputConnection(locals()[get_variable_name("elevation", lod, "")].GetOutputPort())
    locals()[get_variable_name("normals", lod, "")] = vtk.vtkPolyDataNormals()
    locals()[get_variable_name("normals", lod, "")].SetInputConnection(locals()[get_variable_name("toPoly", lod, "")].GetOutputPort())
示例#35
0
#streamer.SetStartPosition(0.18474886E+01, 0.12918899E+00, 0.00000000E+00)
streamer.SetSource(seedFilter.GetOutput())
streamer.SetMaximumPropagation(160000.0)
#streamer.SetMaximumPropagationUnitToTimeUnit()
streamer.SetInitialIntegrationStep(1.0)
#streamer.SetInitialIntegrationStepUnitToCellLengthUnit()
streamer.SetIntegrationDirectionToBoth()
streamer.SetIntegrator(integ)
#
streamTube = vtk.vtkTubeFilter()
streamTube.SetInputConnection(streamer.GetOutputPort())
#streamTube.SetInputArrayToProcess(1,0,0,vtkDataObject::FIELD_ASSOCIATION_POINTS, vectors)
streamTube.SetRadius(5000.0)
streamTube.SetNumberOfSides(12)

streamWarp = vtk.vtkWarpScalar()
streamWarp.SetInputConnection(streamTube.GetOutputPort())
streamWarp.SetNormal(0.0, 0.0, 1.0)
streamWarp.UseNormalOn()
streamWarp.SetScaleFactor(10000.0)

mapStreamTube = vtk.vtkPolyDataMapper()
mapStreamTube.SetInputConnection(streamWarp.GetOutputPort())
#mapStreamTube.SetInputConnection(streamer.GetOutputPort())
#mapStreamTube.SetInputConnection(streamTube.GetOutputPort())
mapStreamTube.SetScalarRange(
    meshReader.GetOutput().GetPointData().GetScalars().GetRange())

mapStreamTube.SetLookupTable(lut)
streamTubeActor = vtk.vtkActor()
streamTubeActor.SetMapper(mapStreamTube)
示例#36
0
(p_bot, p_top) = map(float, opts.prts.split(","))
bot_elev_array = flat_bot.GetPointData().GetArray("Elevation")
top_elev_array = bot_mesh_with_top_elev.GetPointData().GetArray("Elevation")
final_z = vtk.vtkDoubleArray()
final_z.SetNumberOfValues(flat_bot.GetNumberOfPoints())
final_z.SetName("Elevation")
for ptid in range(flat_bot.GetNumberOfPoints()):
    final_z.SetValue(
        ptid,
        p_bot * bot_elev_array.GetValue(ptid) +
        p_top * top_elev_array.GetValue(ptid))
bot_mesh_with_top_elev.GetPointData().RemoveArray("Elevation")
bot_mesh_with_top_elev.GetPointData().AddArray(final_z)

if opts.verbose: print "Warping the elevation values to z"
bot_with_z = vtk.vtkWarpScalar()
bot_with_z.SetInput(bot_mesh_with_top_elev)
bot_with_z.SetInputArrayToProcess(0, 0, 0, 0, "Elevation")
bot_with_z.Update()
bot_with_z = bot_with_z.GetOutput()

if bot_with_z.GetPointData().GetArray("vtkValidPointMask").GetRange()[0] < 1:
    # there are some invalid points
    if opts.verbose:
        print "**** Incompatible meshes produced invalid points ****"
    if opts.verbose: print "Removing invalid points"
    only_valid = vtk.vtkThreshold()
    only_valid.SetInput(bot_with_z)
    only_valid.SetInputArrayToProcess(0, 0, 0, 0, "vtkValidPointMask")
    only_valid.ThresholdBetween(0.5, 1.5)
    only_valid.Update()
    def testSphereWidget(self):

        # This example demonstrates how to use the vtkSphereWidget to control the
        # position of a light.

        # These are the pre-recorded events
        Recording = \
           "# StreamVersion 1\n\
            CharEvent 23 266 0 0 105 1 i\n\
            KeyReleaseEvent 23 266 0 0 105 1 i\n\
            EnterEvent 69 294 0 0 0 0 i\n\
            MouseMoveEvent 69 294 0 0 0 0 i\n\
            MouseMoveEvent 68 293 0 0 0 0 i\n\
            MouseMoveEvent 67 292 0 0 0 0 i\n\
            MouseMoveEvent 66 289 0 0 0 0 i\n\
            MouseMoveEvent 66 282 0 0 0 0 i\n\
            MouseMoveEvent 66 271 0 0 0 0 i\n\
            MouseMoveEvent 69 253 0 0 0 0 i\n\
            MouseMoveEvent 71 236 0 0 0 0 i\n\
            MouseMoveEvent 74 219 0 0 0 0 i\n\
            MouseMoveEvent 76 208 0 0 0 0 i\n\
            MouseMoveEvent 78 190 0 0 0 0 i\n\
            MouseMoveEvent 78 173 0 0 0 0 i\n\
            MouseMoveEvent 77 162 0 0 0 0 i\n\
            MouseMoveEvent 77 151 0 0 0 0 i\n\
            MouseMoveEvent 77 139 0 0 0 0 i\n\
            MouseMoveEvent 76 125 0 0 0 0 i\n\
            MouseMoveEvent 73 114 0 0 0 0 i\n\
            MouseMoveEvent 73 106 0 0 0 0 i\n\
            MouseMoveEvent 73 101 0 0 0 0 i\n\
            MouseMoveEvent 72 95 0 0 0 0 i\n\
            MouseMoveEvent 72 92 0 0 0 0 i\n\
            MouseMoveEvent 70 89 0 0 0 0 i\n\
            MouseMoveEvent 69 86 0 0 0 0 i\n\
            MouseMoveEvent 67 84 0 0 0 0 i\n\
            MouseMoveEvent 65 81 0 0 0 0 i\n\
            MouseMoveEvent 60 79 0 0 0 0 i\n\
            MouseMoveEvent 59 79 0 0 0 0 i\n\
            MouseMoveEvent 58 79 0 0 0 0 i\n\
            MouseMoveEvent 57 78 0 0 0 0 i\n\
            MouseMoveEvent 55 78 0 0 0 0 i\n\
            MouseMoveEvent 54 77 0 0 0 0 i\n\
            LeftButtonPressEvent 54 77 0 0 0 0 i\n\
            MouseMoveEvent 61 79 0 0 0 0 i\n\
            MouseMoveEvent 67 83 0 0 0 0 i\n\
            MouseMoveEvent 72 88 0 0 0 0 i\n\
            MouseMoveEvent 77 90 0 0 0 0 i\n\
            MouseMoveEvent 78 91 0 0 0 0 i\n\
            MouseMoveEvent 80 92 0 0 0 0 i\n\
            MouseMoveEvent 84 93 0 0 0 0 i\n\
            MouseMoveEvent 85 94 0 0 0 0 i\n\
            MouseMoveEvent 88 97 0 0 0 0 i\n\
            MouseMoveEvent 90 100 0 0 0 0 i\n\
            MouseMoveEvent 92 102 0 0 0 0 i\n\
            MouseMoveEvent 94 103 0 0 0 0 i\n\
            MouseMoveEvent 97 105 0 0 0 0 i\n\
            MouseMoveEvent 101 107 0 0 0 0 i\n\
            MouseMoveEvent 102 109 0 0 0 0 i\n\
            MouseMoveEvent 104 111 0 0 0 0 i\n\
            MouseMoveEvent 108 113 0 0 0 0 i\n\
            MouseMoveEvent 112 115 0 0 0 0 i\n\
            MouseMoveEvent 118 119 0 0 0 0 i\n\
            MouseMoveEvent 118 120 0 0 0 0 i\n\
            MouseMoveEvent 118 123 0 0 0 0 i\n\
            MouseMoveEvent 120 125 0 0 0 0 i\n\
            MouseMoveEvent 122 128 0 0 0 0 i\n\
            MouseMoveEvent 123 129 0 0 0 0 i\n\
            MouseMoveEvent 125 132 0 0 0 0 i\n\
            MouseMoveEvent 125 134 0 0 0 0 i\n\
            MouseMoveEvent 127 138 0 0 0 0 i\n\
            MouseMoveEvent 127 142 0 0 0 0 i\n\
            MouseMoveEvent 127 147 0 0 0 0 i\n\
            MouseMoveEvent 126 152 0 0 0 0 i\n\
            MouseMoveEvent 126 155 0 0 0 0 i\n\
            MouseMoveEvent 125 160 0 0 0 0 i\n\
            MouseMoveEvent 125 167 0 0 0 0 i\n\
            MouseMoveEvent 125 169 0 0 0 0 i\n\
            MouseMoveEvent 125 174 0 0 0 0 i\n\
            MouseMoveEvent 122 179 0 0 0 0 i\n\
            MouseMoveEvent 120 183 0 0 0 0 i\n\
            MouseMoveEvent 116 187 0 0 0 0 i\n\
            MouseMoveEvent 113 192 0 0 0 0 i\n\
            MouseMoveEvent 113 193 0 0 0 0 i\n\
            MouseMoveEvent 111 195 0 0 0 0 i\n\
            MouseMoveEvent 108 198 0 0 0 0 i\n\
            MouseMoveEvent 106 200 0 0 0 0 i\n\
            MouseMoveEvent 104 202 0 0 0 0 i\n\
            MouseMoveEvent 103 203 0 0 0 0 i\n\
            MouseMoveEvent 99 205 0 0 0 0 i\n\
            MouseMoveEvent 97 207 0 0 0 0 i\n\
            MouseMoveEvent 94 208 0 0 0 0 i\n\
            MouseMoveEvent 91 210 0 0 0 0 i\n\
            MouseMoveEvent 89 211 0 0 0 0 i\n\
            MouseMoveEvent 86 211 0 0 0 0 i\n\
            MouseMoveEvent 84 211 0 0 0 0 i\n\
            MouseMoveEvent 80 211 0 0 0 0 i\n\
            MouseMoveEvent 77 211 0 0 0 0 i\n\
            MouseMoveEvent 75 211 0 0 0 0 i\n\
            MouseMoveEvent 71 211 0 0 0 0 i\n\
            MouseMoveEvent 68 211 0 0 0 0 i\n\
            MouseMoveEvent 66 210 0 0 0 0 i\n\
            MouseMoveEvent 62 210 0 0 0 0 i\n\
            MouseMoveEvent 58 209 0 0 0 0 i\n\
            MouseMoveEvent 54 207 0 0 0 0 i\n\
            MouseMoveEvent 52 204 0 0 0 0 i\n\
            MouseMoveEvent 51 203 0 0 0 0 i\n\
            MouseMoveEvent 51 200 0 0 0 0 i\n\
            MouseMoveEvent 48 196 0 0 0 0 i\n\
            MouseMoveEvent 45 187 0 0 0 0 i\n\
            MouseMoveEvent 45 181 0 0 0 0 i\n\
            MouseMoveEvent 44 168 0 0 0 0 i\n\
            MouseMoveEvent 40 161 0 0 0 0 i\n\
            MouseMoveEvent 39 154 0 0 0 0 i\n\
            MouseMoveEvent 38 146 0 0 0 0 i\n\
            MouseMoveEvent 35 131 0 0 0 0 i\n\
            MouseMoveEvent 34 121 0 0 0 0 i\n\
            MouseMoveEvent 34 110 0 0 0 0 i\n\
            MouseMoveEvent 34 103 0 0 0 0 i\n\
            MouseMoveEvent 34 91 0 0 0 0 i\n\
            MouseMoveEvent 34 86 0 0 0 0 i\n\
            MouseMoveEvent 34 73 0 0 0 0 i\n\
            MouseMoveEvent 35 66 0 0 0 0 i\n\
            MouseMoveEvent 37 60 0 0 0 0 i\n\
            MouseMoveEvent 37 53 0 0 0 0 i\n\
            MouseMoveEvent 38 50 0 0 0 0 i\n\
            MouseMoveEvent 38 48 0 0 0 0 i\n\
            MouseMoveEvent 41 45 0 0 0 0 i\n\
            MouseMoveEvent 43 45 0 0 0 0 i\n\
            MouseMoveEvent 44 45 0 0 0 0 i\n\
            MouseMoveEvent 47 43 0 0 0 0 i\n\
            MouseMoveEvent 51 44 0 0 0 0 i\n\
            MouseMoveEvent 54 44 0 0 0 0 i\n\
            MouseMoveEvent 55 44 0 0 0 0 i\n\
            MouseMoveEvent 59 44 0 0 0 0 i\n\
            MouseMoveEvent 64 44 0 0 0 0 i\n\
            MouseMoveEvent 67 44 0 0 0 0 i\n\
            MouseMoveEvent 68 44 0 0 0 0 i\n\
            MouseMoveEvent 71 44 0 0 0 0 i\n\
            MouseMoveEvent 74 44 0 0 0 0 i\n\
            MouseMoveEvent 77 44 0 0 0 0 i\n\
            MouseMoveEvent 80 45 0 0 0 0 i\n\
            MouseMoveEvent 81 45 0 0 0 0 i\n\
            MouseMoveEvent 85 49 0 0 0 0 i\n\
            MouseMoveEvent 89 50 0 0 0 0 i\n\
            MouseMoveEvent 94 52 0 0 0 0 i\n\
            MouseMoveEvent 99 56 0 0 0 0 i\n\
            MouseMoveEvent 104 58 0 0 0 0 i\n\
            MouseMoveEvent 107 61 0 0 0 0 i\n\
            MouseMoveEvent 109 63 0 0 0 0 i\n\
            MouseMoveEvent 109 67 0 0 0 0 i\n\
            MouseMoveEvent 111 83 0 0 0 0 i\n\
            MouseMoveEvent 113 86 0 0 0 0 i\n\
            MouseMoveEvent 113 87 0 0 0 0 i\n\
            MouseMoveEvent 113 89 0 0 0 0 i\n\
            MouseMoveEvent 112 93 0 0 0 0 i\n\
            MouseMoveEvent 112 97 0 0 0 0 i\n\
            MouseMoveEvent 111 104 0 0 0 0 i\n\
            MouseMoveEvent 112 108 0 0 0 0 i\n\
            MouseMoveEvent 116 115 0 0 0 0 i\n\
            MouseMoveEvent 116 123 0 0 0 0 i\n\
            MouseMoveEvent 116 129 0 0 0 0 i\n\
            MouseMoveEvent 119 138 0 0 0 0 i\n\
            MouseMoveEvent 122 141 0 0 0 0 i\n\
            MouseMoveEvent 127 148 0 0 0 0 i\n\
            MouseMoveEvent 128 161 0 0 0 0 i\n\
            MouseMoveEvent 131 166 0 0 0 0 i\n\
            MouseMoveEvent 134 168 0 0 0 0 i\n\
            MouseMoveEvent 135 171 0 0 0 0 i\n\
            MouseMoveEvent 134 174 0 0 0 0 i\n\
            MouseMoveEvent 132 176 0 0 0 0 i\n\
            MouseMoveEvent 132 178 0 0 0 0 i\n\
            MouseMoveEvent 129 180 0 0 0 0 i\n\
            MouseMoveEvent 127 182 0 0 0 0 i\n\
            MouseMoveEvent 124 185 0 0 0 0 i\n\
            MouseMoveEvent 122 186 0 0 0 0 i\n\
            MouseMoveEvent 118 189 0 0 0 0 i\n\
            MouseMoveEvent 114 191 0 0 0 0 i\n\
            MouseMoveEvent 114 193 0 0 0 0 i\n\
            MouseMoveEvent 112 193 0 0 0 0 i\n\
            MouseMoveEvent 111 194 0 0 0 0 i\n\
            MouseMoveEvent 110 197 0 0 0 0 i\n\
            MouseMoveEvent 110 198 0 0 0 0 i\n\
            MouseMoveEvent 109 199 0 0 0 0 i\n\
            MouseMoveEvent 108 200 0 0 0 0 i\n\
            MouseMoveEvent 108 201 0 0 0 0 i\n\
            MouseMoveEvent 108 202 0 0 0 0 i\n\
            MouseMoveEvent 108 203 0 0 0 0 i\n\
            MouseMoveEvent 104 206 0 0 0 0 i\n\
            LeftButtonReleaseEvent 104 206 0 0 0 0 i\n\
            MouseMoveEvent 104 205 0 0 0 0 i\n\
            MouseMoveEvent 104 204 0 0 0 0 i\n\
            MouseMoveEvent 105 205 0 0 0 0 i\n\
            MouseMoveEvent 105 206 0 0 0 0 i\n\
        "

        # Start by loading some data.
        #
        dem = vtk.vtkDEMReader()
        dem.SetFileName(VTK_DATA_ROOT + "/Data/SainteHelens.dem")
        dem.Update()

        Scale = 2
        lut = vtk.vtkLookupTable()
        lut.SetHueRange(0.6, 0)
        lut.SetSaturationRange(1.0, 0)
        lut.SetValueRange(0.5, 1.0)
        lo = Scale * dem.GetElevationBounds()[0]

        hi = Scale * dem.GetElevationBounds()[1]


        shrink = vtk.vtkImageShrink3D()
        shrink.SetShrinkFactors(4, 4, 1)
        shrink.SetInputConnection(dem.GetOutputPort())
        shrink.AveragingOn()

        geom = vtk.vtkImageDataGeometryFilter()
        geom.SetInputConnection(shrink.GetOutputPort())
        geom.ReleaseDataFlagOn()

        warp = vtk.vtkWarpScalar()
        warp.SetInputConnection(geom.GetOutputPort())
        warp.SetNormal(0, 0, 1)
        warp.UseNormalOn()
        warp.SetScaleFactor(Scale)
        warp.ReleaseDataFlagOn()

        elevation = vtk.vtkElevationFilter()
        elevation.SetInputConnection(warp.GetOutputPort())
        elevation.SetLowPoint(0, 0, lo)
        elevation.SetHighPoint(0, 0, hi)
        elevation.SetScalarRange(lo, hi)
        elevation.ReleaseDataFlagOn()

        normals = vtk.vtkPolyDataNormals()
        normals.SetInputConnection(elevation.GetOutputPort())
        normals.SetFeatureAngle(60)
        normals.ConsistencyOff()
        normals.SplittingOff()
        normals.ReleaseDataFlagOn()
        normals.Update()

        demMapper = vtk.vtkPolyDataMapper()
        demMapper.SetInputConnection(normals.GetOutputPort())
        demMapper.SetScalarRange(lo, hi)
        demMapper.SetLookupTable(lut)

        demActor = vtk.vtkActor()
        demActor.SetMapper(demMapper)

        # Create the RenderWindow, Renderer and both Actors
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.SetMultiSamples(0)
        renWin.AddRenderer(ren)
        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin)
        iRen.LightFollowCameraOff()
        #    iRen.SetInteractorStyle("")

        # The callback takes two arguments.
        # The first being the object that generates the event and
        # the second argument the event name (which is a string).
        def MoveLight(widget, event_string):
            light.SetPosition(rep.GetHandlePosition())

        # Associate the line widget with the interactor
        rep = vtk.vtkSphereRepresentation()
        rep.SetPlaceFactor(4)
        rep.PlaceWidget(normals.GetOutput().GetBounds())
        rep.HandleVisibilityOn()
        rep.SetRepresentationToWireframe()
        #  rep HandleVisibilityOff
        #  rep HandleTextOff
        sphereWidget = vtk.vtkSphereWidget2()
        sphereWidget.SetInteractor(iRen)
        sphereWidget.SetRepresentation(rep)
        #  sphereWidget.TranslationEnabledOff()
        #  sphereWidget.ScalingEnabledOff()
        sphereWidget.AddObserver("InteractionEvent", MoveLight)

        recorder = vtk.vtkInteractorEventRecorder()
        recorder.SetInteractor(iRen)
        #  recorder.SetFileName("c:/record.log")
        #  recorder.Record()
        recorder.ReadFromInputStringOn()
        recorder.SetInputString(Recording)

        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(demActor)
        ren.SetBackground(1, 1, 1)
        renWin.SetSize(300, 300)
        ren.SetBackground(0.1, 0.2, 0.4)

        cam1 = ren.GetActiveCamera()
        cam1.SetViewUp(0, 0, 1)
        cam1.SetFocalPoint(dem.GetOutput().GetCenter())
        cam1.SetPosition(1, 0, 0)
        ren.ResetCamera()
        cam1.Elevation(25)
        cam1.Azimuth(125)
        cam1.Zoom(1.25)

        light = vtk.vtkLight()
        light.SetFocalPoint(rep.GetCenter())
        light.SetPosition(rep.GetHandlePosition())
        ren.AddLight(light)

        iRen.Initialize()
        renWin.Render()

        # render the image
        renWin.Render()

        # Actually probe the data
        recorder.Play()

        img_file = "TestSphereWidget.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
示例#38
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
示例#39
0
    def testSphereWidget(self):

        # This example demonstrates how to use the vtkSphereWidget to control the
        # position of a light.

        # These are the pre-recorded events
        Recording = \
           "# StreamVersion 1\n\
            CharEvent 23 266 0 0 105 1 i\n\
            KeyReleaseEvent 23 266 0 0 105 1 i\n\
            EnterEvent 69 294 0 0 0 0 i\n\
            MouseMoveEvent 69 294 0 0 0 0 i\n\
            MouseMoveEvent 68 293 0 0 0 0 i\n\
            MouseMoveEvent 67 292 0 0 0 0 i\n\
            MouseMoveEvent 66 289 0 0 0 0 i\n\
            MouseMoveEvent 66 282 0 0 0 0 i\n\
            MouseMoveEvent 66 271 0 0 0 0 i\n\
            MouseMoveEvent 69 253 0 0 0 0 i\n\
            MouseMoveEvent 71 236 0 0 0 0 i\n\
            MouseMoveEvent 74 219 0 0 0 0 i\n\
            MouseMoveEvent 76 208 0 0 0 0 i\n\
            MouseMoveEvent 78 190 0 0 0 0 i\n\
            MouseMoveEvent 78 173 0 0 0 0 i\n\
            MouseMoveEvent 77 162 0 0 0 0 i\n\
            MouseMoveEvent 77 151 0 0 0 0 i\n\
            MouseMoveEvent 77 139 0 0 0 0 i\n\
            MouseMoveEvent 76 125 0 0 0 0 i\n\
            MouseMoveEvent 73 114 0 0 0 0 i\n\
            MouseMoveEvent 73 106 0 0 0 0 i\n\
            MouseMoveEvent 73 101 0 0 0 0 i\n\
            MouseMoveEvent 72 95 0 0 0 0 i\n\
            MouseMoveEvent 72 92 0 0 0 0 i\n\
            MouseMoveEvent 70 89 0 0 0 0 i\n\
            MouseMoveEvent 69 86 0 0 0 0 i\n\
            MouseMoveEvent 67 84 0 0 0 0 i\n\
            MouseMoveEvent 65 81 0 0 0 0 i\n\
            MouseMoveEvent 60 79 0 0 0 0 i\n\
            MouseMoveEvent 59 79 0 0 0 0 i\n\
            MouseMoveEvent 58 79 0 0 0 0 i\n\
            MouseMoveEvent 57 78 0 0 0 0 i\n\
            MouseMoveEvent 55 78 0 0 0 0 i\n\
            MouseMoveEvent 54 77 0 0 0 0 i\n\
            LeftButtonPressEvent 54 77 0 0 0 0 i\n\
            MouseMoveEvent 61 79 0 0 0 0 i\n\
            MouseMoveEvent 67 83 0 0 0 0 i\n\
            MouseMoveEvent 72 88 0 0 0 0 i\n\
            MouseMoveEvent 77 90 0 0 0 0 i\n\
            MouseMoveEvent 78 91 0 0 0 0 i\n\
            MouseMoveEvent 80 92 0 0 0 0 i\n\
            MouseMoveEvent 84 93 0 0 0 0 i\n\
            MouseMoveEvent 85 94 0 0 0 0 i\n\
            MouseMoveEvent 88 97 0 0 0 0 i\n\
            MouseMoveEvent 90 100 0 0 0 0 i\n\
            MouseMoveEvent 92 102 0 0 0 0 i\n\
            MouseMoveEvent 94 103 0 0 0 0 i\n\
            MouseMoveEvent 97 105 0 0 0 0 i\n\
            MouseMoveEvent 101 107 0 0 0 0 i\n\
            MouseMoveEvent 102 109 0 0 0 0 i\n\
            MouseMoveEvent 104 111 0 0 0 0 i\n\
            MouseMoveEvent 108 113 0 0 0 0 i\n\
            MouseMoveEvent 112 115 0 0 0 0 i\n\
            MouseMoveEvent 118 119 0 0 0 0 i\n\
            MouseMoveEvent 118 120 0 0 0 0 i\n\
            MouseMoveEvent 118 123 0 0 0 0 i\n\
            MouseMoveEvent 120 125 0 0 0 0 i\n\
            MouseMoveEvent 122 128 0 0 0 0 i\n\
            MouseMoveEvent 123 129 0 0 0 0 i\n\
            MouseMoveEvent 125 132 0 0 0 0 i\n\
            MouseMoveEvent 125 134 0 0 0 0 i\n\
            MouseMoveEvent 127 138 0 0 0 0 i\n\
            MouseMoveEvent 127 142 0 0 0 0 i\n\
            MouseMoveEvent 127 147 0 0 0 0 i\n\
            MouseMoveEvent 126 152 0 0 0 0 i\n\
            MouseMoveEvent 126 155 0 0 0 0 i\n\
            MouseMoveEvent 125 160 0 0 0 0 i\n\
            MouseMoveEvent 125 167 0 0 0 0 i\n\
            MouseMoveEvent 125 169 0 0 0 0 i\n\
            MouseMoveEvent 125 174 0 0 0 0 i\n\
            MouseMoveEvent 122 179 0 0 0 0 i\n\
            MouseMoveEvent 120 183 0 0 0 0 i\n\
            MouseMoveEvent 116 187 0 0 0 0 i\n\
            MouseMoveEvent 113 192 0 0 0 0 i\n\
            MouseMoveEvent 113 193 0 0 0 0 i\n\
            MouseMoveEvent 111 195 0 0 0 0 i\n\
            MouseMoveEvent 108 198 0 0 0 0 i\n\
            MouseMoveEvent 106 200 0 0 0 0 i\n\
            MouseMoveEvent 104 202 0 0 0 0 i\n\
            MouseMoveEvent 103 203 0 0 0 0 i\n\
            MouseMoveEvent 99 205 0 0 0 0 i\n\
            MouseMoveEvent 97 207 0 0 0 0 i\n\
            MouseMoveEvent 94 208 0 0 0 0 i\n\
            MouseMoveEvent 91 210 0 0 0 0 i\n\
            MouseMoveEvent 89 211 0 0 0 0 i\n\
            MouseMoveEvent 86 211 0 0 0 0 i\n\
            MouseMoveEvent 84 211 0 0 0 0 i\n\
            MouseMoveEvent 80 211 0 0 0 0 i\n\
            MouseMoveEvent 77 211 0 0 0 0 i\n\
            MouseMoveEvent 75 211 0 0 0 0 i\n\
            MouseMoveEvent 71 211 0 0 0 0 i\n\
            MouseMoveEvent 68 211 0 0 0 0 i\n\
            MouseMoveEvent 66 210 0 0 0 0 i\n\
            MouseMoveEvent 62 210 0 0 0 0 i\n\
            MouseMoveEvent 58 209 0 0 0 0 i\n\
            MouseMoveEvent 54 207 0 0 0 0 i\n\
            MouseMoveEvent 52 204 0 0 0 0 i\n\
            MouseMoveEvent 51 203 0 0 0 0 i\n\
            MouseMoveEvent 51 200 0 0 0 0 i\n\
            MouseMoveEvent 48 196 0 0 0 0 i\n\
            MouseMoveEvent 45 187 0 0 0 0 i\n\
            MouseMoveEvent 45 181 0 0 0 0 i\n\
            MouseMoveEvent 44 168 0 0 0 0 i\n\
            MouseMoveEvent 40 161 0 0 0 0 i\n\
            MouseMoveEvent 39 154 0 0 0 0 i\n\
            MouseMoveEvent 38 146 0 0 0 0 i\n\
            MouseMoveEvent 35 131 0 0 0 0 i\n\
            MouseMoveEvent 34 121 0 0 0 0 i\n\
            MouseMoveEvent 34 110 0 0 0 0 i\n\
            MouseMoveEvent 34 103 0 0 0 0 i\n\
            MouseMoveEvent 34 91 0 0 0 0 i\n\
            MouseMoveEvent 34 86 0 0 0 0 i\n\
            MouseMoveEvent 34 73 0 0 0 0 i\n\
            MouseMoveEvent 35 66 0 0 0 0 i\n\
            MouseMoveEvent 37 60 0 0 0 0 i\n\
            MouseMoveEvent 37 53 0 0 0 0 i\n\
            MouseMoveEvent 38 50 0 0 0 0 i\n\
            MouseMoveEvent 38 48 0 0 0 0 i\n\
            MouseMoveEvent 41 45 0 0 0 0 i\n\
            MouseMoveEvent 43 45 0 0 0 0 i\n\
            MouseMoveEvent 44 45 0 0 0 0 i\n\
            MouseMoveEvent 47 43 0 0 0 0 i\n\
            MouseMoveEvent 51 44 0 0 0 0 i\n\
            MouseMoveEvent 54 44 0 0 0 0 i\n\
            MouseMoveEvent 55 44 0 0 0 0 i\n\
            MouseMoveEvent 59 44 0 0 0 0 i\n\
            MouseMoveEvent 64 44 0 0 0 0 i\n\
            MouseMoveEvent 67 44 0 0 0 0 i\n\
            MouseMoveEvent 68 44 0 0 0 0 i\n\
            MouseMoveEvent 71 44 0 0 0 0 i\n\
            MouseMoveEvent 74 44 0 0 0 0 i\n\
            MouseMoveEvent 77 44 0 0 0 0 i\n\
            MouseMoveEvent 80 45 0 0 0 0 i\n\
            MouseMoveEvent 81 45 0 0 0 0 i\n\
            MouseMoveEvent 85 49 0 0 0 0 i\n\
            MouseMoveEvent 89 50 0 0 0 0 i\n\
            MouseMoveEvent 94 52 0 0 0 0 i\n\
            MouseMoveEvent 99 56 0 0 0 0 i\n\
            MouseMoveEvent 104 58 0 0 0 0 i\n\
            MouseMoveEvent 107 61 0 0 0 0 i\n\
            MouseMoveEvent 109 63 0 0 0 0 i\n\
            MouseMoveEvent 109 67 0 0 0 0 i\n\
            MouseMoveEvent 111 83 0 0 0 0 i\n\
            MouseMoveEvent 113 86 0 0 0 0 i\n\
            MouseMoveEvent 113 87 0 0 0 0 i\n\
            MouseMoveEvent 113 89 0 0 0 0 i\n\
            MouseMoveEvent 112 93 0 0 0 0 i\n\
            MouseMoveEvent 112 97 0 0 0 0 i\n\
            MouseMoveEvent 111 104 0 0 0 0 i\n\
            MouseMoveEvent 112 108 0 0 0 0 i\n\
            MouseMoveEvent 116 115 0 0 0 0 i\n\
            MouseMoveEvent 116 123 0 0 0 0 i\n\
            MouseMoveEvent 116 129 0 0 0 0 i\n\
            MouseMoveEvent 119 138 0 0 0 0 i\n\
            MouseMoveEvent 122 141 0 0 0 0 i\n\
            MouseMoveEvent 127 148 0 0 0 0 i\n\
            MouseMoveEvent 128 161 0 0 0 0 i\n\
            MouseMoveEvent 131 166 0 0 0 0 i\n\
            MouseMoveEvent 134 168 0 0 0 0 i\n\
            MouseMoveEvent 135 171 0 0 0 0 i\n\
            MouseMoveEvent 134 174 0 0 0 0 i\n\
            MouseMoveEvent 132 176 0 0 0 0 i\n\
            MouseMoveEvent 132 178 0 0 0 0 i\n\
            MouseMoveEvent 129 180 0 0 0 0 i\n\
            MouseMoveEvent 127 182 0 0 0 0 i\n\
            MouseMoveEvent 124 185 0 0 0 0 i\n\
            MouseMoveEvent 122 186 0 0 0 0 i\n\
            MouseMoveEvent 118 189 0 0 0 0 i\n\
            MouseMoveEvent 114 191 0 0 0 0 i\n\
            MouseMoveEvent 114 193 0 0 0 0 i\n\
            MouseMoveEvent 112 193 0 0 0 0 i\n\
            MouseMoveEvent 111 194 0 0 0 0 i\n\
            MouseMoveEvent 110 197 0 0 0 0 i\n\
            MouseMoveEvent 110 198 0 0 0 0 i\n\
            MouseMoveEvent 109 199 0 0 0 0 i\n\
            MouseMoveEvent 108 200 0 0 0 0 i\n\
            MouseMoveEvent 108 201 0 0 0 0 i\n\
            MouseMoveEvent 108 202 0 0 0 0 i\n\
            MouseMoveEvent 108 203 0 0 0 0 i\n\
            MouseMoveEvent 104 206 0 0 0 0 i\n\
            LeftButtonReleaseEvent 104 206 0 0 0 0 i\n\
            MouseMoveEvent 104 205 0 0 0 0 i\n\
            MouseMoveEvent 104 204 0 0 0 0 i\n\
            MouseMoveEvent 105 205 0 0 0 0 i\n\
            MouseMoveEvent 105 206 0 0 0 0 i\n\
        "

        # Start by loading some data.
        #
        dem = vtk.vtkDEMReader()
        dem.SetFileName(VTK_DATA_ROOT + "/Data/SainteHelens.dem")
        dem.Update()

        Scale = 2
        lut = vtk.vtkLookupTable()
        lut.SetHueRange(0.6, 0)
        lut.SetSaturationRange(1.0, 0)
        lut.SetValueRange(0.5, 1.0)
        lo = Scale * dem.GetElevationBounds()[0]

        hi = Scale * dem.GetElevationBounds()[1]

        shrink = vtk.vtkImageShrink3D()
        shrink.SetShrinkFactors(4, 4, 1)
        shrink.SetInputConnection(dem.GetOutputPort())
        shrink.AveragingOn()

        geom = vtk.vtkImageDataGeometryFilter()
        geom.SetInputConnection(shrink.GetOutputPort())
        geom.ReleaseDataFlagOn()

        warp = vtk.vtkWarpScalar()
        warp.SetInputConnection(geom.GetOutputPort())
        warp.SetNormal(0, 0, 1)
        warp.UseNormalOn()
        warp.SetScaleFactor(Scale)
        warp.ReleaseDataFlagOn()

        elevation = vtk.vtkElevationFilter()
        elevation.SetInputConnection(warp.GetOutputPort())
        elevation.SetLowPoint(0, 0, lo)
        elevation.SetHighPoint(0, 0, hi)
        elevation.SetScalarRange(lo, hi)
        elevation.ReleaseDataFlagOn()

        normals = vtk.vtkPolyDataNormals()
        normals.SetInputConnection(elevation.GetOutputPort())
        normals.SetFeatureAngle(60)
        normals.ConsistencyOff()
        normals.SplittingOff()
        normals.ReleaseDataFlagOn()
        normals.Update()

        demMapper = vtk.vtkPolyDataMapper()
        demMapper.SetInputConnection(normals.GetOutputPort())
        demMapper.SetScalarRange(lo, hi)
        demMapper.SetLookupTable(lut)

        demActor = vtk.vtkActor()
        demActor.SetMapper(demMapper)

        # Create the RenderWindow, Renderer and both Actors
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.SetMultiSamples(0)
        renWin.AddRenderer(ren)
        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin)
        iRen.LightFollowCameraOff()

        #    iRen.SetInteractorStyle("")

        # The callback takes two arguments.
        # The first being the object that generates the event and
        # the second argument the event name (which is a string).
        def MoveLight(widget, event_string):
            light.SetPosition(rep.GetHandlePosition())

        # Associate the line widget with the interactor
        rep = vtk.vtkSphereRepresentation()
        rep.SetPlaceFactor(4)
        rep.PlaceWidget(normals.GetOutput().GetBounds())
        rep.HandleVisibilityOn()
        rep.SetRepresentationToWireframe()
        #  rep HandleVisibilityOff
        #  rep HandleTextOff
        sphereWidget = vtk.vtkSphereWidget2()
        sphereWidget.SetInteractor(iRen)
        sphereWidget.SetRepresentation(rep)
        #  sphereWidget.TranslationEnabledOff()
        #  sphereWidget.ScalingEnabledOff()
        sphereWidget.AddObserver("InteractionEvent", MoveLight)

        recorder = vtk.vtkInteractorEventRecorder()
        recorder.SetInteractor(iRen)
        #  recorder.SetFileName("c:/record.log")
        #  recorder.Record()
        recorder.ReadFromInputStringOn()
        recorder.SetInputString(Recording)

        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(demActor)
        ren.SetBackground(1, 1, 1)
        renWin.SetSize(300, 300)
        ren.SetBackground(0.1, 0.2, 0.4)

        cam1 = ren.GetActiveCamera()
        cam1.SetViewUp(0, 0, 1)
        cam1.SetFocalPoint(dem.GetOutput().GetCenter())
        cam1.SetPosition(1, 0, 0)
        ren.ResetCamera()
        cam1.Elevation(25)
        cam1.Azimuth(125)
        cam1.Zoom(1.25)

        light = vtk.vtkLight()
        light.SetFocalPoint(rep.GetCenter())
        light.SetPosition(rep.GetHandlePosition())
        ren.AddLight(light)

        iRen.Initialize()
        renWin.Render()

        # render the image
        renWin.Render()

        # Actually probe the data
        recorder.Play()

        img_file = "TestSphereWidget.png"
        vtk.test.Testing.compareImage(
            iRen.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()
示例#40
0
    def set_initial_display(self):
        if self.renwininter is None:
            self.renwininter = MEQ_QVTKRenderWindowInteractor(self.winsplitter)
            self.renwininter.setWhatsThis(rendering_control_instructions)
            self.renwin = self.renwininter.GetRenderWindow()
            self.inter = self.renwin.GetInteractor()
            self.winsplitter.insertWidget(0, self.renwininter)
            self.winsplitter.addWidget(self.v_box_controls)
            self.winsplitter.setSizes([500, 100])
            self.renwininter.show()

            # Paul Kemper suggested the following:
            camstyle = vtk.vtkInteractorStyleTrackballCamera()
            self.renwininter.SetInteractorStyle(camstyle)

        self.extents = self.image_array.GetDataExtent()
        self.spacing = self.image_array.GetDataSpacing()
        self.origin = self.image_array.GetDataOrigin()

        # An outline is shown for context.
        if self.warped_surface:
            self.index_selector.initWarpContextmenu()
            sx, sy, sz = self.image_array.GetDataSpacing()
            xMin, xMax, yMin, yMax, zMin, zMax = self.image_array.GetDataExtent(
            )
            xMin = sx * xMin
            xMax = sx * xMax
            yMin = sy * yMin
            yMax = sy * yMax
            self.scale_factor = 0.5 * (
                (xMax - xMin) +
                (yMax - yMin)) / (self.data_max - self.data_min)
            zMin = self.data_min * self.scale_factor
            zMax = self.data_max * self.scale_factor
            self.outline = vtk.vtkOutlineSource()
            self.outline.SetBounds(xMin, xMax, yMin, yMax, zMin, zMax)
        else:
            self.index_selector.init3DContextmenu()
            self.outline = vtk.vtkOutlineFilter()
            self.outline.SetInput(self.image_array.GetOutput())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInput(self.outline.GetOutput())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)

        # create blue to red color table
        self.lut = vtk.vtkLookupTable()
        self.lut.SetHueRange(0.6667, 0.0)
        self.lut.SetNumberOfColors(256)
        self.lut.Build()

        # here is where the 2-D image gets warped
        if self.warped_surface:
            geometry = vtk.vtkImageDataGeometryFilter()
            geometry.SetInput(self.image_array.GetOutput())
            self.warp = vtk.vtkWarpScalar()
            self.warp.SetInput(geometry.GetOutput())
            self.warp.SetScaleFactor(self.scale_factor)
            self.mapper = vtk.vtkPolyDataMapper()
            self.mapper.SetInput(self.warp.GetPolyDataOutput())
            self.mapper.SetScalarRange(self.data_min, self.data_max)
            self.mapper.SetLookupTable(self.lut)
            self.mapper.ImmediateModeRenderingOff()
            warp_actor = vtk.vtkActor()
            #     warp_actor.SetScale(2,1,1)
            warp_actor.SetMapper(self.mapper)

            min_range = 0.5 * self.scale_factor
            max_range = 2.0 * self.scale_factor
            self.index_selector.set_emit(False)
            self.index_selector.setMaxValue(max_range, False)
            self.index_selector.setMinValue(min_range)
            self.index_selector.setTickInterval((max_range - min_range) / 10)
            self.index_selector.setRange(max_range, False)
            self.index_selector.setValue(self.scale_factor)
            self.index_selector.setLabel('display gain')
            self.index_selector.hideNDControllerOption()
            self.index_selector.reset_scale_toggle()
            self.index_selector.set_emit(True)
        else:
            # set up ImagePlaneWidgets ...

            # The shared picker enables us to use 3 planes at one time
            # and gets the picking order right
            picker = vtk.vtkCellPicker()
            picker.SetTolerance(0.005)

            # get locations for initial slices
            xMin, xMax, yMin, yMax, zMin, zMax = self.extents
            x_index = (xMax - xMin) / 2
            y_index = (yMax - yMin) / 2
            z_index = (zMax - zMin) / 2

            # The 3 image plane widgets are used to probe the dataset.
            self.planeWidgetX = vtk.vtkImagePlaneWidget()
            self.planeWidgetX.DisplayTextOn()
            self.planeWidgetX.SetInput(self.image_array.GetOutput())
            self.planeWidgetX.SetPlaneOrientationToXAxes()
            self.planeWidgetX.SetSliceIndex(x_index)
            self.planeWidgetX.SetPicker(picker)
            self.planeWidgetX.SetKeyPressActivationValue("x")
            self.planeWidgetX.SetLookupTable(self.lut)
            self.planeWidgetX.TextureInterpolateOff()
            self.planeWidgetX.SetResliceInterpolate(0)

            self.planeWidgetY = vtk.vtkImagePlaneWidget()
            self.planeWidgetY.DisplayTextOn()
            self.planeWidgetY.SetInput(self.image_array.GetOutput())
            self.planeWidgetY.SetPlaneOrientationToYAxes()
            self.planeWidgetY.SetSliceIndex(y_index)
            self.planeWidgetY.SetPicker(picker)
            self.planeWidgetY.SetKeyPressActivationValue("y")
            self.planeWidgetY.SetLookupTable(
                self.planeWidgetX.GetLookupTable())
            self.planeWidgetY.TextureInterpolateOff()
            self.planeWidgetY.SetResliceInterpolate(0)

            self.planeWidgetZ = vtk.vtkImagePlaneWidget()
            self.planeWidgetZ.DisplayTextOn()
            self.planeWidgetZ.SetInput(self.image_array.GetOutput())
            self.planeWidgetZ.SetPlaneOrientationToZAxes()
            self.planeWidgetZ.SetSliceIndex(z_index)
            self.planeWidgetZ.SetPicker(picker)
            self.planeWidgetZ.SetKeyPressActivationValue("z")
            self.planeWidgetZ.SetLookupTable(
                self.planeWidgetX.GetLookupTable())
            self.planeWidgetZ.TextureInterpolateOff()
            self.planeWidgetZ.SetResliceInterpolate(0)

            self.current_widget = self.planeWidgetZ
            self.mode_widget = self.planeWidgetZ
            self.index_selector.set_emit(False)
            self.index_selector.setMinValue(zMin)
            self.index_selector.setMaxValue(zMax, False)
            self.index_selector.setTickInterval((zMax - zMin) / 10)
            self.index_selector.setRange(zMax, False)
            self.index_selector.setValue(z_index)
            self.index_selector.setLabel('Z axis')
            self.index_selector.reset_scale_toggle()
            self.index_selector.set_emit(True)

# create scalar bar for display of intensity range
        self.scalar_bar = vtk.vtkScalarBarActor()
        self.scalar_bar.SetLookupTable(self.lut)
        self.scalar_bar.SetOrientationToVertical()
        self.scalar_bar.SetWidth(0.1)
        self.scalar_bar.SetHeight(0.8)
        self.scalar_bar.SetTitle("Intensity")
        self.scalar_bar.GetPositionCoordinate(
        ).SetCoordinateSystemToNormalizedViewport()
        self.scalar_bar.GetPositionCoordinate().SetValue(0.01, 0.1)

        # Create the RenderWindow and Renderer
        self.ren = vtk.vtkRenderer()
        self.renwin.AddRenderer(self.ren)

        # Add the outline actor to the renderer, set the background color and size
        if self.warped_surface:
            self.ren.AddActor(warp_actor)
        self.ren.AddActor(outlineActor)
        self.ren.SetBackground(0.1, 0.1, 0.2)
        self.ren.AddActor2D(self.scalar_bar)

        # Create a text property for cube axes
        tprop = vtk.vtkTextProperty()
        tprop.SetColor(1, 1, 1)
        tprop.ShadowOn()

        # Create a vtkCubeAxesActor2D.  Use the outer edges of the bounding box to
        # draw the axes.  Add the actor to the renderer.
        self.axes = vtk.vtkCubeAxesActor2D()
        if self.warped_surface:
            if zMin < 0.0 and zMax > 0.0:
                zLoc = 0.0
            else:
                zLoc = zMin
            self.axes.SetBounds(xMin, xMax, yMin, yMax, zLoc, zLoc)
            self.axes.SetZLabel(" ")
        else:
            self.axes.SetInput(self.image_array.GetOutput())
            self.axes.SetZLabel("Z")
        self.axes.SetCamera(self.ren.GetActiveCamera())
        self.axes.SetLabelFormat("%6.4g")
        self.axes.SetFlyModeToOuterEdges()
        self.axes.SetFontFactor(0.8)
        self.axes.SetAxisTitleTextProperty(tprop)
        self.axes.SetAxisLabelTextProperty(tprop)
        self.axes.SetXLabel("X")
        self.axes.SetYLabel("Y")
        self.ren.AddProp(self.axes)

        # Set the interactor for the widgets
        if not self.warped_surface:
            self.planeWidgetX.SetInteractor(self.inter)
            self.planeWidgetX.On()
            self.planeWidgetY.SetInteractor(self.inter)
            self.planeWidgetY.On()
            self.planeWidgetZ.SetInteractor(self.inter)
            self.planeWidgetZ.On()

        self.initialize_camera()
示例#41
0
def main(argv):
    if len(argv) < 2:
        print "usage: ", argv[0], " <data>"
        exit(1)
    data_fn = argv[1]

    mapper = vtk.vtkPolyDataMapper()
    if data_fn.find('.vtk') != -1:
        reader = vtk.vtkPolyDataReader()
        reader.SetFileName(data_fn)
        reader.Update()
        data = reader.GetOutput()
        trianglize = vtk.vtkDelaunay2D()
        trianglize.SetInput(data)
        trianglize.Update()
        mapper.SetInputConnection(trianglize.GetOutputPort())
    elif data_fn.find('.pgm') != -1:
        reader = vtk.vtkPNMReader()
        reader.SetFileName(data_fn)
        reader.Update()
        data = reader.GetOutput()
        trianglize = vtk.vtkImageDataGeometryFilter()
        trianglize.SetInput(data)
        trianglize.Update()
        warp = vtk.vtkWarpScalar()
        warp.SetScaleFactor(0.2)  # arbitrary choice
        warp.SetInputConnection(trianglize.GetOutputPort())
        warp.Update()
        mapper.SetInputConnection(warp.GetOutputPort())
    elif data_fn.find('.dcm') != -1:
        reader = vtk.vtkDICOMImageReader()
        reader.SetFileName(data_fn)
        reader.Update()
        data = reader.GetOutput()
        trianglize = vtk.vtkImageDataGeometryFilter()
        trianglize.SetInput(data)
        trianglize.Update()
        warp = vtk.vtkWarpScalar()
        #warp.SetScaleFactor(0.2) # arbitrary choice
        warp.SetInputConnection(trianglize.GetOutputPort())
        warp.Update()
        mapper.SetInputConnection(warp.GetOutputPort())
    else:
        print "unrecognized data file:", data_fn
        exit(1)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(700, 700)
    renderWindow.AddRenderer(renderer)
    renderWindow.SetWindowName("heightfield")

    renderer.AddActor(actor)
    renderer.SetBackground(0.4, 0.3, 0.2)

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

    renderWindow.Render()
    interactor.Start()
示例#42
0
    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()
            
# from each together.

import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Read in an image and compute a luminance value. The image is
# extracted as a set of polygons (vtkImageDataGeometryFilter). We then
# will warp the plane using the scalar (luminance) values.
reader = vtk.vtkBMPReader()
reader.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp")
luminance = vtk.vtkImageLuminance()
luminance.SetInputConnection(reader.GetOutputPort())
geometry = vtk.vtkImageDataGeometryFilter()
geometry.SetInputConnection(luminance.GetOutputPort())
warp = vtk.vtkWarpScalar()
warp.SetInputConnection(geometry.GetOutputPort())
warp.SetScaleFactor(-0.1)

# Use vtkMergeFilter to combine the original image with the warped
# geometry.
merge = vtk.vtkMergeFilter()
merge.SetGeometryConnection(warp.GetOutputPort())
merge.SetScalarsConnection(reader.GetOutputPort())
mapper = vtk.vtkDataSetMapper()
mapper.SetInputConnection(merge.GetOutputPort())
mapper.SetScalarRange(0, 255)
actor = vtk.vtkActor()
actor.SetMapper(mapper)

# Create renderer stuff
示例#44
0
 def initialize (self):
     debug ("In WarpScalar::initialize ()")
     self.fil = vtk.vtkWarpScalar ()
     self._set_input ()
     self.fil.Update ()
示例#45
0
def main():
    colors = vtk.vtkNamedColors()

    fileName1, fileName2 = get_program_parameters()

    # Here we read data from a annular combustor. A combustor burns fuel and air
    # in a gas turbine (e.g., a jet engine) and the hot gas eventually makes its
    # way to the turbine section.
    #
    pl3d = vtk.vtkMultiBlockPLOT3DReader()
    pl3d.SetXYZFileName(fileName1)
    pl3d.SetQFileName(fileName2)
    pl3d.SetScalarFunctionNumber(100)
    pl3d.SetVectorFunctionNumber(202)
    pl3d.Update()

    pl3dOutput = pl3d.GetOutput().GetBlock(0)

    # Planes are specified using a imin,imax, jmin,jmax, kmin,kmax coordinate
    # specification. Min and max i,j,k values are clamped to 0 and maximum value.
    #
    plane = vtk.vtkStructuredGridGeometryFilter()
    plane.SetInputData(pl3dOutput)
    plane.SetExtent(10, 10, 1, 100, 1, 100)

    plane2 = vtk.vtkStructuredGridGeometryFilter()
    plane2.SetInputData(pl3dOutput)
    plane2.SetExtent(30, 30, 1, 100, 1, 100)
    plane3 = vtk.vtkStructuredGridGeometryFilter()
    plane3.SetInputData(pl3dOutput)
    plane3.SetExtent(45, 45, 1, 100, 1, 100)

    # We use an append filter because that way we can do the warping, etc. just
    # using a single pipeline and actor.
    #
    appendF = vtk.vtkAppendPolyData()
    appendF.AddInputConnection(plane.GetOutputPort())
    appendF.AddInputConnection(plane2.GetOutputPort())
    appendF.AddInputConnection(plane3.GetOutputPort())

    warp = vtk.vtkWarpScalar()
    warp.SetInputConnection(appendF.GetOutputPort())
    warp.UseNormalOn()
    warp.SetNormal(1.0, 0.0, 0.0)
    warp.SetScaleFactor(2.5)

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputConnection(warp.GetOutputPort())
    normals.SetFeatureAngle(60)

    planeMapper = vtk.vtkPolyDataMapper()
    planeMapper.SetInputConnection(normals.GetOutputPort())
    planeMapper.SetScalarRange(pl3dOutput.GetScalarRange())

    planeActor = vtk.vtkActor()
    planeActor.SetMapper(planeMapper)

    # The outline provides context for the data and the planes.
    outline = vtk.vtkStructuredGridOutlineFilter()
    outline.SetInputData(pl3dOutput)

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

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(colors.GetColor3d('Black'))

    # Create the usual graphics stuff.
    #
    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    ren1.AddActor(outlineActor)
    ren1.AddActor(planeActor)
    ren1.SetBackground(colors.GetColor3d('Silver'))

    renWin.SetSize(640, 480)
    renWin.SetWindowName('WarpCombustor')

    # Create an initial view.
    ren1.GetActiveCamera().SetClippingRange(3.95297, 50)
    ren1.GetActiveCamera().SetFocalPoint(8.88908, 0.595038, 29.3342)
    ren1.GetActiveCamera().SetPosition(-12.3332, 31.7479, 41.2387)
    ren1.GetActiveCamera().SetViewUp(0.060772, -0.319905, 0.945498)
    iren.Initialize()

    # Render the image.
    #
    renWin.Render()
    iren.Start()
      min_thick_table = [50, 3.3, 3.3, 3.3, 9.5, 10, 9.5, 11.111] # last entry is a dummy - must be positive
   if opts.ys6 or opts.ys6_1:
      min_thick_table = [50, 4.5, 3.15, 3.25, 10, 6.0, 10, 3.0, 2.5, 3.3, 3.3, 3.3, 3.0, 3.3, 3.3, 9.5, 3, 3, 9.5, 11.111] # real thing, last entry is a dummy - must be positive
   if opts.ys6_1_sp4:
      min_thick_table = [50, 4.5, 3.15, 3.25, 10, 6.0, 10, 3.0, 2.5, 3.3, 3.3, 3.3, 3.011, 3.3012, 3.3012, 6.013, 3.014, 3.015, 3.016, 9.5017, 11.111] # last entry is a dummy - must be positive
   if opts.ys6_true_sp4:
      min_thick_table = [50, 4.5, 3.15, 3.25, 10, 6.0, 10, 3.0, 2.5, 3.3, 3.3, 3.3, 3.011, 3.3012, 3.3012, 2.0, 3.014, 3.015, 3.016, 9.5017, 11.111] # last entry is a dummy - must be positive
   if opts.split_weath:
      final_thickness = min_thick_table[-2]
      min_thick_table[-2] = final_thickness/2
      min_thick_table[-1] = final_thickness/2
      min_thick_table.append(11.111)
else:
   min_thick_table = [opts.min_thickness]*num_surfaces
surface_flat = [vtk.vtkTransformFilter() for x in range(num_surfaces)]
base_mesh_on_surface = [vtk.vtkWarpScalar() for x in range(num_surfaces)]
loc = [vtk.vtkCellLocator() for x in range(num_surfaces)]

if len(material_names) != num_solids - 1:
   print "material_names and solid_names have incompatable lengths"
   sys.exit(3)
if num_surfaces != len(default_solid_nums) + 1:
   print "default_solid_nums and number of surfaces are incompatable"
   sys.exit(4)

# this is a transform to get rid of the z values
# the data must be flat for the interpolation to work
# otherwise vtk thinks the xyz points don't lie on
# the vtp surface and no interpolation occurs
flattener = vtk.vtkTransform()
flattener.Scale(1.0, 1.0, 0.0)