def keypressCallback(obj, ev):
    key = obj.GetKeySym()
    if key == "s":
        filter.Modified()
        filter.SetInputBufferTypeToZBuffer()
        filter.Update()

        scale = vtk.vtkImageShiftScale()
        scale.SetOutputScalarTypeToUnsignedChar()
        scale.SetInputConnection(filter.GetOutputPort())
        scale.SetShift(0)
        scale.SetScale(-300)

        scale2 = vtk.vtkImageShiftScale()
        scale2.SetOutputScalarTypeToUnsignedChar()
        scale2.SetInputConnection(scale.GetOutputPort())
        scale2.SetShift(255)

        global iteration
        iteration = iteration + 1

        file_name = "/home/vishnusanjay/cmpt764/Final project/last_examples/depthimages_1/chair_" + \
                    str(iteration) + ".bmp"
        imageWriter = vtk.vtkBMPWriter()
        imageWriter.SetFileName(file_name)
        imageWriter.SetInputConnection(scale2.GetOutputPort())
        imageWriter.Write()
Beispiel #2
0
    def test_dither_boat(self):
        self.print_param.fill_pattern.value = 1
        self.print_param.skin_offset.value = 1.0
        self.print_param.infill.value = 0.5

        slicer = VoxelSlicer()
        slicer.set_settings(self.printer_setting,
                            self.printhead_setting, self.print_param)
        slicer.SetInputDataObject(self.part)
        slicer.Update()

        slice_stack = slicer.GetOutputDataObject(0)
        img_dim = slice_stack.GetDimensions()
        self.assertTrue(img_dim[2] > 0)
        (x_min, x_max, y_min, y_max, _, _) = slice_stack.GetExtent()

        mid_point = int(img_dim[2]/2)
        single_im = vtk.vtkExtractVOI()
        single_im.SetVOI(x_min, x_max, y_min, y_max, mid_point, mid_point)
        single_im.SetSampleRate(1, 1, 1)
        single_im.SetInputData(slice_stack)
        single_im.Update()

        writer = vtk.vtkBMPWriter()
        writer.SetInputData(single_im.GetOutput())
        writer.SetFileName(os.path.join(self.out_dir, 'test_d.bmp'))
        writer.Update()
        writer.Write()

        writer_3d = vtk.vtkXMLImageDataWriter()
        writer_3d.SetFileName(os.path.join(self.out_dir, 'test_d.vti'))
        writer_3d.SetInputData(slice_stack)
        writer_3d.Update()
        writer_3d.Write()
Beispiel #3
0
    def save_rendered(self, image_file_name):
        "Output snapshot to image file"

        image_file_type = os.path.splitext(image_file_name)[1]

        # Remove existing image file
        if os.path.exists(image_file_name):
            if os.path.isfile(image_file_name):
                os.remove(image_file_name)
            else:
                raise VisualizerError \
                    ('Cannot overwrite image file: ' + image_file_name)

        if image_file_type == '.bmp':
            writer = vtk.vtkBMPWriter()
        elif image_file_type == '.jpg':
            writer = vtk.vtkJPEGWriter()
        elif image_file_type == '.png':
            writer = vtk.vtkPNGWriter()
        elif image_file_type == '.tif':
            writer = vtk.vtkTIFFWriter()
        else:
            error_info = 'Illegal image-file type: ' + image_file_type + '\n'
            error_info += 'Please choose from "bmp","jpg","png","tif".'
            raise VisualizerError(error_info)

        w2i = vtk.vtkWindowToImageFilter()
        w2i.SetInput(self.window)
        self.window.Render()

        writer.SetInput(w2i.GetOutput())
        writer.SetFileName(image_file_name)
        writer.Write()
Beispiel #4
0
def save_image(renderwindow, base, extension):
    file = (base + extension).encode(sys.getfilesystemencoding())
    print 'save_image', file

    w2i = vtk.vtkWindowToImageFilter()
    w2i.SetInput(renderwindow)
    w2i.Update()
    if extension == '.jpg':
        image = vtk.vtkJPEGWriter()
        image.SetQuality(100)
    elif extension == '.png':
        image = vtk.vtkPNGWriter()
    elif extension == '.bmp':
        image = vtk.vtkBMPWriter()
    elif extension == '.tiff':
        image = vtk.vtkTIFFWriter()
        image.SetCompressionToNoCompression()
    else:
        return "Image exporter: unknown file extension: " + extension

    image.SetInputConnection(w2i.GetOutputPort())
    image.SetFileName(file)
    renderwindow.Render()
    image.Write()

    return None
Beispiel #5
0
def handle_filetype_writing_special_cases(writer, **kwargs):
    '''Handle intermediate steps for writing filetype

    Calls the associated function for each writer type to try
    and handle the output. These may add filters before the
    writer such as casting. It is recommended to set the writer
    input data or input connection before calling this function.

    If no special cases are known for a writer type, nothing
    is done.

    In general, it is recommended to call this on your vtkImageWriter
    class just before calling update to avoid common data typing errors.
    
    Note that this function may insert new filters between the filter connected
    to writer and the writer itself.

    Args:
        writer (vtk.vtkImageWriter):    The file writer
        kwargs (dict):                  Dictionary of args passed to subsequent functions

    Returns:
        None
    '''
    step_map = {
        type(vtkbone.vtkboneAIMWriter()): handle_aim_writing_special_cases,
        type(vtk.vtkTIFFWriter()): handle_tiff_writing_special_cases,
        type(vtk.vtkPNGWriter()): handle_png_writing_special_cases,
        type(vtk.vtkBMPWriter()): handle_bmp_writing_special_cases,
        type(vtk.vtkJPEGWriter()): handle_jpeg_writing_special_cases
    }

    if type(writer) in step_map:
        return step_map[type(writer)](writer, **kwargs)
    return None
Beispiel #6
0
    def save_rendered(self, image_file_name):
        "Output snapshot to image file"

        image_file_type = os.path.splitext(image_file_name)[1]

        # Remove existing image file
        if os.path.exists(image_file_name):
            if os.path.isfile(image_file_name):
                os.remove(image_file_name)
            else:
                raise VisualizerError \
                    ('Cannot overwrite image file: ' + image_file_name)

        if image_file_type == '.bmp':
            writer = vtk.vtkBMPWriter()
        elif image_file_type == '.jpg':
            writer = vtk.vtkJPEGWriter()
        elif image_file_type == '.png':
            writer = vtk.vtkPNGWriter()
        elif image_file_type == '.tif':
            writer = vtk.vtkTIFFWriter()
        else:
            error_info = 'Illegal image-file type: ' + image_file_type + '\n'
            error_info += 'Please choose from "bmp","jpg","png","tif".'
            raise VisualizerError(error_info)

        w2i = vtk.vtkWindowToImageFilter()
        w2i.SetInput(self.window)
        self.window.Render()

        writer.SetInput(w2i.GetOutput())
        writer.SetFileName(image_file_name)
        writer.Write()
Beispiel #7
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkBMPWriter(), 'Writing vtkBMP.',
         ('vtkBMP',), (),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Beispiel #8
