Beispiel #1
0
    def build_vtk_renderer(self):

        # offscreen rendering
        if (vtk.vtkVersion().GetVTKMajorVersion() == 5.0):
            graphics_factory = vtk.vtkGraphicsFactory()
            graphics_factory.SetOffScreenOnlyMode( 1);
            graphics_factory.SetUseMesaClasses( 1 );
            imaging_factory = vtk.vtkImagingFactory()
            imaging_factory.SetUseMesaClasses( 1 );
  
        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(1, 1, 1)
        self.render_window = vtk.vtkRenderWindow()
        # offscreen rendering
        self.render_window.SetOffScreenRendering(1)

        self.render_window.AddRenderer(self.renderer)
        # create a renderwindowinteractor
        #if self.interact:
        #self.iren = vtk.vtkRenderWindowInteractor()
        #self.iren.SetRenderWindow(self.render_window)

        # scalar bar        
        self.scalarbar = vtk.vtkScalarBarActor()
        # To avoid uninitialized warning in VTK 6
        self.scalarbar.SetTitle("") 
        # black text since background is white for printing
        self.scalarbar.GetLabelTextProperty().SetColor(0, 0, 0)
        self.scalarbar.GetTitleTextProperty().SetColor(0, 0, 0)
    def build_vtk_renderer(self):

        # offscreen rendering
        if (vtk.vtkVersion().GetVTKMajorVersion() == 5.0):
            graphics_factory = vtk.vtkGraphicsFactory()
            graphics_factory.SetOffScreenOnlyMode( 1);
            graphics_factory.SetUseMesaClasses( 1 );
            imaging_factory = vtk.vtkImagingFactory()
            imaging_factory.SetUseMesaClasses( 1 );
  
        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(1, 1, 1)
        self.render_window = vtk.vtkRenderWindow()
        # offscreen rendering
        self.render_window.SetOffScreenRendering(1)

        self.render_window.AddRenderer(self.renderer)
        # create a renderwindowinteractor
        #if self.interact:
        #self.iren = vtk.vtkRenderWindowInteractor()
        #self.iren.SetRenderWindow(self.render_window)

        # scalar bar        
        self.scalarbar = vtk.vtkScalarBarActor()
        # To avoid uninitialized warning in VTK 6
        self.scalarbar.SetTitle("") 
        # black text since background is white for printing
        self.scalarbar.GetLabelTextProperty().SetColor(0, 0, 0)
        self.scalarbar.GetTitleTextProperty().SetColor(0, 0, 0)
Beispiel #3
0
def setup_vtk_offscreen(setup_vtk_err):
    """ Used to ensure VTK renders to off screen window. """

    vtk_std_err, setup_qt = setup_vtk_err

    factory = vtk.vtkGraphicsFactory()
    factory.SetOffScreenOnlyMode(False)
    factory.SetUseMesaClasses(False)
    return factory, vtk_std_err, setup_qt
Beispiel #4
0
def set_off_screen_rendering(window):
    'Turn on off-screen rendering, if available'
    gfx_factory = vtk.vtkGraphicsFactory()
    gfx_factory.SetOffScreenOnlyMode(1)
    gfx_factory.SetUseMesaClasses(1)

    img_factory = vtk.vtkImagingFactory()
    img_factory.SetUseMesaClasses(1)

    window.SetOffScreenRendering(1)
Beispiel #5
0
def renderer_to_arr(ren, size):
    """
    Convert DataFrame to HTML table.

    Parameters
    ----------
    ren : Renderer
        vtk Renderer.
    
    size : tuple of int
        Size of the output image

    Returns
    -------
    arr : array
        Image as numpy array.
    
    Notes
    -----
    Inspired from https://github.com/fury-gl/fury/blob/master/fury/window.py
    """
    width, height = size

    graphics_factory = vtk.vtkGraphicsFactory()
    graphics_factory.SetOffScreenOnlyMode(1)

    render_window = vtk.vtkRenderWindow()
    render_window.SetOffScreenRendering(1)
    render_window.AddRenderer(ren)
    render_window.SetSize(width, height)

    render_window.SetAlphaBitPlanes(True)

    render_window.SetMultiSamples(0)

    ren.UseDepthPeelingOn()

    ren.SetMaximumNumberOfPeels(4)

    ren.SetOcclusionRatio(0.0)

    render_window.Render()

    window_to_image_filter = vtk.vtkWindowToImageFilter()
    window_to_image_filter.SetInput(render_window)
    window_to_image_filter.Update()

    vtk_image = window_to_image_filter.GetOutput()
    h, w, _ = vtk_image.GetDimensions()
    vtk_array = vtk_image.GetPointData().GetScalars()
    components = vtk_array.GetNumberOfComponents()
    arr = numpy_support.vtk_to_numpy(vtk_array).reshape(w, h, components)
    return arr
    def __init__(self,
                 mesh,
                 camera_position,
                 focal_point,
                 view_angle,
                 image_size,
                 view_up=(0, 1, 0)):
        self.graphics = vtk.vtkGraphicsFactory()
        self.graphics.SetUseMesaClasses(1)
        #self.img_factory = vtk.vtkImagingFactory()
        #self.img_factory.SetUseMesaClasses(1)

        self.mesh = mesh
        self.image_size = image_size

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputData(self.mesh)

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

        self.camera = vtk.vtkCamera()

        self.renderer = vtk.vtkRenderer()
        self.renderer.SetActiveCamera(self.camera)
        self.renderer.AddActor(self.actor)
        self.renderer.SetBackground(0, 0, 0)

        self.render_window = vtk.vtkRenderWindow()
        self.render_window.SetOffScreenRendering(True)
        self.render_window.AddRenderer(self.renderer)

        self.interactor = vtk.vtkRenderWindowInteractor()
        self.interactor.SetRenderWindow(self.render_window)

        self.picker = vtk.vtkPointPicker()
        self.interactor.SetPicker(self.picker)

        self.render_window.SetSize(self.image_size, self.image_size)
        self.camera.SetPosition(camera_position[0], camera_position[1],
                                camera_position[2])
        self.camera.SetFocalPoint(focal_point[0], focal_point[1],
                                  focal_point[2])
        self.camera.SetViewUp(view_up)
        self.camera.OrthogonalizeViewUp()
        self.camera.SetViewAngle(view_angle)

        self.image_filter = vtk.vtkWindowToImageFilter()
        self.image_filter.SetInput(self.render_window)
