Example #1
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()
Example #2
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
    def save_tiff(self, filename):
        """
		Save the rendered screen as TIFF
		"""
        tifwriter = vtk.vtkTIFFWriter()
        tifwriter.SetCompressionToNoCompression()
        self.saveScreen(tifwriter, filename)
Example #4
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()
Example #5
0
    def write_picture(self, magnify, fname):
        ren = self.getRenderer()
        assert ren is not None
        renderLarge = vtk.vtkRenderLargeImage()
        renderLarge.SetInput(ren)
        renderLarge.SetMagnification(magnify)

        rotation = 'x'
        self.set_rotation(rotation)

        lfname = fname.lower()
        if lfname.endswith('.png'):
            writer = vtk.vtkPNGWriter()
        elif lfname.endswith('.jpeg'):
            writer = vtk.vtkJPEGWriter()
        elif lfname.endswith('.tiff'):
            writer = vtk.vtkTIFFWriter()
        elif lfname.endswith('.ps'):
            writer = vtk.vtkPostScriptWriter()
        else:
            writer = vtk.vtkPNGWriter()

        writer.SetInput(renderLarge.GetOutput())
        writer.SetFileName(fname)
        writer.Write()
Example #6
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkTIFFWriter(), 'Writing vtkTIFF.',
         ('vtkTIFF',), (),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Example #7
0
    def output_screenshot(self, screenshot_fname, file_format='png', screenshot_data=None):
        """
        Saves scene rendered in the renderer to the image
        :param ren: {vtkRenderer} renderer
        :param screenshot_fname: {str} screenshot filename
        :return: None
        """

        ren = self.get_renderer()
        ren_win = vtk.vtkRenderWindow()
        ren_win.SetOffScreenRendering(1)

        if screenshot_data is not None:
            ren_win.SetSize(screenshot_data.win_width, screenshot_data.win_height)

        ren_win.AddRenderer(ren)
        ren_win.Render()

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

        if file_format.lower() == 'png':
            writer = vtk.vtkPNGWriter()
        elif file_format.lower() == 'tiff':
            writer = vtk.vtkTIFFWriter()
            screenshot_fname = splitext(screenshot_fname)[0] + '.tif'
        else:
            writer = vtk.vtkPNGWriter()

        writer.SetFileName(screenshot_fname)

        writer.SetInputConnection(windowToImageFilter.GetOutputPort())
        writer.Write()
Example #8
0
    def save_tiff(self, filename):
        """
		Save the rendered screen as TIFF
		"""
        tifwriter = vtk.vtkTIFFWriter()
        tifwriter.SetCompressionToNoCompression()
        self.saveScreen(tifwriter, filename)
Example #9
0
 def WriteTIFFImageFile(self):
     if (self.OutputFileName == ''):
         self.PrintError('Error: no OutputFileName.')
     self.PrintLog('Writing TIFF image file.')
     outputImage = self.Image
     if self.Image.GetScalarTypeAsString() != 'unsigned char':
         shiftScale = vtk.vtkImageShiftScale()
         shiftScale.SetInputData(self.Image)
         if self.WindowLevel[0] == 0.0:
             scalarRange = self.Image.GetScalarRange()
             shiftScale.SetShift(-scalarRange[0])
             shiftScale.SetScale(255.0/(scalarRange[1]-scalarRange[0]))
         else: 
             shiftScale.SetShift(-(self.WindowLevel[1]-self.WindowLevel[0]/2.0))
             shiftScale.SetScale(255.0/self.WindowLevel[0])
         shiftScale.SetOutputScalarTypeToUnsignedChar()
         shiftScale.ClampOverflowOn()
         shiftScale.Update()
         outputImage = shiftScale.GetOutput()
     writer = vtk.vtkTIFFWriter()
     writer.SetInputData(outputImage)
     if self.Image.GetDimensions()[2] == 1:
         writer.SetFileName(self.OutputFileName)
     else:
         writer.SetFilePrefix(self.OutputFileName)
         writer.SetFilePattern("%s%04d.tif")
     writer.Write()