0
    def get_frame_as_array(self):
        """render the 3d scene and export it as a numpy array.

        This can be useful to display the image in a plot for instance. We use the `vtkBMPWriter` to generate the
        buffer as an array of bytes. The numpy array is then created from this buffer and reshaped to the appropriate
        RGB image size.

        :return: a numpy array representing the RGB rendered image.
        """
        self.renWin.SetOffScreenRendering(1)
        self.renWin.Render()
        w2i = vtk.vtkWindowToImageFilter()
        w2i.SetInput(self.renWin)
        w2i.Update()
        bmp_shape = self.renWin.GetSize() + (3, )
        writer = vtk.vtkBMPWriter()
        writer.SetWriteToMemory(1)
        writer.SetInputConnection(w2i.GetOutputPort())
        writer.Write()
        data = bytes(memoryview(writer.GetResult()))
        self.renWin.SetOffScreenRendering(0)
        # create the numpy array from the bytes buffer (leave off the first 54 bytes corresponding to the BMP header)
        array_bgr = np.frombuffer(data[54:], dtype=np.uint8).reshape(bmp_shape)
        b = array_bgr[::-1, :, 0].T
        g = array_bgr[::-1, :, 1].T
        r = array_bgr[::-1, :, 2].T
        return np.array([r, g, b]).transpose(2, 1, 0)
Beispiel #9
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkBMPWriter(),
                                       'Writing vtkBMP.', ('vtkBMP', ), (),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
 def ScreenShot(self,filename):
     "Create a screenshot of the visualizer in BMP format"
     win2img = vtk.vtkWindowToImageFilter()
     win2img.SetInput(self.renderWindow)
     win2img.Update()
     bmpWriter = vtk.vtkBMPWriter()
     bmpWriter.SetInput(win2img.GetOutput())
     bmpWriter.SetFileName(filename)
     bmpWriter.Write()
    def save_frame_depth(self, path):

        #setup camera
        camera = vtkCamera()
        camera.SetPosition(self.cx, self.cy, self.cz)
        camera.SetFocalPoint(self.fx, self.fy, self.fz)
        camera.SetViewUp(self.ux, self.uy, self.uz)
        camera.SetViewAngle(self.fovy)
        #setup renderer
        renderer = vtkRenderer()
        renderWindow = vtkRenderWindow()
        renderWindow.SetOffScreenRendering(1)
        renderWindow.AddRenderer(renderer)
        renderWindow.SetSize(self.w, self.h)
        for i in xrange(-1, self.expert.nr_obstacles_c()):
            vss, nss, iss = self.save_frame_mesh(i)
            #geometry
            pts = vtkPoints()
            for i in xrange(len(vss)):
                pts.InsertNextPoint(vss[i][0], vss[i][1], vss[i][2])
                tris = vtkCellArray()
            for i in xrange(len(iss)):
                triangle = vtkTriangle()
                triangle.GetPointIds().SetId(0, iss[i][0])
                triangle.GetPointIds().SetId(1, iss[i][1])
                triangle.GetPointIds().SetId(2, iss[i][2])
                tris.InsertNextCell(triangle)
            poly = vtkPolyData()
            poly.SetPoints(pts)
            poly.SetPolys(tris)
            #actor
            mapper = vtkPolyDataMapper()
            mapper.SetInput(poly)
            actor = vtkActor()
            actor.SetMapper(mapper)
            renderer.AddActor(actor)
        renderer.SetBackground(self.bk_r, self.bk_g, self.bk_b)
        renderer.SetActiveCamera(camera)
        renderWindow.Render()
        #output options
        windowToImageFilter = vtkWindowToImageFilter()
        windowToImageFilter.SetInput(renderWindow)
        windowToImageFilter.SetMagnification(1)
        windowToImageFilter.SetInputBufferTypeToZBuffer()
        #Extract z buffer value
        windowToImageFilter.Update()
        #scale and shift
        scale = vtkImageShiftScale()
        scale.SetOutputScalarTypeToUnsignedChar()
        scale.SetInputConnection(windowToImageFilter.GetOutputPort())
        scale.SetShift(0)
        scale.SetScale(-255)
        #output
        writer = vtkBMPWriter()
        writer.SetFileName(path)
        writer.SetInputConnection(scale.GetOutputPort())
        writer.Write()
Beispiel #12
0
def WriteImage(fileName, renWin1, rgba=True):
    """
    Write the render window view to an image file.

    Image types supported are:
     BMP, JPEG, PNM, PNG, PostScript, TIFF.
    The default parameters are used for all writers, change as needed.

    :param fileName: The file name, if no extension then PNG is assumed.
    :param renWin1: The render window.
    :param rgba: Used to set the buffer type.
    :return:
    """

    import os

    if fileName:
        # Select the writer to use.
        path, ext = os.path.splitext(fileName)
        ext = ext.lower()
        if not ext:
            ext = '.png'
            fileName = fileName + ext
        if ext == '.bmp':
            writer = vtk.vtkBMPWriter()
        elif ext == '.jpg':
            writer = vtk.vtkJPEGWriter()
        elif ext == '.pnm':
            writer = vtk.vtkPNMWriter()
        elif ext == '.ps':
            if rgba:
                rgba = False
            writer = vtk.vtkPostScriptWriter()
        elif ext == '.tiff':
            writer = vtk.vtkTIFFWriter()
        else:
            writer = vtk.vtkPNGWriter()

        windowto_image_filter = vtk.vtkWindowToImageFilter()
        windowto_image_filter.SetInput(renWin1)
        windowto_image_filter.SetScale(1)  # image quality
        if rgba:
            windowto_image_filter.SetInputBufferTypeToRGBA()
        else:
            windowto_image_filter.SetInputBufferTypeToRGB()
            # Read from the front buffer.
            windowto_image_filter.ReadFrontBufferOff()
            windowto_image_filter.Update()

        writer.SetFileName(fileName)
        writer.SetInputConnection(windowto_image_filter.GetOutputPort())
        writer.Write()
    else:
        raise RuntimeError('Need a filename.')
Beispiel #13
0
    def OnExportPicture(self, pubsub_evt):
        Publisher.sendMessage('Begin busy cursor')
        view_prop_list = []
        for slice_data in self.slice_data_list:
            view_prop_list.append(slice_data.box_actor)
            self.ren.RemoveViewProp(slice_data.box_actor)

        id, filename, filetype = pubsub_evt.data
        dict = {
            "AXIAL": const.AXIAL,
            "CORONAL": const.CORONAL,
            "SAGITAL": const.SAGITAL
        }

        if id == dict[self.orientation]:
            if filetype == const.FILETYPE_POV:
                renwin = self.interactor.GetRenderWindow()
                image = vtk.vtkWindowToImageFilter()
                image.SetInput(renwin)
                writer = vtk.vtkPOVExporter()
                writer.SetFilePrefix(filename.split(".")[0])
                writer.SetRenderWindow(renwin)
                writer.Write()
            else:
                ren = self.slice_data.renderer
                #Use tiling to generate a large rendering.
                image = vtk.vtkRenderLargeImage()
                image.SetInput(ren)
                image.SetMagnification(1)

                image = image.GetOutput()

                # write image file
                if (filetype == const.FILETYPE_BMP):
                    writer = vtk.vtkBMPWriter()
                elif (filetype == const.FILETYPE_JPG):
                    writer = vtk.vtkJPEGWriter()
                elif (filetype == const.FILETYPE_PNG):
                    writer = vtk.vtkPNGWriter()
                elif (filetype == const.FILETYPE_PS):
                    writer = vtk.vtkPostScriptWriter()
                elif (filetype == const.FILETYPE_TIF):
                    writer = vtk.vtkTIFFWriter()
                    filename = "%s.tif" % filename.strip(".tif")

                writer.SetInput(image)
                writer.SetFileName(filename)
                writer.Write()

            for actor in view_prop_list:
                self.ren.AddViewProp(actor)

        Publisher.sendMessage('End busy cursor')