Beispiel #7
0
    def save_render_window(self, render_window, clusterviz_config, \
            display_mode):
        """
        Save the current render window to file
        """
        # make sure we're using the mesa classes when saving to file
        fact_graphics = vtkGraphicsFactory()
        fact_graphics.SetUseMesaClasses(1)
        fact_graphics.SetOffScreenOnlyMode(1)

        render_window.OffScreenRenderingOn()
        # to save the file to png, need to pass the render window
        # through a filter to an image object
        win2img_filter = vtkWindowToImageFilter()
        win2img_filter.SetInput(render_window)

        output_file = clusterviz_config.get_output_file(display_mode)

        # work out the output file name's base name (the bit without .png)
        base_regex = re.compile(r'(.*?)\.\w+$')
        basename_search_result = base_regex.search(output_file)
        if basename_search_result.group(1) is None:
            self.logger.critical("Unable to determine the base image output file name.")
            sys.exit(1)

        output_file_basename = basename_search_result.group(1)

        out_writer = vtkPNGWriter()
        out_writer.SetInput(win2img_filter.GetOutput())
        out_writer.SetFileName("%s.png" % output_file_basename)

        # render the window to save it to file
        render_window.Render()
        out_writer.Write()

        # and write out a file with the current date on it
        from datetime import datetime
        date = datetime.now()
        date_str = date.strftime("%Y%m%d_%H%M")
        fname_str = "%s_%s.png" % (output_file_basename, date_str)
        out_writer.SetFileName(fname_str)

        # save it to file
        out_writer.Write()
 def takeScreenShort(self):
     graphics_factory = vtk.vtkGraphicsFactory();
     graphics_factory.SetOffScreenOnlyMode(1);
     graphics_factory.SetUseMesaClasses(1);
     windows = vtk.vtkRenderWindow();
     #Do not open the window!!
     windows.SetOffScreenRendering(True);
     windows.SetSize(self.width,self.height);
     mapper = vtk.vtkPolyDataMapper();
     mapper.SetInputData(self.data);
     for d in ("X","Y",):
         for degree in range(0,100,90):
             actor = vtk.vtkActor()
             actor.SetMapper(mapper);
             getattr(actor,"Rotate{}".format(d))(degree);
             actor.GetProperty().SetColor(0,0,0)
             ren = vtk.vtkRenderer();
             windows.AddRenderer(ren);
             ren.AddActor(actor);
             ren.SetBackground(255.0, 255.0, 255.0);
             ren.ResetCamera();
             cen = ren.GetActiveCamera().GetFocalPoint();
             bounds = actor.GetBounds();
             lightOne = vtk.vtkLight();
             lightOne.SetFocalPoint(cen);
             lightOne.SetPosition(cen);
             lightOne.PositionalOff();
             lightTwo = vtk.vtkLight();
             lightTwo.SetFocalPoint(cen);
             lightTwo.SetPosition(bounds[0],bounds[2],bounds[4]);
             lightTwo.PositionalOn();
             lightThree = vtk.vtkLight();
             lightThree.SetFocalPoint(cen);
             lightThree.SetPosition(bounds[1],bounds[3],bounds[5]);
             lightThree.PositionalOn();
             ren.AddLight(lightOne);
             ren.AddLight(lightTwo);
             ren.AddLight(lightThree);
             windows.Render();
             self.saveToImage(windows,"{}_{}_{}".format(self.fileName,d,degree));
             windows.RemoveRenderer(ren);
 def takeScreenShort(self):
     graphics_factory = vtk.vtkGraphicsFactory();
     graphics_factory.SetOffScreenOnlyMode(1);
     graphics_factory.SetUseMesaClasses(1);
     windows = vtk.vtkRenderWindow();
     #Do not open the window!!
     windows.SetOffScreenRendering(True);
     windows.SetSize(self.width,self.height);
     rot_op = RotateOp();
     op_translate = TransformOp(rot_op);
     for d in ("X","Y","Z",):
         for degree in range(0,360,self.step):
             if d == "X":
                 rot_op.rotateX = degree * math.pi / 180.0;
             elif d == "Y":
                 rot_op.rotateY = degree * math.pi / 180.0;
             else:
                 rot_op.rotateZ = degree * math.pi / 180.0;
             op_translate.data = self.data;
             mapper = vtk.vtkPolyDataMapper();
             mapper.SetInputData(op_translate.perform());
             op_translate.reset();
             actor = vtk.vtkActor()
             actor.SetMapper(mapper);
             if self.plain_color:
                 actor.GetProperty().SetColor(*[c for c in self.obj_rgb]);
             else:
                 actor.GetProperty().SetSpecularColor(*[c/255.0 for c in self.obj_rgb_spec]);
                 actor.GetProperty().SetDiffuseColor(*[c/255.0 for c in self.obj_rgb_diff]);
                 actor.GetProperty().SetAmbientColor(*[c/255.0 for c in self.obj_rgb_amb]);
             
             ren = vtk.vtkRenderer();
             windows.AddRenderer(ren);
             ren.AddActor(actor);
             ren.SetBackground(self.rgb[0]/255.0,self.rgb[1]/255.0,self.rgb[2]/255.0);
             windows.Render();
             self.saveToImage(windows,"{}_{}_{}".format(self.fileName,d,degree));
             windows.RemoveRenderer(ren);