Example #10
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
Example #11
0
 def WriteTIFFImageFile(self):
     if (self.OutputFileName == ''):
         self.PrintError('Error: no OutputFileName.')
     self.PrintLog('Writing TIFF image file.')
     outputImage = self.Image
     if self.Image.GetScalarTypeAsString() != 'unsigned char':
         shiftScale = vtk.vtkImageShiftScale()
         shiftScale.SetInputData(self.Image)
         if self.WindowLevel[0] == 0.0:
             scalarRange = self.Image.GetScalarRange()
             shiftScale.SetShift(-scalarRange[0])
             shiftScale.SetScale(255.0 / (scalarRange[1] - scalarRange[0]))
         else:
             shiftScale.SetShift(-(self.WindowLevel[1] -
                                   self.WindowLevel[0] / 2.0))
             shiftScale.SetScale(255.0 / self.WindowLevel[0])
         shiftScale.SetOutputScalarTypeToUnsignedChar()
         shiftScale.ClampOverflowOn()
         shiftScale.Update()
         outputImage = shiftScale.GetOutput()
     writer = vtk.vtkTIFFWriter()
     writer.SetInputData(outputImage)
     if self.Image.GetDimensions()[2] == 1:
         writer.SetFileName(self.OutputFileName)
     else:
         writer.SetFilePrefix(self.OutputFileName)
         writer.SetFilePattern("%s%04d.tif")
     writer.Write()
Example #12
0
    def take_multi_rotation_screen_shot(self, path, angleRot):
        WindowToImageFilter = vtk.vtkWindowToImageFilter()

        WindowToImageFilter.SetInput(self.renWin)
        TIFFWriter = vtk.vtkTIFFWriter()
        TIFFWriter.SetInputConnection(WindowToImageFilter.GetOutputPort())

        self.ren.GetActiveCamera().SetFocalPoint(self.shape_data[2] / 2.0,
                                                 self.shape_data[1] / 2.0,
                                                 1.3 * self.shape_data[0])
        self.ren.GetActiveCamera().Elevation(80)
        self.ren.GetActiveCamera().Roll(180)
        self.ren.GetActiveCamera().Zoom(0.7)

        self.renderer.AddActor(self.actor)
        for i in range(0, angleRot):

            WindowToImageFilter.Modified()
            WindowToImageFilter.Update()

            TIFFWriter.SetFileName(path + '%4.4d' % i + '.tiff')
            TIFFWriter.Write()
            self.ren.GetActiveCamera().Azimuth(1)
        self.ren.RemoveVolume(self.volume)
        self.ren.RemoveActor(self.actor)
Example #13
0
    def write_picture(self, magnify, fname):
        ren = self.getRenderer()
        assert ren is not None
        renderLarge = vtk.vtkRenderLargeImage()
        renderLarge.SetInput(ren)
        renderLarge.SetMagnification(magnify)

        rotation = 'x'
        self.set_rotation(rotation)

        lfname = fname.lower()
        if lfname.endswith('.png'):
            writer = vtk.vtkPNGWriter()
        elif lfname.endswith('.jpeg'):
            writer = vtk.vtkJPEGWriter()
        elif lfname.endswith('.tiff'):
            writer = vtk.vtkTIFFWriter()
        elif lfname.endswith('.ps'):
            writer = vtk.vtkPostScriptWriter()
        else:
            writer = vtk.vtkPNGWriter()

        writer.SetInput(renderLarge.GetOutput())
        writer.SetFileName(fname)
        writer.Write()
Example #14
0
def CaptureImage():
    w2i = vtk.vtkWindowToImageFilter()
    writer = vtk.vtkTIFFWriter()
    w2i.SetInput(renWin)
    w2i.Update()
    writer.SetInputConnection(w2i.GetOutputPort())
    writer.SetFileName("image.tif")
    renWin.Render()
    writer.Write()
def CaptureImage():
    w2i = vtk.vtkWindowToImageFilter()
    writer = vtk.vtkTIFFWriter()
    w2i.SetInput(renWin)
    w2i.Update()
    writer.SetInputConnection(w2i.GetOutputPort())
    writer.SetFileName("image.tif")
    renWin.Render()
    writer.Write()
Example #16
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkTIFFWriter(),
                                       'Writing vtkTIFF.', ('vtkTIFF', ),
                                       (),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Example #17