Beispiel #14
0
    def OnExportPicture(self, pubsub_evt):
        Publisher.sendMessage('Begin busy cursor')
        view_prop_list = []
        for slice_data in self.slice_data_list:
            view_prop_list.append(slice_data.box_actor) 
            self.ren.RemoveViewProp(slice_data.box_actor)

        id, filename, filetype = pubsub_evt.data
        dict = {"AXIAL": const.AXIAL,
                "CORONAL": const.CORONAL,
                "SAGITAL": const.SAGITAL}

        if id == dict[self.orientation]:
            if filetype == const.FILETYPE_POV:
                renwin = self.interactor.GetRenderWindow()
                image = vtk.vtkWindowToImageFilter()
                image.SetInput(renwin)
                writer = vtk.vtkPOVExporter()
                writer.SetFilePrefix(filename.split(".")[0])
                writer.SetRenderWindow(renwin)
                writer.Write()
            else:
                ren = self.slice_data.renderer
                #Use tiling to generate a large rendering.
                image = vtk.vtkRenderLargeImage()
                image.SetInput(ren)
                image.SetMagnification(1)
                image.Update()

                image = image.GetOutput()


                # write image file
                if (filetype == const.FILETYPE_BMP):
                    writer = vtk.vtkBMPWriter()
                elif (filetype == const.FILETYPE_JPG):
                    writer =  vtk.vtkJPEGWriter()
                elif (filetype == const.FILETYPE_PNG):
                    writer = vtk.vtkPNGWriter()
                elif (filetype == const.FILETYPE_PS):
                    writer = vtk.vtkPostScriptWriter()
                elif (filetype == const.FILETYPE_TIF):
                    writer = vtk.vtkTIFFWriter()
                    filename = "%s.tif"%filename.strip(".tif")

                writer.SetInputData(image)
                writer.SetFileName(filename)
                writer.Write()

            for actor in view_prop_list:
                self.ren.AddViewProp(actor)

        Publisher.sendMessage('End busy cursor')
Beispiel #15
0
 def _get_image_writer(image_type: ImageTypes) -> None:
     """Get vtk image writer for each image type."""
     if image_type == ImageTypes.png:
         writer = vtk.vtkPNGWriter()
     elif image_type == ImageTypes.bmp:
         writer = vtk.vtkBMPWriter()
     elif image_type == ImageTypes.jpg:
         writer = vtk.vtkJPEGWriter()
     elif image_type == ImageTypes.pnm:
         writer = vtk.vtkPNMWriter()
     elif image_type == ImageTypes.ps:
         writer = vtk.vtkPostScriptWriter()
     elif image_type == ImageTypes.tiff:
         writer = vtk.vtkTIFFWriter()
     else:
         raise ValueError(f'Invalid image type: {image_type}')
     return writer
    def SaveAsBMP(self,filename,resolution=1):
        """Saves the window as bmp-file.

        Resolution is an integer representing the number of squares
        that the window is divided into when writing to the bmp-file. 
        Thus choosing a higher number improves the quality of the 
        saved image.
        """
        from vtk import vtkRenderLargeImage,vtkBMPWriter
        #self.UpdateLight()

        renderLarge = vtkRenderLargeImage()
        renderLarge.SetInput(self.GetRenderer())
        renderLarge.SetMagnification(resolution)

        writer = vtkBMPWriter()
        writer.SetFileName(filename)
        writer.SetInput(renderLarge.GetOutput())
        writer.Write()
    def SaveAsBMP(self, filename, resolution=1):
        """Saves the window as bmp-file.

        Resolution is an integer representing the number of squares
        that the window is divided into when writing to the bmp-file. 
        Thus choosing a higher number improves the quality of the 
        saved image.
        """
        from vtk import vtkRenderLargeImage, vtkBMPWriter
        #self.UpdateLight()

        renderLarge = vtkRenderLargeImage()
        renderLarge.SetInput(self.GetRenderer())
        renderLarge.SetMagnification(resolution)

        writer = vtkBMPWriter()
        writer.SetFileName(filename)
        writer.SetInput(renderLarge.GetOutput())
        writer.Write()
Beispiel #18
0
 def save_bmp (self, file_name=""): 
     debug ("In RenderWindow::save_bmp ()")
     if not file_name:
         file_name = tk_fsave (title="Export to BMP image",
                               initialdir=Common.config.initial_dir,
                               defaultextension=".bmp",
                               filetypes=[("BMP images", "*.bmp"), 
                                          ("All files", "*")])
     if len (file_name) != 0:
         Common.state.busy ()
         w2if = vtk.vtkWindowToImageFilter ()
         w2if.SetMagnification (Common.config.magnification)
         self.lift ()
         w2if.SetInput (self.renwin)
         ex = vtk.vtkBMPWriter ()
         ex.SetFileName (file_name)
         ex.SetInput (w2if.GetOutput ())
         ex.Write () 
         Common.state.idle ()
Beispiel #19
0
 def ExportToImageFile(self, filename, format):
     if format == "tif":
         writer = vtk.vtkTIFFWriter()
     elif format == "bmp":
         writer = vtk.vtkBMPWriter()
     elif format == "jpg":
         writer = vtk.vtkJPEGWriter()
     elif format == "png":
         writer = vtk.vtkPNGWriter()
     elif format == "pnm":
         writer = vtk.vtkPNMWriter()
     else:
         raise Exception("Unsupported export format")
     imageFilter = vtk.vtkWindowToImageFilter()
     imageFilter.SetInput(self.GetRenderWindow())
     writer.SetInputConnection(imageFilter.GetOutputPort())
     writer.SetFileName(filename)
     self.GetRenderWindow().Render()
     writer.Write()