Beispiel #10
0
    def gen_mesh_probe_png(self, probe, png_filename):
        """
        Generate PNG image of the FE mesh.

        Parameters
        ----------
        probe : VTK objectstr
            The probe, VTKPolyData or VTKSource.
        png_filename : str
            The name of the output PNG file.
        """

        surface = vtk.vtkDataSetSurfaceFilter()
        if vtk_version < 6:
            surface.SetInput(self.vtkdata)

        else:
            surface.SetInputData(self.vtkdata)

        surface.Update()

        gf = vtk.vtkGraphicsFactory()
        gf.SetOffScreenOnlyMode(1)
        gf.SetUseMesaClasses(1)

        ifa = vtk.vtkImagingFactory()
        ifa.SetUseMesaClasses(1)

        mapper = vtk.vtkPolyDataMapper()
        if vtk_version < 6:
            mapper.SetInput(surface.GetOutput())

        else:
            mapper.SetInputData(surface.GetOutput())

        mapper.SetScalarModeToUseCellData()

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetOpacity(0.33)

        mapper2 = vtk.vtkPolyDataMapper()
        if hasattr(probe, 'GetOutput'):
            probe0 = probe.GetOutput()

        else:
            probe0 = probe

        if vtk_version < 6:
            mapper2.SetInput(probe0)

        else:
            mapper2.SetInputData(probe0)

        actor2 = vtk.vtkActor()
        actor2.SetMapper(mapper2)
        actor2.GetProperty().SetColor(0,0,0)
        actor2.GetProperty().SetLineWidth(2)
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.SetOffScreenRendering(1)
        renWin.AddRenderer(ren)
        ren.AddActor(actor)
        ren.AddActor(actor2)
        ren.SetBackground(1, 1, 1)
        renWin.Render()

        image = vtk.vtkWindowToImageFilter()
        image.SetInput(renWin)
        image.Update()

        writer = vtk.vtkPNGWriter()
        writer.SetFileName(png_filename)
        if vtk_version < 6:
            writer.SetInput(image.GetOutput())

        else:
            writer.SetInputData(image.GetOutput())

        writer.Write()