0
 def CaptureImage():
     w2i = vtk.vtkWindowToImageFilter()
     writer = vtk.vtkTIFFWriter()
     w2i.SetInput(renWin)
     w2i.Update()
     writer.SetInput(w2i.GetOutput())
     writer.SetFileName("/home/danc/image.tif")
     renWin.Render()
     writer.Write()
Example #18
0
    def test_get_tif(self):
        '''tif file returns correct reader'''
        extension='.tif'
        expected = type(vtk.vtkTIFFReader())
        writer = vtk.vtkTIFFWriter()

        filename = os.path.join(self.test_dir, 'file'+extension)
        self.generate_image(filename, writer)
        self.assertEqual(type(get_vtk_reader(filename)), expected)
Example #19
0
def saveTiffImage(name, image, coding='uchar'):
    """
    save a Raw Image (.img,.raw) from a vtkImageData
    """
    imgCast = castImage(image, coding)
    writer = vtk.vtkTIFFWriter()
    writer.SetFileName(name)
    writer.SetInput(imgCast)
    writer.SetFileDimensionality(3)
    writer.Write()
Example #20
0
 def SaveCapture():
     fname = tkFileDialog.asksaveasfilename(defaultextension=".tif",
                                            filetypes=[ ('TIF Files','*.tif') ] )
     if fname:
         w2i = vtk.vtkWindowToImageFilter()
         writer = vtk.vtkTIFFWriter()
         w2i.SetInput(Globals.renWin)
         writer.SetInputConnection( w2i.GetOutputPort() )
         writer.SetFileName(fname)
         Globals.renWin.Render()
         writer.Write()
Example #21
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.')
Example #22
0
 def saveimageCB(self, *args):
     w2i = vtk.vtkWindowToImageFilter()
     writer = vtk.vtkTIFFWriter()
     renWin = self.canvas.GetRenderWindow()
     w2i.SetInput(renWin)
     print renWin
     renWin.Render()
     w2i.Update()
     print w2i.GetOutput()
     writer.SetInputConnection(w2i.GetOutputPort())
     writer.SetFileName("image.tif")
     writer.Write()
Example #23
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')
Example #24
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')
Example #25
0
 def SaveCapture():
     fname = tkFileDialog.asksaveasfilename(defaultextension=".tif",
                                            filetypes=[('TIF Files',
                                                        '*.tif')])
     if fname:
         w2i = vtk.vtkWindowToImageFilter()
         writer = vtk.vtkTIFFWriter()
         w2i.SetInput(Globals.renWin)
         writer.SetInputConnection(w2i.GetOutputPort())
         writer.SetFileName(fname)
         Globals.renWin.Render()
         writer.Write()
Example #26
0
def write(obj, fileoutput):
    '''
    Write 3D object to file.

    Possile extensions are: .vtk, .ply, .obj, .stl, .byu, .vtp, .xyz, .tif
    '''
    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 = vu.polydata(obj, True)
        w = vtk.vtkOBJExporter()
        w.SetFilePrefix(fileoutput.replace('.obj', ''))
        vc.printc('Please use write(vp.renderWin)', c=3)
        w.SetInput(obj)
        w.Update()
        vc.printc("Saved file: " + fileoutput, c='g')
        return
    elif '.tif' in fr:
        wr = vtk.vtkTIFFWriter()
        wr.SetFileDimensionality(len(obj.GetDimensions()))
        vu.setInput(wr, obj)
        wr.SetFileName(fileoutput)
        wr.Write()
        vc.printc("TIFF stack saved as: " + fileoutput, c='g')
        return
    else:
        vc.printc('Unavailable format in file ' + fileoutput, c='r')
        exit(1)

    try:
        obj = vu.polydata(obj, True)
        vu.setInput(w, vu.polydata(obj, True))
        w.SetFileName(fileoutput)
        w.Write()
        vc.printc("Saved file: " + fileoutput, c='g')
    except:
        vc.printc("Error saving: " + fileoutput, c='r')