Beispiel #20
0
    def _export_picture(self, id, filename, filetype):
        if filetype == const.FILETYPE_POV:
            renwin = self.interactor.GetRenderWindow()
            image = vtk.vtkWindowToImageFilter()
            image.SetInput(renwin)
            writer = vtk.vtkPOVExporter()
            writer.SetFileName(filename.encode(const.FS_ENCODE))
            writer.SetRenderWindow(renwin)
            writer.Write()
        else:
            #Use tiling to generate a large rendering.
            image = vtk.vtkRenderLargeImage()
            image.SetInput(self.ren)
            image.SetMagnification(1)
            image.Update()

            image = image.GetOutput()

            # write image file
            if (filetype == const.FILETYPE_BMP):
                writer = vtk.vtkBMPWriter()
            elif (filetype == const.FILETYPE_JPG):
                writer = vtk.vtkJPEGWriter()
            elif (filetype == const.FILETYPE_PNG):
                writer = vtk.vtkPNGWriter()
            elif (filetype == const.FILETYPE_PS):
                writer = vtk.vtkPostScriptWriter()
            elif (filetype == const.FILETYPE_TIF):
                writer = vtk.vtkTIFFWriter()
                filename = u"%s.tif" % filename.strip(".tif")

            writer.SetInputData(image)
            writer.SetFileName(filename.encode(const.FS_ENCODE))
            writer.Write()

        if not os.path.exists(filename):
            wx.MessageBox(_("InVesalius was not able to export this picture"),
                          _("Export picture error"))
Beispiel #21
0
    def OnExportPicture(self, pubsub_evt):
        Publisher.sendMessage('Begin busy cursor')
        id, filename, filetype = pubsub_evt.data
        if id == const.VOLUME:
            if filetype == const.FILETYPE_POV:
                renwin = self.interactor.GetRenderWindow()
                image = vtk.vtkWindowToImageFilter()
                image.SetInput(renwin)
                writer = vtk.vtkPOVExporter()
                writer.SetFileName(filename)
                writer.SetRenderWindow(renwin)
                writer.Write()
            else:
                #Use tiling to generate a large rendering.
                image = vtk.vtkRenderLargeImage()
                image.SetInput(self.ren)
                image.SetMagnification(1)
                image.Update()

                image = image.GetOutput()

                # write image file
                if (filetype == const.FILETYPE_BMP):
                    writer = vtk.vtkBMPWriter()
                elif (filetype == const.FILETYPE_JPG):
                    writer =  vtk.vtkJPEGWriter()
                elif (filetype == const.FILETYPE_PNG):
                    writer = vtk.vtkPNGWriter()
                elif (filetype == const.FILETYPE_PS):
                    writer = vtk.vtkPostScriptWriter()
                elif (filetype == const.FILETYPE_TIF):
                    writer = vtk.vtkTIFFWriter()
                    filename = "%s.tif"%filename.strip(".tif")

                writer.SetInputData(image)
                writer.SetFileName(filename)
                writer.Write()
        Publisher.sendMessage('End busy cursor')
Beispiel #22
0
    def OnExportPicture(self, pubsub_evt):
        Publisher.sendMessage('Begin busy cursor')
        id, filename, filetype = pubsub_evt.data
        if id == const.VOLUME:
            if filetype == const.FILETYPE_POV:
                renwin = self.interactor.GetRenderWindow()
                image = vtk.vtkWindowToImageFilter()
                image.SetInput(renwin)
                writer = vtk.vtkPOVExporter()
                writer.SetFileName(filename)
                writer.SetRenderWindow(renwin)
                writer.Write()
            else:
                #Use tiling to generate a large rendering.
                image = vtk.vtkRenderLargeImage()
                image.SetInput(self.ren)
                image.SetMagnification(1)
                image.Update()

                image = image.GetOutput()

                # write image file
                if (filetype == const.FILETYPE_BMP):
                    writer = vtk.vtkBMPWriter()
                elif (filetype == const.FILETYPE_JPG):
                    writer = vtk.vtkJPEGWriter()
                elif (filetype == const.FILETYPE_PNG):
                    writer = vtk.vtkPNGWriter()
                elif (filetype == const.FILETYPE_PS):
                    writer = vtk.vtkPostScriptWriter()
                elif (filetype == const.FILETYPE_TIF):
                    writer = vtk.vtkTIFFWriter()
                    filename = "%s.tif" % filename.strip(".tif")

                writer.SetInputData(image)
                writer.SetFileName(filename)
                writer.Write()
        Publisher.sendMessage('End busy cursor')