Beispiel #11
0
def gen_shot(vtk_filename, png_filename):
    """
    Generate PNG image of the FE mesh.

    Parameters
    ----------
    vtk_filename : str
        The input mesh filename (file in VTK format).

    png_filename : str
        The name of the output PNG file.
    """

    reader = vtk.vtkUnstructuredGridReader()
    reader.SetFileName(vtk_filename)
    reader.Update()
    bnd = reader.GetOutput().GetPoints().GetBounds()

    surface0 = vtk.vtkDataSetSurfaceFilter()
    surface0.SetInput(reader.GetOutput())
    surface0.Update()

    if abs(bnd[5] - bnd[4]) > 1.0e-12:
        tr = vtk.vtkTransform()
        tr.RotateWXYZ(45, 1, 1, 1)

        trFilter = vtk.vtkTransformPolyDataFilter()
        trFilter.SetTransform(tr)
        trFilter.SetInputConnection(surface0.GetOutputPort())
        trFilter.Update()
        surface = trFilter

    else:
        surface = surface0

    ca, cb = surface.GetOutput().GetCellData().GetScalars().GetRange()

    lut = vtk.vtkLookupTable()
    lut.SetHueRange(0.667, 0.667)
    lut.SetSaturationRange(0.0, 1.0)
    lut.SetValueRange(0.8, 1.0)
    lut.SetAlphaRange(1.0, 1.0)
    lut.SetTableRange(ca, cb)

    gf = vtk.vtkGraphicsFactory()
    gf.SetOffScreenOnlyMode(1)
    gf.SetUseMesaClasses(1)

    ifa = vtk.vtkImagingFactory()
    ifa.SetUseMesaClasses(1)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetLookupTable(lut)
    mapper.SetScalarRange(ca, cb)
    mapper.SetInput(surface.GetOutput())
    mapper.SetScalarModeToUseCellData()

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

    mapper2 = vtk.vtkPolyDataMapper()
    mapper2.SetInput(surface.GetOutput())
    actor2 = vtk.vtkActor()
    actor2.SetMapper(mapper2)
    actor2.GetProperty().SetRepresentationToWireframe()

    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.SetOffScreenRendering(1)
    renWin.AddRenderer(ren)
    ren.AddActor(actor)
    ren.AddActor(actor2)
    renWin.Render()

    image = vtk.vtkWindowToImageFilter()
    image.SetInput(renWin)
    image.Update()

    base, _ = os.path.splitext(vtk_filename)
    writer = vtk.vtkPNGWriter()
    writer.SetFileName(png_filename)
    writer.SetInput(image.GetOutput())
    writer.Write()
Beispiel #12
0
def main(argv):
    #Just get something working for testing...
    try:
        opts, args = getopt.getopt(argv, "hi:", ["ifile="])
    except getopt.GetoptError as err:
        print 'tviewer.py -i <inputfile.vtk>'
        print(str(err))
    for opt, arg in opts:
        if opt == '-h':
            print 'tviewer.py -i <inputfile.vtk>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
    print("Going to load and view ", inputfile)
    #Read data
    reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(inputfile)
    reader.Update()

    #lut = vtk.vtkLookupTable()
    #lut.SetNumberOfColors(65535)
    #lut.SetHueRange(0.0, 2.667)

    #lut.SetVectorMode(vtk.vtkScalarsToColors.MAGNITUDE)
    #lut.Build()
    #Setup offscreen rendering
    graphics_factory = vtk.vtkGraphicsFactory()
    graphics_factory.SetOffScreenOnlyMode(1)
    graphics_factory.SetUseMesaClasses(1)
    #imaging_factory = vtk.vtkImagingFactory()
    #imaging_factory.SetUseMesaClasses(1)

    #Get image from reader
    image = reader.GetOutput()
    #image.SetSpacing(1,1,1)
    #image.GetPointData().SetScalars(image.GetPointData().GetVectors())
    #Compute Q Criterion for texture mapping
    vorticity = vtk.vtkGradientFilter()
    vorticity.SetInputData(image)
    vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS, "Velocity")
    vorticity.ComputeQCriterionOn()
    #vorticity.SetComputeGradient(0)
    vorticity.Update()
    #Generate contour for comparison
    c = vtk.vtkContourFilter()
    #c.SetValue(0,1128)
    c.SetValue(0, 450)
    image.GetPointData().SetScalars(
        vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    c.SetInputData(image)
    c.Update()
    contour = c.GetOutput()
    #contour.GetCellData().SetScalars(image.GetPointData().GetVectors("Velocity"))
    normals = vtk.vtkPolyDataNormals()
    normals.SetInputData(contour)

    normals.SetFeatureAngle(45)  #?
    normals.Update()
    #print normals.GetOutput()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(normals.GetOutput())
    mapper.ScalarVisibilityOn()
    mapper.SetScalarRange(-1, 1)
    mapper.SetScalarModeToUsePointFieldData()
    mapper.ColorByArrayComponent("Velocity", 0)
    #print image
    #print contour

    #mapper.SelectColorArray("Q-criterion")
    #mapper.SetLookupTable(lut)

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

    ren = vtk.vtkRenderer()
    ren.AddActor(actor)
    ren.SetBackground(1, 1, 1)
    ren.ResetCamera()

    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(400, 400)
    renWin.SetOffScreenRendering(1)
    renWin.AddRenderer(ren)
    renWin.Render()

    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renWin)
    windowToImageFilter.Update()

    w = vtk.vtkPNGWriter()
    w.SetFileName("cube.png")
    w.SetInputConnection(windowToImageFilter.GetOutputPort())
    w.Write()