Example #27
0
    def take_screen_shot(self, file_name):

        WindowToImageFilter = vtk.vtkWindowToImageFilter()

        WindowToImageFilter.SetInput(self.renWin)
        TIFFWriter = vtk.vtkTIFFWriter()
        TIFFWriter.SetInputConnection(WindowToImageFilter.GetOutputPort())
        self.renWin.SetSize(1600, 1200)
        self.ren.Modified()
        self.renWin.Modified()
        self.renWin.Render()
        TIFFWriter.SetFileName(file_name)
        WindowToImageFilter.Modified()
        WindowToImageFilter.Update()

        TIFFWriter.Write()
Example #28
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
Example #29
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()
Example #30
0
File: gfx.py Project: ggoret/VEDA
	def snapshot(self):
		fn = FD.asksaveasfilename(title="Save snapshot",filetypes=[("JPEG format", "*.jpg "),("TIFF format", "*.tif "),("PNG  format", "*.png ")])
		if fn == '':
			return
		w2i = vtk.vtkWindowToImageFilter()
		w2i.SetInput(self.renwin)
		w2i.Update()
		if fn.endswith('tif') or fn.endswith('TIF') :
			writer = vtk.vtkTIFFWriter()
		elif fn.endswith('jpg') or fn.endswith('JPG') or fn.endswith('jpeg') or fn.endswith('JPEG'):
			writer = vtk.vtkJPEGWriter()
		elif fn.endswith('png') or fn.endswith('PNG'):
			writer = vtk.vtkPNGWriter()
		else:
			fn += '.jpg'
			writer = vtk.vtkJPEGWriter()
		writer.SetFileName(fn)
		writer.SetInputConnection(w2i.GetOutputPort())
		self.renwin.Render()
		writer.Write()