Beispiel #23
0
def write(objct, fileoutput, binary=True):
    """
    Write 3D object to file. (same as `save()`).

    Possile extensions are:
        - vtk, vti, npy, ply, obj, stl, byu, vtp, vti, mhd, xyz, tif, png, bmp.
    """
    obj = objct
    if isinstance(obj, Mesh): # picks transformation
        obj = objct.polydata(True)
    elif isinstance(obj, (vtk.vtkActor, vtk.vtkVolume)):
        obj = objct.GetMapper().GetInput()
    elif isinstance(obj, (vtk.vtkPolyData, vtk.vtkImageData)):
        obj = objct

    fr = fileoutput.lower()
    if   fr.endswith(".vtk"):
        writer = vtk.vtkPolyDataWriter()
    elif fr.endswith(".ply"):
        writer = vtk.vtkPLYWriter()
        pscal = obj.GetPointData().GetScalars()
        if not pscal:
            pscal = obj.GetCellData().GetScalars()
        if pscal and pscal.GetName():
            writer.SetArrayName(pscal.GetName())
            #writer.SetColorMode(0)
        lut = objct.GetMapper().GetLookupTable()
        if lut:
            writer.SetLookupTable(lut)
    elif fr.endswith(".stl"):
        writer = vtk.vtkSTLWriter()
    elif fr.endswith(".vtp"):
        writer = vtk.vtkXMLPolyDataWriter()
    elif fr.endswith(".vtm"):
        g = vtk.vtkMultiBlockDataGroupFilter()
        for ob in objct:
            if isinstance(ob, Mesh): # picks transformation
                ob = ob.polydata(True)
            elif isinstance(ob, (vtk.vtkActor, vtk.vtkVolume)):
                ob = ob.GetMapper().GetInput()
            g.AddInputData(ob)
        g.Update()
        mb = g.GetOutputDataObject(0)
        wri = vtk.vtkXMLMultiBlockDataWriter()
        wri.SetInputData(mb)
        wri.SetFileName(fileoutput)
        wri.Write()
        return mb
    elif fr.endswith(".xyz"):
        writer = vtk.vtkSimplePointsWriter()
    elif fr.endswith(".facet"):
        writer = vtk.vtkFacetWriter()
    elif fr.endswith(".tif"):
        writer = vtk.vtkTIFFWriter()
        writer.SetFileDimensionality(len(obj.GetDimensions()))
    elif fr.endswith(".vti"):
        writer = vtk.vtkXMLImageDataWriter()
    elif fr.endswith(".mhd"):
        writer = vtk.vtkMetaImageWriter()
    elif fr.endswith(".nii"):
        writer = vtk.vtkNIFTIImageWriter()
    elif fr.endswith(".png"):
        writer = vtk.vtkPNGWriter()
    elif fr.endswith(".jpg"):
        writer = vtk.vtkJPEGWriter()
    elif fr.endswith(".bmp"):
        writer = vtk.vtkBMPWriter()
    elif fr.endswith(".npy"):
        if utils.isSequence(objct):
            objslist = objct
        else:
            objslist = [objct]
        dicts2save = []
        for obj in objslist:
            dicts2save.append( _np_dump(obj) )
        np.save(fileoutput, dicts2save)
        return dicts2save

    elif fr.endswith(".obj"):
        outF = open(fileoutput, "w")
        outF.write('# OBJ file format with ext .obj\n')
        outF.write('# File Created by vtkplotter\n')
        cobjct = objct.clone().clean()

        for p in cobjct.points():
            outF.write('v '+ str(p[0]) +" "+ str(p[1])+" "+ str(p[2])+'\n')

        for vn in cobjct.normals(cells=False):
            outF.write('vn '+str(vn[0])+" "+str(vn[1])+" "+str(vn[2])+'\n')

        #pdata = cobjct.polydata().GetPointData().GetScalars()
        #if pdata:
        #    ndata = vtk_to_numpy(pdata)
        #    for vd in ndata:
        #        outF.write('vp '+ str(vd) +'\n')

        #ptxt = cobjct.polydata().GetPointData().GetTCoords() # not working
        #if ptxt:
        #    ntxt = vtk_to_numpy(ptxt)
        #    print(len(cobjct.faces()), cobjct.points().shape, ntxt.shape)
        #    for vt in ntxt:
        #        outF.write('vt '+ str(vt[0]) +" "+ str(vt[1])+ ' 0\n')

        for f in cobjct.faces():
            fs = ''
            for fi in f:
                fs += " "+str(fi+1)
            outF.write('f' + fs + '\n')

        #ldata = cobjct.polydata().GetLines().GetData()
        #print(cobjct.polydata().GetLines())
        #if ldata:
        #    ndata = vtk_to_numpy(ldata)
        #    print(ndata)
        #    for l in ndata:
        #        ls = ''
        #        for li in l:
        #            ls += str(li+1)+" "
        #        outF.write('l '+ ls + '\n')

        outF.close()
        return objct

    elif fr.endswith(".xml"):  # write tetrahedral dolfin xml
        vertices = objct.points().astype(str)
        faces = np.array(objct.faces()).astype(str)
        ncoords = vertices.shape[0]
        outF = open(fileoutput, "w")
        outF.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        outF.write('<dolfin xmlns:dolfin="http://www.fenicsproject.org">\n')

        if len(faces[0]) == 4:# write tetrahedral mesh
            ntets = faces.shape[0]
            outF.write('  <mesh celltype="tetrahedron" dim="3">\n')
            outF.write('    <vertices size="' + str(ncoords) + '">\n')
            for i in range(ncoords):
                x, y, z = vertices[i]
                outF.write('      <vertex index="'+str(i)+'" x="'+x+'" y="'+y+'" z="'+z+'"/>\n')
            outF.write('    </vertices>\n')
            outF.write('    <cells size="' + str(ntets) + '">\n')
            for i in range(ntets):
                v0, v1, v2, v3 = faces[i]
                outF.write('     <tetrahedron index="'+str(i)
                           + '" v0="'+v0+'" v1="'+v1+'" v2="'+v2+'" v3="'+v3+'"/>\n')

        elif len(faces[0]) == 3:# write triangle mesh
            ntri = faces.shape[0]
            outF.write('  <mesh celltype="triangle" dim="2">\n')
            outF.write('    <vertices size="' + str(ncoords) + '">\n')
            for i in range(ncoords):
                x, y, dummy_z = vertices[i]
                outF.write('      <vertex index="'+str(i)+'" x="'+x+'" y="'+y+'"/>\n')
            outF.write('    </vertices>\n')
            outF.write('    <cells size="' + str(ntri) + '">\n')
            for i in range(ntri):
                v0, v1, v2 = faces[i]
                outF.write('     <triangle index="'+str(i)+'" v0="'+v0+'" v1="'+v1+'" v2="'+v2+'"/>\n')

        outF.write('    </cells>\n')
        outF.write("  </mesh>\n")
        outF.write("</dolfin>\n")
        outF.close()
        return objct

    else:
        colors.printc("~noentry Unknown format", fileoutput, "file not saved.", c="r")
        return objct

    try:
        if hasattr(writer, 'SetFileTypeToBinary'):
            if binary:
                writer.SetFileTypeToBinary()
            else:
                writer.SetFileTypeToASCII()
        writer.SetInputData(obj)
        writer.SetFileName(fileoutput)
        writer.Write()
    except Exception as e:
        colors.printc("~noentry Error saving: " + fileoutput, "\n", e, c="r")
    return objct
 def test_get_bmp(self):
     '''bmp filetype returns None'''
     expected = type(vtk.vtkBMPWriter())
     self.assertEqual(type(get_vtk_writer('test.Bmp')), expected)
Beispiel #25
0
def write(objct, fileoutput, binary=True):
    """
    Write 3D object to file. (same as `save()`).

    Possile extensions are:
        - vtk, vti, ply, obj, stl, byu, vtp, vti, mhd, xyz, tif, png, bmp.
    """
    obj = objct
    if isinstance(obj, Actor):  # picks transformation
        obj = objct.polydata(True)
    elif isinstance(obj, (vtk.vtkActor, vtk.vtkVolume)):
        obj = objct.GetMapper().GetInput()
    elif isinstance(obj, (vtk.vtkPolyData, vtk.vtkImageData)):
        obj = objct

    fr = fileoutput.lower()
    if ".vtk" in fr:
        w = vtk.vtkPolyDataWriter()
    elif ".ply" in fr:
        w = vtk.vtkPLYWriter()
    elif ".stl" in fr:
        w = vtk.vtkSTLWriter()
    elif ".vtp" in fr:
        w = vtk.vtkXMLPolyDataWriter()
    elif ".vtm" in fr:
        g = vtk.vtkMultiBlockDataGroupFilter()
        for ob in objct:
            g.AddInputData(ob)
        g.Update()
        mb = g.GetOutputDataObject(0)
        wri = vtk.vtkXMLMultiBlockDataWriter()
        wri.SetInputData(mb)
        wri.SetFileName(fileoutput)
        wri.Write()
        return mb
    elif ".xyz" in fr:
        w = vtk.vtkSimplePointsWriter()
    elif ".facet" in fr:
        w = vtk.vtkFacetWriter()
    elif ".tif" in fr:
        w = vtk.vtkTIFFWriter()
        w.SetFileDimensionality(len(obj.GetDimensions()))
    elif ".vti" in fr:
        w = vtk.vtkXMLImageDataWriter()
    elif ".mhd" in fr:
        w = vtk.vtkMetaImageWriter()
    elif ".png" in fr:
        w = vtk.vtkPNGWriter()
    elif ".jpg" in fr:
        w = vtk.vtkJPEGWriter()
    elif ".bmp" in fr:
        w = vtk.vtkBMPWriter()
    elif ".xml" in fr:  # write tetrahedral dolfin xml
        vertices = obj.coordinates()
        faces = obj.cells()
        ncoords = vertices.shape[0]
        ntets = faces.shape[0]
        outF = open(fileoutput, "w")
        outF.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        outF.write('<dolfin xmlns:dolfin="http://www.fenicsproject.org">\n')
        outF.write('  <mesh celltype="tetrahedron" dim="3">\n')
        outF.write('    <vertices size="' + str(ncoords) + '">\n')
        for i in range(ncoords):
            x, y, z = vertices[i]
            outF.write('      <vertex index="' + str(i) + '" x="' + str(x) +
                       '" y="' + str(y) + '" z="' + str(z) + '"/>\n')
        outF.write('    </vertices>\n')
        outF.write('    <cells size="' + str(ntets) + '">\n')
        for i in range(ntets):
            v0, v1, v2, v3 = faces[i]
            outF.write('      <tetrahedron index="' + str(i) + '" v0="' +
                       str(v0) + '" v1="' + str(v1) + '" v2="' + str(v2) +
                       '" v3="' + str(v3) + '"/>\n')
        outF.write('    </cells>\n')
        outF.write("  </mesh>\n")
        outF.write("</dolfin>\n")
        outF.close()
        return objct
    else:
        colors.printc("~noentry Unknown format",
                      fileoutput,
                      "file not saved.",
                      c="r")
        return objct

    try:
        if hasattr(w, 'SetFileTypeToBinary'):
            if binary:
                w.SetFileTypeToBinary()
            else:
                w.SetFileTypeToASCII()
        w.SetInputData(obj)
        w.SetFileName(fileoutput)
        w.Write()
        colors.printc("~save Saved file: " + fileoutput, c="g")
    except Exception as e:
        colors.printc("~noentry Error saving: " + fileoutput, "\n", e, c="r")
    return objct