Beispiel #13
0
def main(argv):
   #Just get something working for testing...
    try:
        opts, args = getopt.getopt(argv,"hi:", ["ifile="])
    except getopt.GetoptError as err:
        print 'tviewer.py -i <inputfile.vtk>'
        print (str(err))
    for opt, arg in opts:
        if opt == '-h':
            print 'tviewer.py -i <inputfile.vtk>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
    print("Going to load and view ", inputfile)
    #Read data
    reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(inputfile)
    reader.Update()

    #lut = vtk.vtkLookupTable()
    #lut.SetNumberOfColors(65535)
    #lut.SetHueRange(0.0, 2.667)
    
    #lut.SetVectorMode(vtk.vtkScalarsToColors.MAGNITUDE)
    #lut.Build()
    #Setup offscreen rendering
    graphics_factory = vtk.vtkGraphicsFactory()
    graphics_factory.SetOffScreenOnlyMode(1)
    graphics_factory.SetUseMesaClasses(1)
    #imaging_factory = vtk.vtkImagingFactory()
    #imaging_factory.SetUseMesaClasses(1)

    #Get image from reader
    image = reader.GetOutput()
    #image.SetSpacing(1,1,1)
    #image.GetPointData().SetScalars(image.GetPointData().GetVectors())
    #Compute Q Criterion for texture mapping
    vorticity = vtk.vtkGradientFilter()
    vorticity.SetInputData(image)
    vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
    vorticity.ComputeQCriterionOn()
    #vorticity.SetComputeGradient(0)
    vorticity.Update()
    #Generate contour for comparison
    c = vtk.vtkContourFilter()
    #c.SetValue(0,1128)
    c.SetValue(0,450)
    image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    c.SetInputData(image)
    c.Update()
    contour = c.GetOutput()
    #contour.GetCellData().SetScalars(image.GetPointData().GetVectors("Velocity"))
    normals = vtk.vtkPolyDataNormals()
    normals.SetInputData(contour)

    normals.SetFeatureAngle(45) #?
    normals.Update()
    #print normals.GetOutput()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(normals.GetOutput())
    mapper.ScalarVisibilityOn()
    mapper.SetScalarRange(-1,1)
    mapper.SetScalarModeToUsePointFieldData()
    mapper.ColorByArrayComponent("Velocity", 0)
    #print image
    #print contour

    #mapper.SelectColorArray("Q-criterion")
    #mapper.SetLookupTable(lut)

    #print mapper
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    
    ren = vtk.vtkRenderer()
    ren.AddActor(actor)
    ren.SetBackground(1,1,1)
    ren.ResetCamera()

    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(400,400)
    renWin.SetOffScreenRendering(1)
    renWin.AddRenderer(ren)
    renWin.Render()
    
    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renWin)
    windowToImageFilter.Update()
    
    w = vtk.vtkPNGWriter()
    w.SetFileName("cube.png")
    w.SetInputConnection(windowToImageFilter.GetOutputPort())
    w.Write()
Beispiel #14
0
def snapshot(scene,
             fname=None,
             size=(300, 300),
             offscreen=True,
             order_transparent=False,
             stereo='off'):
    """Save a snapshot of the scene in a file or in memory.

    Parameters
    -----------
    scene : Scene() or vtkRenderer
        Scene instance
    fname : str or None
        Save PNG file. If None return only an array without saving PNG.
    size : (int, int)
        ``(width, height)`` of the window. Default is (300, 300).
    offscreen : bool
        Default True. Go stealthmode no window should appear.
    order_transparent : bool
        Default False. Use depth peeling to sort transparent objects.
    stereo: string
        Set the stereo type. Default is 'off'. Other types include: \n
            'opengl': OpenGL frame-sequential stereo. Referred to as \
                      'CrystalEyes' by VTK. \n
            'anaglyph': For use with red/blue glasses. See VTK docs to \
                        use different colors. \n
            'interlaced': Line interlaced. \n
            'checkerboard': Checkerboard interlaced. \n
            'left': Left eye only. \n
            'right': Right eye only. \n
            'horizontal': Side-by-side.

    Returns
    -------
    arr : ndarray
        Color array of size (width, height, 3) where the last dimension
        holds the RGB values.

    """
    width, height = size

    if offscreen:
        graphics_factory = vtk.vtkGraphicsFactory()
        graphics_factory.SetOffScreenOnlyMode(1)
        # TODO check if the line below helps in something
        # graphics_factory.SetUseMesaClasses(1)

    render_window = vtk.vtkRenderWindow()
    if offscreen:
        render_window.SetOffScreenRendering(1)
    if stereo.lower() != 'off':
        enable_stereo(render_window, stereo)
    render_window.AddRenderer(scene)
    render_window.SetSize(width, height)

    if order_transparent:

        # Use a render window with alpha bits
        # as default is 0 (false))
        render_window.SetAlphaBitPlanes(True)

        # Force to not pick a framebuffer with a multisample buffer
        # (default is 8)
        render_window.SetMultiSamples(0)

        # Choose to use depth peeling (if supported)
        # (default is 0 (false)):
        scene.UseDepthPeelingOn()

        # Set depth peeling parameters
        # Set the maximum number of rendering passes (default is 4)
        scene.SetMaximumNumberOfPeels(4)

        # Set the occlusion ratio (initial value is 0.0, exact image):
        scene.SetOcclusionRatio(0.0)

    render_window.Render()

    window_to_image_filter = vtk.vtkWindowToImageFilter()
    window_to_image_filter.SetInput(render_window)
    window_to_image_filter.Update()

    vtk_image = window_to_image_filter.GetOutput()
    h, w, _ = vtk_image.GetDimensions()
    vtk_array = vtk_image.GetPointData().GetScalars()
    components = vtk_array.GetNumberOfComponents()
    arr = numpy_support.vtk_to_numpy(vtk_array).reshape(h, w, components)

    if fname is None:
        return arr

    writer = vtk.vtkPNGWriter()
    writer.SetFileName(fname)
    writer.SetInputConnection(window_to_image_filter.GetOutputPort())
    writer.Write()
    return arr