Example #31
0
 def save_tiff (self, file_name=""): 
     debug ("In RenderWindow::save_tiff ()")
     if not file_name:
         file_name = tk_fsave (title="Export to TIFF image",
                               initialdir=Common.config.initial_dir,
                               defaultextension=".tif",
                               filetypes=[("TIFF images", "*.tiff"), 
                                          ("TIFF images", "*.tif"),
                                          ("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.vtkTIFFWriter ()
         ex.SetFileName (file_name)
         ex.SetInput (w2if.GetOutput ())
         ex.Write () 
         Common.state.idle ()
Example #32
0
    def test_write_tiff_unsigned_long(self):
        '''Can write tiff file with type unsigned long'''
        extension = '.tiff'
        filename = os.path.join(self.test_dir, 'file' + extension)
        scalar_type = vtk.VTK_UNSIGNED_LONG

        source = self.generate_image(scalar_type)
        writer = vtk.vtkTIFFWriter()
        writer.SetInputConnection(source.GetOutputPort())
        writer.SetFileName(filename)

        handle_filetype_writing_special_cases(writer)

        writer.Update()
        self.assertTrue(os.path.isfile(filename))

        reader = vtk.vtkTIFFReader()
        reader.SetFileName(filename)
        reader.Update()

        self.assertEqual(reader.GetOutput().GetScalarType(), vtk.VTK_FLOAT)
Example #33
0
    def onTakePicture(self, event):
        renderLarge = vtk.vtkRenderLargeImage()
        renderLarge.SetInput(self.getRenderer())
        renderLarge.SetMagnification(4)

        wildcard = "PNG (*.png)|*.png|" \
            "JPEG (*.jpeg; *.jpeg; *.jpg; *.jfif)|*.jpg;*.jpeg;*.jpg;*.jfif|" \
            "TIFF (*.tif; *.tiff)|*.tif;*.tiff|" \
            "BMP (*.bmp)|*.bmp|" \
            "PostScript (*.ps)|*.ps|" \
            "All files (*.*)|*.*"

        dlg = wx.FileDialog(None, "Choose a file", self.dirname, "", wildcard,
                            wx.SAVE | wx.OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            fname = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            fname = os.path.join(self.dirname, fname)

            print "fname = ", fname

            # We write out the image which causes the rendering to occur. If you
            # watch your screen you might see the pieces being rendered right
            # after one another.
            lfname = fname.lower()
            if lfname.endswith('.png'):
                writer = vtk.vtkPNGWriter()
            elif lfname.endswith('.jpeg'):
                writer = vtk.vtkJPEGWriter()
            elif lfname.endswith('.tiff'):
                writer = vtk.vtkTIFFWriter()
            elif lfname.endswith('.ps'):
                writer = vtk.vtkPostScriptWriter()
            else:
                writer = vtk.vtkPNGWriter()

            writer.SetInputConnection(renderLarge.GetOutputPort())
            writer.SetFileName(fname)
            writer.Write()
        dlg.Destroy()
Example #34
0
    def onTakePicture(self, event):
        renderLarge = vtk.vtkRenderLargeImage()
        renderLarge.SetInput(self.getRenderer())
        renderLarge.SetMagnification(4)

        wildcard = "PNG (*.png)|*.png|" \
            "JPEG (*.jpeg; *.jpeg; *.jpg; *.jfif)|*.jpg;*.jpeg;*.jpg;*.jfif|" \
            "TIFF (*.tif; *.tiff)|*.tif;*.tiff|" \
            "BMP (*.bmp)|*.bmp|" \
            "PostScript (*.ps)|*.ps|" \
            "All files (*.*)|*.*"

        dlg = wx.FileDialog(None, "Choose a file", self.dirname,
                            "", wildcard, wx.SAVE | wx.OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            fname = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            fname = os.path.join(self.dirname, fname)

            print "fname = ", fname

            # We write out the image which causes the rendering to occur. If you
            # watch your screen you might see the pieces being rendered right
            # after one another.
            lfname = fname.lower()
            if lfname.endswith('.png'):
                writer = vtk.vtkPNGWriter()
            elif lfname.endswith('.jpeg'):
                writer = vtk.vtkJPEGWriter()
            elif lfname.endswith('.tiff'):
                writer = vtk.vtkTIFFWriter()
            elif lfname.endswith('.ps'):
                writer = vtk.vtkPostScriptWriter()
            else:
                writer = vtk.vtkPNGWriter()

            writer.SetInputConnection(renderLarge.GetOutputPort())
            writer.SetFileName(fname)
            writer.Write()
        dlg.Destroy()
Example #35
0
 def PrintCallback(self, irenStyle, event):
     iren = irenStyle.GetInteractor()
     if 't' is iren.GetKeySym():
         renWin = iren.GetRenderWindow()
         windowToImage = vtk.vtkWindowToImageFilter()
         windowToImage.SetInput(renWin)
         windowToImage.SetMagnification(self.imageMagnification)
         if self.bJPEGFile:
             filename = "planes.jpg"
             writer = vtk.vtkJPEGWriter()
         else:
             writer = vtk.vtkTIFFWriter()
             filename = "planes.tif"
         writer.SetFileName(filename)
         writer.SetInput(windowToImage.GetOutput())
         #writer.SetCompressionToLZW()ple
         aaFrames = renWin.GetAAFrames()
         renWin.SetAAFrames(self.imageAAFrames)
         writer.Write()
         renWin.SetAAFrames(aaFrames)
         print "wrote", filename
         renWin.Render()
Example #36
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')
Example #37
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"))
Example #38
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')
Example #39
0
    def saveButtonClicked(self):
        self.saveFile = str(QtGui.QFileDialog.getSaveFileName())
        print(self.saveFile)

        if os.path.exists(self.inputFileName):
            reply = QtGui.QMessageBox.question(self, 'Message',
            "File exists. Overwrite?", QtGui.QMessageBox.Yes |
            QtGui.QMessageBox.No, QtGui.QMessageBox.No)

            if reply == QtGui.QMessageBox.No:
                self.saveFile = None
                return

        # Do it, write it out!
        windowToImage = vtk.vtkWindowToImageFilter()
        windowToImage.SetInput(self.vtkWidget.GetRenderWindow())
        windowToImage.Update()

        writer = vtk.vtkTIFFWriter()
        writer.SetCompressionToNoCompression()
        writer.SetFileName(self.saveFile)
        writer.SetInputConnection(windowToImage.GetOutputPort())
        writer.Write()
Example #40
0
 def snapshot(self):
     fn = FD.asksaveasfilename(title="Save snapshot",
                               filetypes=[("JPEG format", "*.jpg "),
                                          ("TIFF format", "*.tif "),
                                          ("PNG  format", "*.png ")])
     if fn == '':
         return
     w2i = vtk.vtkWindowToImageFilter()
     w2i.SetInput(self.renwin)
     w2i.Update()
     if fn.endswith('tif') or fn.endswith('TIF'):
         writer = vtk.vtkTIFFWriter()
     elif fn.endswith('jpg') or fn.endswith('JPG') or fn.endswith(
             'jpeg') or fn.endswith('JPEG'):
         writer = vtk.vtkJPEGWriter()
     elif fn.endswith('png') or fn.endswith('PNG'):
         writer = vtk.vtkPNGWriter()
     else:
         fn += '.jpg'
         writer = vtk.vtkJPEGWriter()
     writer.SetFileName(fn)
     writer.SetInputConnection(w2i.GetOutputPort())
     self.renwin.Render()
     writer.Write()
Example #41
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
Example #42
0
    def View(self,filename):

        '''
        Nastavení interaktoru pro pohyb s objektem. Třída vtkInteractorStyleTrackballCamera(), nám umožní nastavit na levé tlačítko
        myši funkce pohybu s vizualizovaným objektem a na pravé možnost zoomu
        '''
        self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())

        '''
        Nastavení readeru pro čtení vtk souboru v podobě nestrukturované mřížky
        '''
        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(filename)
        reader.Update()

        '''
        Jako filtr je použit objekt třídy vtkDataSetSurfaceFilter(), který nám z dat vyextrahuje vnější povrch
        '''
        surface.SetInput(reader.GetOutput())
        surface.Update()

        '''
        Dále použijeme třídu vtkClipPolyData(), ta nám při pohybu roviny způsobí, že za ní bude nechávat pouze obrysy spojení
        buněk bez vyplnění povrchu, tím snadno poznáme kde jsme s rovinou po objektu již přejeli a kde ne
        '''
        clipper = vtk.vtkClipPolyData()
        clipper.SetInput(surface.GetOutput())
        clipper.SetClipFunction(plane)
        clipper.GenerateClippedOutputOn()

        clipMapper = vtk.vtkPolyDataMapper()
        clipMapper.SetInput(clipper.GetOutput())

        clipActor = vtk.vtkActor()
        clipActor.SetMapper(clipMapper)

        mapper = vtk.vtkDataSetMapper()
        mapper.SetInput(surface.GetOutput())



        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().EdgeVisibilityOn()
        # nastavuje šířku linek ohraničující buňky
        actor.GetProperty().SetLineWidth(0.1)
        actor.GetProperty().SetRepresentationToWireframe()
        self.ren.AddActor(clipActor)
        self.ren.AddActor(actor)

        self.iren.Initialize()
        self.iren.Start()
        '''
        Třídu vtkWindowToImageFilter použijeme pro uložení vizualizace z prohlížecího režimu ve formátu tif
        '''
        try:
            w2i = vtk.vtkWindowToImageFilter()
            writer = vtk.vtkTIFFWriter()
            w2i.SetInput(self.renWin)
            w2i.Update()
            writer.SetInputConnection(w2i.GetOutputPort())
            writer.SetFileName("image.tif")
            self.renWin.Render()
            writer.Write()
            self.renWin.Render()
            self.renWin.Finalize()
        except(AttributeError):
            print()
Example #43
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
Example #44
0
    def showVtkPolyData(self, pdata, windowSizeX=600,
                        windowSizeY=400, filename=''):
        """
        Show the boundary surface or write image to file
        @param pdata vtkPolyData instance
        @param windowSizeX number of pixels in x
        @param windowSizeY number of pixels in y
        @param filename write to a file if this keyword
        is present and a non-empty string
        """
        # Create a rendering window and renderer.
        try:
            ren = vtk.vtkRenderer()
            renWin = vtk.vtkRenderWindow()
            iren = vtk.vtkRenderWindowInteractor()
            camera = vtk.vtkCamera()
            mapper = vtk.vtkPolyDataMapper()
            actor = vtk.vtkActor()
            axes = [vtk.vtkArrowSource(),
                    vtk.vtkArrowSource(),
                    vtk.vtkArrowSource()]
            axesTransf = [vtk.vtkTransform(),
                          vtk.vtkTransform(),
                          vtk.vtkTransform()]
            axesTPD = [vtk.vtkTransformPolyDataFilter(),
                       vtk.vtkTransformPolyDataFilter(),
                       vtk.vtkTransformPolyDataFilter()]
            axesMappers = [vtk.vtkPolyDataMapper(),
                           vtk.vtkPolyDataMapper(),
                           vtk.vtkPolyDataMapper()]
            axesActors = [vtk.vtkActor(), vtk.vtkActor(), vtk.vtkActor()]

            renderLarge = vtk.vtkRenderLargeImage()
        except:
            print('WARNING: Cannot call show method -- likely missing VTK')
            return
        renWin.AddRenderer(ren)
        renWin.SetSize(windowSizeX, windowSizeY)
        # Create a renderwindowinteractor.
        iren.SetRenderWindow(renWin)
        # Camera
        xmin, xmax, ymin, ymax, zmin, zmax = pdata.GetBounds()
        lo = numpy.array([xmin, ymin, zmin])
        hi = numpy.array([xmax, ymax, zmax])
        camera.SetFocalPoint(hi)
        center = 0.5*(lo + hi)
        camera.SetPosition(center + hi - lo)
        camera.Zoom(1.0)
        ren.SetActiveCamera(camera)
        # Mapper.
        if vtk.VTK_MAJOR_VERSION >= 6:
            mapper.SetInputData(pdata)
        else:
            mapper.SetInput(pdata)
        # Actor.
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(1, 1, 1)
        # Add axes.
        axesColrs = [(1., 0., 0.,), (0., 1., 0.,), (0., 0., 1.,)]
        for a in axes:
            a.SetShaftRadius(0.01)
            a.SetTipLength(0.2)
            a.SetTipRadius(0.03)
        for at in axesTransf:
            at.PostMultiply()
        # Rotate the y and z arrows (initially along x).
        axesTransf[1].RotateZ(90.0)
        axesTransf[2].RotateY(-90.0)
        # Scale.
        for i in range(3):
            factor = hi[i] - lo[i]
            scale = [1., 1., 1.]
            scale[i] = factor
            axesTransf[i].Scale(scale)
        # Translate to loBounds.
        for at in axesTransf:
            at.Translate(lo)
        for i in range(3):
            axesTPD[i].SetInputConnection(axes[i].GetOutputPort())
            axesTPD[i].SetTransform(axesTransf[i])
            axesMappers[i].SetInputConnection(axesTPD[i].GetOutputPort())
            axesActors[i].SetMapper(axesMappers[i])
            axesActors[i].GetProperty().SetColor(axesColrs[i])
            ren.AddActor(axesActors[i])
        # Assign actor to the renderer.
        ren.AddActor(actor)
        # Write to file.
        writer = None
        if filename:
            if filename.lower().find('.png') > 0:
                writer = vtk.vtkPNGWriter()
            elif filename.lower().find('.jp') > 0:
                writer = vtk.vtkJPEGWriter()
            elif filename.lower().find('.tiff') > 0:
                writer = vtk.vtkTIFFWriter()
            if writer:
                renderLarge.SetInput(ren)
                renderLarge.SetMagnification(1)
                renderLarge.Update()
                writer.SetFileName(filename)
                writer.SetInputConnection(renderLarge.GetOutputPort())
                writer.Write()
        else:
            # Fire up interactor.
            iren.Initialize()
            renWin.Render()
            iren.Start()
Example #45
0
    def saveImage(self, renderType, imageFormat, fileprefix, overwrite, povray="povray"):
        """
        Save image to file.
        
        """
        logger = self.logger
        
        if renderType == "VTK":
            filename = "%s.%s" % (fileprefix, imageFormat)
            
            renWin = self.renWin
            
            w2if = vtk.vtkWindowToImageFilter()
            w2if.SetInput(renWin)
            
            if imageFormat == "jpg":
                writer = vtk.vtkJPEGWriter()
            
            elif imageFormat == "png":
                writer = vtk.vtkPNGWriter()
                
            elif imageFormat == "tif":
                writer = vtk.vtkTIFFWriter()
            
            writer.SetInputConnection(w2if.GetOutputPort())
            
            if not overwrite:
                count = 0
                while os.path.exists(filename):
                    count += 1
                    filename = "%s(%d).%s" % (fileprefix, count, imageFormat)
            
            writer.SetFileName(filename)
            writer.Write()
        
        elif renderType == "POV":
            self.logger.debug("Rendering using POV-Ray")

            # which renderer and pipeline
            renIndex = self.parent.rendererIndex
            pipelineIndex = self.parent.currentPipelineIndex
            
            self.logger.debug("Renderer %d; Pipeline %d", renIndex, pipelineIndex)
            
            # header file
            povfile = os.path.join(self.mainWindow.tmpDirectory, "renderer%d.pov" % renIndex)
            self.logger.debug("Povray file: '%s'", povfile)
            with open(povfile, "w") as fh:
                # first write the header (camera info etc.)
                self.writePOVRAYHeader(fh)
                
                # write cell frame if visible
                if self.latticeFrame.visible:
                    self.writePOVRAYCellFrame(fh)
                
                # TODO: write axes if visible
            
            # write povray files for active renderers
            self.logger.debug("Writing renderer povray data")
            filterLists = self.parent.getFilterLists()
            for flist in filterLists:
                if flist.visible:
                    for rend in flist.renderer.renderers():
                        rend.writePovray(povfile)
            
            # POV-Ray settings
            settings = self.mainWindow.preferences.povrayForm
            overlay = settings.overlayImage
            
            # then join filter list files
            _cwd = os.getcwd()
            os.chdir(self.mainWindow.tmpDirectory)
            try:
                # create povray ini file
                povIniFile = "renderer%d_image.ini" % renIndex
                tmpPovOutputFile = "renderer%d_image.%s" % (renIndex, imageFormat)
                with open(povIniFile, "w") as fh:
                    fh.write("; Atoman auto-generated POV-Ray INI file\n")
                    fh.write("Input_File_Name='%s'\n" % os.path.basename(povfile))
                    fh.write("Width=%d\n" % settings.HRes)
                    fh.write("Height=%d\n" % settings.VRes)
                    fh.write("Display=off\n")
                    fh.write("Antialias=on\n")
                    fh.write("Output_File_Name='%s'\n" % tmpPovOutputFile)
                
                # run povray
                command = "%s '%s'" % (povray, povIniFile)
                resultQ = Queue.Queue()
                
                # run in thread
                thread = threading.Thread(target=utilities.runSubprocessInThread, args=(command, resultQ))
                thread.start()
                while thread.isAlive():
                    thread.join(1)
                    QtGui.QApplication.processEvents()
                
                # result
                try:
                    output, stderr, status = resultQ.get(timeout=1)
                except Queue.Empty:
                    logger.error("Could not get result from POV-Ray thread!")
                    return None
                    
                if status:
                    logging.error("POV-Ray failed: out: %s", output)
                    logging.error("POV-Ray failed: err: %s", stderr)
                    return None
                
            finally:
                os.chdir(_cwd)
            
            # output filename
            filename = "%s.%s" % (fileprefix, imageFormat)
            if not overwrite:
                count = 0
                while os.path.exists(filename):
                    count += 1
                    filename = "%s(%d).%s" % (fileprefix, count, imageFormat)
            
            # rename tmp image file to where it should be
            try:
                shutil.move(os.path.join(self.mainWindow.tmpDirectory, tmpPovOutputFile), filename)
            except:
                print "ERROR COPYING POV FILE", sys.exc_info()
                        
            # remove image files
            # os.unlink(povfile)
            # os.unlink(os.path.join(self.mainWindow.tmpDirectory, povIniFile))
        
        if not os.path.exists(filename):
            self.logger.error("Something went wrong with save image")
            return None
        
        elif renderType == "POV" and overlay:
            self.overlayImage(filename)
        
        return filename
Example #46
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
Example #47
0
sp.SetNumberOfScalarComponents(image1.GetOutput().GetNumberOfScalarComponents(),image1.GetOutputInformation(0))
sp.GetPointData().SetScalars(image1.GetOutput().GetPointData().GetScalars())
luminance = vtk.vtkImageLuminance()
luminance.SetInputData(sp)
#
# write to the temp directory if possible, otherwise use .
#
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()
Example #48
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