Beispiel #26
0
#
dir = "."
if (info.commands(globals(), locals(),  "rtTester") == "rtTester"):
    dir = rtTester.GetTempDirectory()
    pass
# make sure it is writeable first
if (catch.catch(globals(),"""channel = open("" + str(dir) + "/test.tmp", "w")""") == 0):
    channel.close()
    file.delete("-force", "" + str(dir) + "/test.tmp")
    tiff1 = vtk.vtkTIFFWriter()
    tiff1.SetInputConnection(image1.GetOutputPort())
    tiff1.SetFileName("" + str(dir) + "/tiff1.tif")
    tiff2 = vtk.vtkTIFFWriter()
    tiff2.SetInputConnection(luminance.GetOutputPort())
    tiff2.SetFileName("" + str(dir) + "/tiff2.tif")
    bmp1 = vtk.vtkBMPWriter()
    bmp1.SetInputConnection(image1.GetOutputPort())
    bmp1.SetFileName("" + str(dir) + "/bmp1.bmp")
    bmp2 = vtk.vtkBMPWriter()
    bmp2.SetInputConnection(luminance.GetOutputPort())
    bmp2.SetFileName("" + str(dir) + "/bmp2.bmp")
    pnm1 = vtk.vtkPNMWriter()
    pnm1.SetInputConnection(image1.GetOutputPort())
    pnm1.SetFileName("" + str(dir) + "/pnm1.pnm")
    pnm2 = vtk.vtkPNMWriter()
    pnm2.SetInputConnection(luminance.GetOutputPort())
    pnm2.SetFileName("" + str(dir) + "/pnm2.pnm")
    psw1 = vtk.vtkPostScriptWriter()
    psw1.SetInputConnection(image1.GetOutputPort())
    psw1.SetFileName("" + str(dir) + "/psw1.ps")
    psw2 = vtk.vtkPostScriptWriter()
Beispiel #27
0
dir = "."
if (info.commands(globals(), locals(), "rtTester") == "rtTester"):
    dir = rtTester.GetTempDirectory()
    pass
# make sure it is writeable first
if (catch.catch(globals(),
                """channel = open("" + str(dir) + "/test.tmp", "w")""") == 0):
    channel.close()
    file.delete("-force", "" + str(dir) + "/test.tmp")
    tiff1 = vtk.vtkTIFFWriter()
    tiff1.SetInputConnection(image1.GetOutputPort())
    tiff1.SetFileName("" + str(dir) + "/tiff1.tif")
    tiff2 = vtk.vtkTIFFWriter()
    tiff2.SetInputConnection(luminance.GetOutputPort())
    tiff2.SetFileName("" + str(dir) + "/tiff2.tif")
    bmp1 = vtk.vtkBMPWriter()
    bmp1.SetInputConnection(image1.GetOutputPort())
    bmp1.SetFileName("" + str(dir) + "/bmp1.bmp")
    bmp2 = vtk.vtkBMPWriter()
    bmp2.SetInputConnection(luminance.GetOutputPort())
    bmp2.SetFileName("" + str(dir) + "/bmp2.bmp")
    pnm1 = vtk.vtkPNMWriter()
    pnm1.SetInputConnection(image1.GetOutputPort())
    pnm1.SetFileName("" + str(dir) + "/pnm1.pnm")
    pnm2 = vtk.vtkPNMWriter()
    pnm2.SetInputConnection(luminance.GetOutputPort())
    pnm2.SetFileName("" + str(dir) + "/pnm2.pnm")
    psw1 = vtk.vtkPostScriptWriter()
    psw1.SetInputConnection(image1.GetOutputPort())
    psw1.SetFileName("" + str(dir) + "/psw1.ps")
    psw2 = vtk.vtkPostScriptWriter()
Beispiel #28
0
    def save_bmp(self, filename):
        """
		Save the rendered screen as bmp
		"""
        self.saveScreen(vtk.vtkBMPWriter(), filename)
Beispiel #29
0
#    print camera2.GetPosition()
#    print camera2.GetFocalPoint()
#    print camera2.GetViewUp()
#    print camera2.GetViewAngle()
#    print camera2.GetClippingRange()
#    print camera2.GetEyeAngle()
#    print volume.GetBounds()  # (0.0, 255.0, 0.0, 255.0, 0.0, 255.0)
    ren.AddVolume(volume)
    ren.SetBackground(0, 0, 0)
    renWin = vtk.vtkRenderWindow()
#    iren = vtk.vtkRenderWindowInteractor()
#    iren.SetRenderWindow(renWin)
    renWin.SetSize(600, 600)
    renWin.AddRenderer(ren)
    renWin.Render()
    window_2_image = vtk.vtkWindowToImageFilter()
    window_2_image.SetInput(renWin)
    window_2_image.Update()
    
    png_writer = vtk.vtkBMPWriter()
    png_writer.SetFileName(dst + '%05d'%(i) + '.bmp')
    png_writer.SetInput(window_2_image.GetOutput())
    png_writer.Write()    
#    iren.Initialize()
#    iren.Start()    
    print i
    i += 1