Beispiel #15
0
def gen_shot(vtk_filename, png_filename):
    """
    Generate PNG image of the FE mesh.

    Parameters
    ----------
    vtk_filename : str
        The input mesh filename (file in VTK format).

    png_filename : str
        The name of the output PNG file.
    """

    reader = vtk.vtkUnstructuredGridReader()
    reader.SetFileName(vtk_filename)
    reader.Update()
    bnd = reader.GetOutput().GetPoints().GetBounds()

    surface0 = vtk.vtkDataSetSurfaceFilter()
    surface0.SetInput(reader.GetOutput())
    surface0.Update()

    if abs(bnd[5] - bnd[4]) > 1.0e-12:
        tr = vtk.vtkTransform()
        tr.RotateWXYZ(45,1,1,1)

        trFilter = vtk.vtkTransformPolyDataFilter()
        trFilter.SetTransform(tr)
        trFilter.SetInputConnection(surface0.GetOutputPort())
        trFilter.Update()
        surface = trFilter

    else:
        surface = surface0

    ca,cb = surface.GetOutput().GetCellData().GetScalars().GetRange()

    lut = vtk.vtkLookupTable()
    lut.SetHueRange(0.667, 0.667)
    lut.SetSaturationRange(0.0, 1.0)
    lut.SetValueRange(0.8, 1.0)
    lut.SetAlphaRange(1.0, 1.0)
    lut.SetTableRange(ca,cb)

    gf = vtk.vtkGraphicsFactory()
    gf.SetOffScreenOnlyMode(1)
    gf.SetUseMesaClasses(1)

    ifa = vtk.vtkImagingFactory()
    ifa.SetUseMesaClasses(1)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetLookupTable(lut)
    mapper.SetScalarRange(ca,cb);
    mapper.SetInput(surface.GetOutput())
    mapper.SetScalarModeToUseCellData()

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

    mapper2 = vtk.vtkPolyDataMapper()
    mapper2.SetInput(surface.GetOutput())
    actor2 = vtk.vtkActor()
    actor2.SetMapper(mapper2)
    actor2.GetProperty().SetRepresentationToWireframe()

    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.SetOffScreenRendering(1)
    renWin.AddRenderer(ren)
    ren.AddActor(actor)
    ren.AddActor(actor2)
    renWin.Render()

    image = vtk.vtkWindowToImageFilter()
    image.SetInput(renWin)
    image.Update()

    base, _ = os.path.splitext(vtk_filename)
    writer = vtk.vtkPNGWriter()
    writer.SetFileName(png_filename)
    writer.SetInput(image.GetOutput())
    writer.Write()
Beispiel #16
0
def snapshot(scene,
             fname=None,
             size=(300, 300),
             offscreen=True,
             order_transparent=False):
    """Save a snapshot of the scene in a file or in memory.

    Parameters
    -----------
    scene : Scene() or vtkRenderer
        Scene instance
    fname : str or None
        Save PNG file. If None return only an array without saving PNG.
    size : (int, int)
        ``(width, height)`` of the window. Default is (300, 300).
    offscreen : bool
        Default True. Go stealthmode no window should appear.
    order_transparent : bool
        Default False. Use depth peeling to sort transparent objects.

    Returns
    -------
    arr : ndarray
        Color array of size (width, height, 3) where the last dimension
        holds the RGB values.

    """
    width, height = size

    if offscreen:
        graphics_factory = vtk.vtkGraphicsFactory()
        graphics_factory.SetOffScreenOnlyMode(1)
        # TODO check if the line below helps in something
        # graphics_factory.SetUseMesaClasses(1)

    render_window = vtk.vtkRenderWindow()
    if offscreen:
        render_window.SetOffScreenRendering(1)
    render_window.AddRenderer(scene)
    render_window.SetSize(width, height)

    if order_transparent:

        # Use a render window with alpha bits
        # as default is 0 (false))
        render_window.SetAlphaBitPlanes(True)

        # Force to not pick a framebuffer with a multisample buffer
        # (default is 8)
        render_window.SetMultiSamples(0)

        # Choose to use depth peeling (if supported)
        # (default is 0 (false)):
        scene.UseDepthPeelingOn()

        # Set depth peeling parameters
        # Set the maximum number of rendering passes (default is 4)
        scene.SetMaximumNumberOfPeels(4)

        # Set the occlusion ratio (initial value is 0.0, exact image):
        scene.SetOcclusionRatio(0.0)

    render_window.Render()

    window_to_image_filter = vtk.vtkWindowToImageFilter()
    window_to_image_filter.SetInput(render_window)
    window_to_image_filter.Update()

    vtk_image = window_to_image_filter.GetOutput()
    h, w, _ = vtk_image.GetDimensions()
    vtk_array = vtk_image.GetPointData().GetScalars()
    components = vtk_array.GetNumberOfComponents()
    arr = numpy_support.vtk_to_numpy(vtk_array).reshape(h, w, components)

    if fname is None:
        return arr

    writer = vtk.vtkPNGWriter()
    writer.SetFileName(fname)
    writer.SetInputConnection(window_to_image_filter.GetOutputPort())
    writer.Write()
    return arr