Beispiel #30
0
        prop_volume.SetColor(vtk_color_map)

        # camera
        camera.Elevation(elev)
        camera.Azimuth(azimuth)
        camera.Roll(roll)
        camera.Zoom(zoom)

        # render to image
        render_window.Render()
        window_to_image = vtk.vtkWindowToImageFilter()
        window_to_image.SetInputBufferTypeToRGBA()
        window_to_image.SetInput(render_window)
        window_to_image.Update()

        image_writer = vtk.vtkBMPWriter()
        image_writer.SetFileName(output_img_dir + rel_filename)
        image_writer.SetInputConnection(window_to_image.GetOutputPort())
        image_writer.Write()

        # undo camera
        camera.Zoom(1.0 / zoom)
        camera.Roll(-roll)
        camera.Azimuth(-azimuth)
        camera.Elevation(-elev)

    input_name = 'input' + str(ind) + '.csv'
    flattened_opacity_map = opacity_map.reshape(opacity_map.shape[0] *
                                                opacity_map.shape[1])
    flattened_color_map = color_map.reshape(color_map.shape[0] *
                                            color_map.shape[1])
Beispiel #31
0
    #    ren.SetActiveCamera(camera2)
    #    camera2.SetFocalPoint(0.0, 0.0, 0.0)
    #    camera2.SetPosition(0.0, 0.0, 50.0)
    #    print camera2.GetPosition()
    #    print camera2.GetFocalPoint()
    #    print camera2.GetViewUp()
    #    print camera2.GetViewAngle()
    #    print camera2.GetClippingRange()
    #    print camera2.GetEyeAngle()
    #    print volume.GetBounds()  # (0.0, 255.0, 0.0, 255.0, 0.0, 255.0)
    ren.AddVolume(volume)
    ren.SetBackground(0, 0, 0)
    renWin = vtk.vtkRenderWindow()
    #    iren = vtk.vtkRenderWindowInteractor()
    #    iren.SetRenderWindow(renWin)
    renWin.SetSize(600, 600)
    renWin.AddRenderer(ren)
    renWin.Render()
    window_2_image = vtk.vtkWindowToImageFilter()
    window_2_image.SetInput(renWin)
    window_2_image.Update()

    png_writer = vtk.vtkBMPWriter()
    png_writer.SetFileName(dst + '%05d' % (i) + '.bmp')
    png_writer.SetInput(window_2_image.GetOutput())
    png_writer.Write()
    #    iren.Initialize()
    #    iren.Start()
    print i
    i += 1
    def save_bmp(self, filename):
        """
		Save the rendered screen as bmp
		"""
        self.saveScreen(vtk.vtkBMPWriter(), filename)
Beispiel #33
0
def write(obj, fileoutput, binary=True):
    '''
    Write 3D object to file.

    Possile extensions are: 
        vtk, vti, ply, obj, stl, byu, vtp, xyz, tif, png, bmp
    '''
    if isinstance(obj, Actor):
        obj = obj.polydata(True)
    elif isinstance(obj, vtk.vtkActor):
        obj = obj.GetMapper().GetInput()

    fr = fileoutput.lower()
    if '.vtk' in fr:
        w = vtk.vtkPolyDataWriter()
    elif '.ply' in fr:
        w = vtk.vtkPLYWriter()
    elif '.stl' in fr:
        w = vtk.vtkSTLWriter()
    elif '.vtp' in fr:
        w = vtk.vtkXMLPolyDataWriter()
    elif '.xyz' in fr:
        w = vtk.vtkSimplePointsWriter()
    elif '.byu' in fr or fr.endswith('.g'):
        w = vtk.vtkBYUWriter()
    elif '.obj' in fr:
        obj = obj.polydata(True)
        w = vtk.vtkOBJExporter()
        w.SetFilePrefix(fileoutput.replace('.obj', ''))
        colors.printc('Please use write(vp.renderWin)', c=3)
        w.SetInputData(obj)
        w.Update()
        colors.printc("Saved file: " + fileoutput, c='g')
        return
    elif '.tif' in fr:
        w = vtk.vtkTIFFWriter()
        w.SetFileDimensionality(len(obj.GetDimensions()))
    elif '.vti' in fr:
        w = vtk.vtkXMLImageDataWriter()
    elif '.png' in fr:
        w = vtk.vtkPNGWriter()
    elif '.jpg' in fr:
        w = vtk.vtkJPEGWriter()
    elif '.bmp' in fr:
        w = vtk.vtkBMPWriter()
    else:
        colors.printc('Unknown format', fileoutput, 'file not saved.', c='r')
        return

    try:
        if binary:
            w.SetFileTypeToBinary()
        else:
            w.SetFileTypeToASCII()
        w.SetInputData(obj)
        w.SetFileName(fileoutput)
        w.Write()
        colors.printc("Saved file: " + fileoutput, c='g')
    except Exception as e:
        colors.printc("Error saving: " + fileoutput, '\n', e, c='r')
    return
Beispiel #34
0
def saveRendererToImg(renderer,fnOut,magnification=10):
	
	"""Saves renderer to image file.
	
	Supported extensions are:
		
		* '.ps'  (PostScript)
		* '.eps' (Encapsualted PostScript)
		* '.pdf' (Portable Document Format)
		* '.jpg' (Joint Photographic Experts Group)
		* '.png' (Portable Network Graphics)
		* '.pnm' (Portable Any Map)
		* '.tif' (Tagged Image File Format)
		* '.bmp' (Bitmap Image)
	
	Some code taken from http://www.programcreek.com/python/example/23102/vtk.vtkGL2PSExporter .
	
	Args:
		fnOut (str): Path to output file.
		renderer (vtk.vtkOpenGLRenderer): Renderer.
		
	Keyword Args:
		magnification (int): Degree of magnification.
		
	Returns:
		vtk.vtkExporter: Exporter object.
	
	"""
	
	
	#Generate exporter
	vtkImageWriters = {
		'.tif': vtk.vtkTIFFWriter(),
		'.tiff': vtk.vtkTIFFWriter(),
		'.bmp': vtk.vtkBMPWriter(),
		'.pnm': vtk.vtkPNMWriter(),
		'.png': vtk.vtkPNGWriter(),
		'.jpg': vtk.vtkJPEGWriter(),
		'.jpeg': vtk.vtkJPEGWriter(),
		'.ps': vtk.vtkPostScriptWriter(),
		'.eps': vtk.vtkPostScriptWriter(),  
		}
	
	#Get extension
	basename,ext=os.path.splitext(fnOut)

	#Large Image renderer for nicer images
	rendererLarge=vtk.vtkRenderLargeImage()
	rendererLarge.SetInput(renderer)
	rendererLarge.SetMagnification(magnification)

	#Get proper writer
	try:
		writer = vtkImageWriters[ext.lower()]
	except KeyError:
		printError("Extension "+ext+" is currently not supported")
		return None
	
	#Write
	writer.SetFileName(fnOut)
	
	writer.SetInputConnection(rendererLarge.GetOutputPort())
	writer.Write()

	return writer
Beispiel #35
0
def write(objct, fileoutput, binary=True):
    """
    Write 3D object to file. (same as `save()`).

    Possile extensions are:
        - vtk, vti, npy, ply, obj, stl, byu, vtp, vti, mhd, xyz, tif, png, bmp.
    """
    obj = objct
    if isinstance(obj, Actor): # picks transformation
        obj = objct.polydata(True)
    elif isinstance(obj, (vtk.vtkActor, vtk.vtkVolume)):
        obj = objct.GetMapper().GetInput()
    elif isinstance(obj, (vtk.vtkPolyData, vtk.vtkImageData)):
        obj = objct

    fr = fileoutput.lower()
    if   ".vtk" in fr:
        writer = vtk.vtkPolyDataWriter()
    elif ".ply" in fr:
        writer = vtk.vtkPLYWriter()
        pscal = obj.GetPointData().GetScalars()
        if not pscal:
            pscal = obj.GetCellData().GetScalars()
        if pscal and pscal.GetName():
            writer.SetArrayName(pscal.GetName())
            #writer.SetColorMode(0)
        lut = objct.GetMapper().GetLookupTable()
        if lut:
            writer.SetLookupTable(lut)
    elif ".stl" in fr:
        writer = vtk.vtkSTLWriter()
    elif ".obj" in fr:
        writer = vtk.vtkOBJWriter()
    elif ".vtp" in fr:
        writer = vtk.vtkXMLPolyDataWriter()
    elif ".vtm" in fr:
        g = vtk.vtkMultiBlockDataGroupFilter()
        for ob in objct:
            g.AddInputData(ob)
        g.Update()
        mb = g.GetOutputDataObject(0)
        wri = vtk.vtkXMLMultiBlockDataWriter()
        wri.SetInputData(mb)
        wri.SetFileName(fileoutput)
        wri.Write()
        return mb
    elif ".xyz" in fr:
        writer = vtk.vtkSimplePointsWriter()
    elif ".facet" in fr:
        writer = vtk.vtkFacetWriter()
    elif ".tif" in fr:
        writer = vtk.vtkTIFFWriter()
        writer.SetFileDimensionality(len(obj.GetDimensions()))
    elif ".vti" in fr:
        writer = vtk.vtkXMLImageDataWriter()
    elif ".mhd" in fr:
        writer = vtk.vtkMetaImageWriter()
    elif ".nii" in fr:
        writer = vtk.vtkNIFTIImageWriter()
    elif ".png" in fr:
        writer = vtk.vtkPNGWriter()
    elif ".jpg" in fr:
        writer = vtk.vtkJPEGWriter()
    elif ".bmp" in fr:
        writer = vtk.vtkBMPWriter()
    elif ".npy" in fr:
        if utils.isSequence(objct):
            objslist = objct
        else:
            objslist = [objct]
        dicts2save = []
        for obj in objslist:
            dicts2save.append( _np_dump(obj) )
        np.save(fileoutput, dicts2save)
        return dicts2save

    elif ".xml" in fr:  # write tetrahedral dolfin xml
        vertices = objct.coordinates().astype(str)
        faces = np.array(objct.faces()).astype(str)
        ncoords = vertices.shape[0]
        outF = open(fileoutput, "w")
        outF.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        outF.write('<dolfin xmlns:dolfin="http://www.fenicsproject.org">\n')

        if len(faces[0]) == 4:# write tetrahedral mesh
            ntets = faces.shape[0]
            outF.write('  <mesh celltype="tetrahedron" dim="3">\n')
            outF.write('    <vertices size="' + str(ncoords) + '">\n')
            for i in range(ncoords):
                x, y, z = vertices[i]
                outF.write('      <vertex index="'+str(i)+'" x="'+x+'" y="'+y+'" z="'+z+'"/>\n')
            outF.write('    </vertices>\n')
            outF.write('    <cells size="' + str(ntets) + '">\n')
            for i in range(ntets):
                v0, v1, v2, v3 = faces[i]
                outF.write('     <tetrahedron index="'+str(i)
                           + '" v0="'+v0+'" v1="'+v1+'" v2="'+v2+'" v3="'+v3+'"/>\n')

        elif len(faces[0]) == 3:# write triangle mesh
            ntri = faces.shape[0]
            outF.write('  <mesh celltype="triangle" dim="2">\n')
            outF.write('    <vertices size="' + str(ncoords) + '">\n')
            for i in range(ncoords):
                x, y, dummy_z = vertices[i]
                outF.write('      <vertex index="'+str(i)+'" x="'+x+'" y="'+y+'"/>\n')
            outF.write('    </vertices>\n')
            outF.write('    <cells size="' + str(ntri) + '">\n')
            for i in range(ntri):
                v0, v1, v2 = faces[i]
                outF.write('     <triangle index="'+str(i)+'" v0="'+v0+'" v1="'+v1+'" v2="'+v2+'"/>\n')

        outF.write('    </cells>\n')
        outF.write("  </mesh>\n")
        outF.write("</dolfin>\n")
        outF.close()
        return objct

    else:
        colors.printc("~noentry Unknown format", fileoutput, "file not saved.", c="r")
        return objct

    try:
        if hasattr(writer, 'SetFileTypeToBinary'):
            if binary:
                writer.SetFileTypeToBinary()
            else:
                writer.SetFileTypeToASCII()
        writer.SetInputData(obj)
        writer.SetFileName(fileoutput)
        writer.Write()
        colors.printc("~save Saved file: " + fileoutput, c="g")
    except Exception as e:
        colors.printc("~noentry Error saving: " + fileoutput, "\n", e, c="r")
    return objct
Beispiel #36
0
def saveRendererToImg(renderer, fnOut, magnification=10):
    """Saves renderer to image file.
	
	Supported extensions are:
		
		* '.ps'  (PostScript)
		* '.eps' (Encapsualted PostScript)
		* '.pdf' (Portable Document Format)
		* '.jpg' (Joint Photographic Experts Group)
		* '.png' (Portable Network Graphics)
		* '.pnm' (Portable Any Map)
		* '.tif' (Tagged Image File Format)
		* '.bmp' (Bitmap Image)
	
	Some code taken from http://www.programcreek.com/python/example/23102/vtk.vtkGL2PSExporter .
	
	Args:
		fnOut (str): Path to output file.
		renderer (vtk.vtkOpenGLRenderer): Renderer.
		
	Keyword Args:
		magnification (int): Degree of magnification.
		
	Returns:
		vtk.vtkExporter: Exporter object.
	
	"""

    #Generate exporter
    vtkImageWriters = {
        '.tif': vtk.vtkTIFFWriter(),
        '.tiff': vtk.vtkTIFFWriter(),
        '.bmp': vtk.vtkBMPWriter(),
        '.pnm': vtk.vtkPNMWriter(),
        '.png': vtk.vtkPNGWriter(),
        '.jpg': vtk.vtkJPEGWriter(),
        '.jpeg': vtk.vtkJPEGWriter(),
        '.ps': vtk.vtkPostScriptWriter(),
        '.eps': vtk.vtkPostScriptWriter(),
    }

    #Get extension
    basename, ext = os.path.splitext(fnOut)

    #Large Image renderer for nicer images
    rendererLarge = vtk.vtkRenderLargeImage()
    rendererLarge.SetInput(renderer)
    rendererLarge.SetMagnification(magnification)

    #Get proper writer
    try:
        writer = vtkImageWriters[ext.lower()]
    except KeyError:
        printError("Extension " + ext + " is currently not supported")
        return None

    #Write
    writer.SetFileName(fnOut)

    writer.SetInputConnection(rendererLarge.GetOutputPort())
    writer.Write()

    return writer