Beispiel #17
0
# this is the one used in the matlab docs: z = x*exp(-x^2-y^2)
z = zeros((len(x),len(y)), dtype=floating)

# boy do *I* feel old fashioned writing it this way
# surely there's another way to do it: - something to do later
for i in range(len(x)):
    for j in range(len(y)):
	z[i,j] = x[i]*exp(-x[i]*x[i] - y[j]*y[j])


import vtk

interactive = True

if not interactive:
    _factGraphics = vtk.vtkGraphicsFactory()
    _factGraphics.SetUseMesaClasses(1)
    _factImage = vtk.vtkImagingFactory()
    _factImage.SetUseMesaClasses(1)

# set up the renderer and the render window
_ren = vtk.vtkRenderer()
_renWin = vtk.vtkRenderWindow()
_renWin.AddRenderer(_ren)
_renWin.SetSize(640,480)
if not interactive:
    _renWin.OffScreenRenderingOn()

# set up the points
_points = vtk.vtkPoints()
_points.SetNumberOfPoints(len(x))
Beispiel #18
0
def main(argv):
   #Just get something working for testing...
    try:
        opts, args = getopt.getopt(argv,"hi:", ["ifile="])
    except getopt.GetoptError as err:
        print 'tviewer.py -i <inputfile.vtk>'
        print (str(err))
    for opt, arg in opts:
        if opt == '-h':
            print 'tviewer.py -i <inputfile.vtk>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
    print("Going to load and view ", inputfile)
    #Read data
    reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(inputfile)
    reader.Update()

    #Setup offscreen rendering
    graphics_factory = vtk.vtkGraphicsFactory()
    graphics_factory.SetOffScreenOnlyMode(1)
    graphics_factory.SetUseMesaClasses(1)


    #Get image from reader
    image = reader.GetOutput()
    print ("Image read in")

    #compute q-criterion
    vorticity = vtk.vtkGradientFilter()
    vorticity.SetInputData(image)
    vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
    vorticity.ComputeQCriterionOn()
    vorticity.SetComputeGradient(0)
    vorticity.Update()

    print ("Vorticity done")
    #Get magnitude  not sure we need it now. lets see.
    #mag = vtk.vtkImageMagnitude()
    #cp = vtk.vtkCellDataToPointData()
    #cp.SetInputData(vorticity.GetOutput())
    #cp.Update()
    #image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
    #mag.SetInputData(image)
    #mag.Update()
    #m = mag.GetOutput()

    image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    print image
    #image.GetPointData().SetScalars(image.GetPointData().GetVectors("Velocity"))
    c = vtk.vtkContourFilter()
    #c.SetValue(0,1128)
    c.SetValue(0,600)
    
    c.SetInputData(image)
    c.Update()
    #import pdb; pdb.set_trace()
    contour = c.GetOutput()
    #contour.GetCellData().SetScalars(image.GetPointData().GetVectors("Velocity"))
    print "Contour done"
    #normals = vtk.vtkPolyDataNormals()
    #normals.SetInputData(contour)

    #normals.SetFeatureAngle(45) #?
    #normals.Update()
    #print normals.GetOutput()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(contour)
    mapper.ScalarVisibilityOn()
    mapper.SetScalarRange(-1,1)
    mapper.SetScalarModeToUsePointFieldData()
    mapper.ColorByArrayComponent("Velocity", 0)
    #import pdb; pdb.set_trace()
    print ("mapped")
    
    #print mapper
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    
    ren = vtk.vtkRenderer()
    ren.AddActor(actor)
    ren.SetBackground(1,1,1)
    ren.ResetCamera()

    #camera = vtk.vtkCamera()
    #camera.SetPosition(0,0,0)
    #camera.SetFocalPoint(0,0,0)
    #ren.SetActiveCamera(camera)
    
    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(600,600)
    renWin.AddRenderer(ren)
    renWin.SetOffScreenRendering(1)
    #import pdb; pdb.set_trace()
    #iren = vtk.vtkRenderWindowInteractor()

    #iren.SetRenderWindow(renWin)
    #iren.Initialize()
    #iren.Start()
    
    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renWin)
    windowToImageFilter.Update()
    
    w = vtk.vtkPNGWriter()
    w.SetFileName("cube.png")
    w.SetInputConnection(windowToImageFilter.GetOutputPort())
    w.Write()
Beispiel #19
0
    def gen_mesh_probe_png(self, probe, png_filename):
        """
        Generate PNG image of the FE mesh.

        Parameters
        ----------
        probe : VTK objectstr
            The probe, VTKPolyData or VTKSource.
        png_filename : str
            The name of the output PNG file.
        """

        surface = vtk.vtkDataSetSurfaceFilter()
        if vtk_version < 6:
            surface.SetInput(self.vtkdata)

        else:
            surface.SetInputData(self.vtkdata)

        surface.Update()

        gf = vtk.vtkGraphicsFactory()
        gf.SetOffScreenOnlyMode(1)
        gf.SetUseMesaClasses(1)

        ifa = vtk.vtkImagingFactory()
        ifa.SetUseMesaClasses(1)

        mapper = vtk.vtkPolyDataMapper()
        if vtk_version < 6:
            mapper.SetInput(surface.GetOutput())

        else:
            mapper.SetInputData(surface.GetOutput())

        mapper.SetScalarModeToUseCellData()

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetOpacity(0.33)

        mapper2 = vtk.vtkPolyDataMapper()
        if hasattr(probe, 'GetOutput'):
            probe0 = probe.GetOutput()

        else:
            probe0 = probe

        if vtk_version < 6:
            mapper2.SetInput(probe0)

        else:
            mapper2.SetInputData(probe0)

        actor2 = vtk.vtkActor()
        actor2.SetMapper(mapper2)
        actor2.GetProperty().SetColor(0,0,0)
        actor2.GetProperty().SetLineWidth(2)
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.SetOffScreenRendering(1)
        renWin.AddRenderer(ren)
        ren.AddActor(actor)
        ren.AddActor(actor2)
        ren.SetBackground(1, 1, 1)
        renWin.Render()

        image = vtk.vtkWindowToImageFilter()
        image.SetInput(renWin)
        image.Update()

        writer = vtk.vtkPNGWriter()
        writer.SetFileName(png_filename)
        if vtk_version < 6:
            writer.SetInput(image.GetOutput())

        else:
            writer.SetInputData(image.GetOutput())

        writer.Write()
Beispiel #20
0
def main(argv):
    #Just get something working for testing...
    try:
        opts, args = getopt.getopt(argv, "hi:", ["ifile="])
    except getopt.GetoptError as err:
        print 'tviewer.py -i <inputfile.vtk>'
        print(str(err))
    for opt, arg in opts:
        if opt == '-h':
            print 'tviewer.py -i <inputfile.vtk>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
    print("Going to load and view ", inputfile)
    #Read data
    reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(inputfile)
    reader.Update()

    #Setup offscreen rendering
    graphics_factory = vtk.vtkGraphicsFactory()
    graphics_factory.SetOffScreenOnlyMode(1)
    graphics_factory.SetUseMesaClasses(1)

    #Get image from reader
    image = reader.GetOutput()
    print("Image read in")

    #compute q-criterion
    vorticity = vtk.vtkGradientFilter()
    vorticity.SetInputData(image)
    vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS, "Velocity")
    vorticity.ComputeQCriterionOn()
    vorticity.SetComputeGradient(0)
    vorticity.Update()

    print("Vorticity done")
    #Get magnitude  not sure we need it now. lets see.
    #mag = vtk.vtkImageMagnitude()
    #cp = vtk.vtkCellDataToPointData()
    #cp.SetInputData(vorticity.GetOutput())
    #cp.Update()
    #image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
    #mag.SetInputData(image)
    #mag.Update()
    #m = mag.GetOutput()

    image.GetPointData().SetScalars(
        vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    print image
    #image.GetPointData().SetScalars(image.GetPointData().GetVectors("Velocity"))
    c = vtk.vtkContourFilter()
    #c.SetValue(0,1128)
    c.SetValue(0, 600)

    c.SetInputData(image)
    c.Update()
    #import pdb; pdb.set_trace()
    contour = c.GetOutput()
    #contour.GetCellData().SetScalars(image.GetPointData().GetVectors("Velocity"))
    print "Contour done"
    #normals = vtk.vtkPolyDataNormals()
    #normals.SetInputData(contour)

    #normals.SetFeatureAngle(45) #?
    #normals.Update()
    #print normals.GetOutput()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(contour)
    mapper.ScalarVisibilityOn()
    mapper.SetScalarRange(-1, 1)
    mapper.SetScalarModeToUsePointFieldData()
    mapper.ColorByArrayComponent("Velocity", 0)
    #import pdb; pdb.set_trace()
    print("mapped")

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

    ren = vtk.vtkRenderer()
    ren.AddActor(actor)
    ren.SetBackground(1, 1, 1)
    ren.ResetCamera()

    #camera = vtk.vtkCamera()
    #camera.SetPosition(0,0,0)
    #camera.SetFocalPoint(0,0,0)
    #ren.SetActiveCamera(camera)

    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(600, 600)
    renWin.AddRenderer(ren)
    renWin.SetOffScreenRendering(1)
    #import pdb; pdb.set_trace()
    #iren = vtk.vtkRenderWindowInteractor()

    #iren.SetRenderWindow(renWin)
    #iren.Initialize()
    #iren.Start()

    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renWin)
    windowToImageFilter.Update()

    w = vtk.vtkPNGWriter()
    w.SetFileName("cube.png")
    w.SetInputConnection(windowToImageFilter.GetOutputPort())
    w.Write()