def plot(self, fileName): '''Plots window contents :param fileName: name of the image file, in none -> screen window. ''' self.renWin.SetOffScreenRendering(True) # Don't use screen. self.renWin.Render() w2if = vtk.vtkWindowToImageFilter() oldSB = self.renWin.GetSwapBuffers() # Tell render window to not swap buffers at end of render. self.renWin.SwapBuffersOff() # Let's grab from back buffer as that overcomes # issues with overlapping windows or other UI # components obfuscating the captured image on # certain windowing systems/platforms. w2if.ReadFrontBufferOff() #Read from the back buffer. w2if.SetInput(self.renWin) if (hasattr(w2if, 'SetScale')): w2if.SetScale(1) # image quality else: w2if.SetMagnification( 1 ) # image quality (apparently deprecated in recent versions of VTL -LCPT 20/05/2020-) w2if.Update() # restore swapping state self.renWin.SetSwapBuffers(oldSB) writer = vtk.vtkJPEGWriter() writer.SetInputConnection(w2if.GetOutputPort()) writer.SetFileName(fileName) writer.Write()
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()
def InitRenderWindow(self, stereo_on=False, axes_on=False, bkgnd=[0.8, 0.8, 0.8], res_x=600, res_y=600): """Sets up the visualisation environment""" self.renderer = vtk.vtkOpenGLRenderer() self.renderWindow = vtk.vtkRenderWindow() self.renderWindow.SetStereoCapableWindow(stereo_on) self.renderWindow.SetStereoRender(stereo_on) self.renderWindow.SetStereoTypeToSplitViewportHorizontal() self.renderWindow.AddRenderer(self.renderer) self.renderWindow.SetMultiSamples(0) self.renderWindow.SetAlphaBitPlanes(1) self.renderer.SetBackground(bkgnd) self.renderWindow.SetSize(res_x, res_y) self.renderer.ResetCamera() self.renderer.GetActiveCamera().Zoom(1) self.InitRenderPasses() axes = vtk.vtkAxesActor() axes.SetConeRadius(0.15) axes.AxisLabelsOn() if axes_on: self.renderer.AddActor(axes) self.camera = self.renderer.GetActiveCamera() self.windowFilter = vtk.vtkWindowToImageFilter() self.windowFilter.SetInput(self.renderWindow) self.windowFilter.ReadFrontBufferOff() self.writer = vtk.vtkJPEGWriter() self.writer.SetInputConnection(self.windowFilter.GetOutputPort())
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()
def screenshot(filename="screenshot.png"): """ Save a screenshot of the current rendering window. """ if not settings.plotter_instance or not settings.plotter_instance.window: colors.printc( '~bomb screenshot(): Rendering window is not present, skip.', c=1) return w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(settings.plotter_instance.window) s = settings.screeshotScale w2if.SetScale(s, s) if settings.screenshotTransparentBackground: w2if.SetInputBufferTypeToRGBA() w2if.ReadFrontBufferOff() # read from the back buffer w2if.Update() if filename.endswith('.png'): writer = vtk.vtkPNGWriter() writer.SetFileName(filename) writer.SetInputConnection(w2if.GetOutputPort()) writer.Write() elif filename.endswith('.jpg'): writer = vtk.vtkJPEGWriter() writer.SetFileName(filename) writer.SetInputConnection(w2if.GetOutputPort()) writer.Write() elif filename.endswith('.svg'): writer = vtk.vtkGL2PSExporter() #writer.SetFileFormatToPDF() #writer.SetFileFormatToTeX() writer.SetFileFormatToSVG() writer.CompressOff() writer.SetInput(settings.plotter_instance.window) writer.SetFilePrefix(filename.split('.')[0]) writer.Write()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkJPEGWriter(), 'Writing vtkJPEG.', ('vtkJPEG',), (), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def renWriteJPEG(ren,args): #@c Save the current window image to a file #@c in jpeg format. If no filename is specified, #@c then an interactive window is popped up asking #@c for a name to be given. #@a ren: renderer #@a args: filename if (args ==""): filename = raw_input("Please enter image name to save") else: filename = args if (filename ==""): return jwriter = vtk.vtkJPEGWriter() jwriter.ProgressiveOff() jwriter.SetQuality(95) ren.GetRenderWindow().Render() w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(ren.GetRenderWindow()) w2i.Update() jwriter.SetInput(w2i.GetOutput()) jwriter.SetFileName(filename) jwriter.Write() del w2i del jwriter return
def save_jpeg(self, filename): """ Save the rendered screen as jpeg """ writer = vtk.vtkJPEGWriter() writer.SetQuality(100) self.saveScreen(writer, filename)
def writeAllImageSlices(imgfn,pathfn,ext,output_dir): reader = vtk.vtkMetaImageReader() reader.SetFileName(imgfn) reader.Update() img = reader.GetOutput() parsed_path = parsePathFile(pathfn) slices = getAllImageSlices(img,parsed_path,ext) writer = vtk.vtkJPEGWriter() table = vtk.vtkLookupTable() scalar_range = img.GetScalarRange() table.SetRange(scalar_range[0], scalar_range[1]) # image intensity range table.SetValueRange(0.0, 1.0) # from black to white table.SetSaturationRange(0.0, 0.0) # no color saturation table.SetRampToLinear() table.Build() # Map the image through the lookup table color = vtk.vtkImageMapToColors() color.SetLookupTable(table) mkdir(output_dir) for i in range(len(slices)): color.SetInputData(slices[i]) writer.SetInputConnection(color.GetOutputPort()) writer.SetFileName(output_dir+'{}.jpg'.format(i)) writer.Update() writer.Write()
def write_image(self, filename="image.png", magnification=1, image_format="png"): """ Save render window to an image. Arguments: filename: filename to save to. Defaults to image.png. magnification: magnification. Use it to render high res images. image_format: choose between jpeg, png. Png is the default. """ render_large = vtk.vtkRenderLargeImage() render_large.SetInput(self.ren) if image_format == "jpeg": writer = vtk.vtkJPEGWriter() writer.SetQuality(80) else: writer = vtk.vtkPNGWriter() render_large.SetMagnification(magnification) writer.SetFileName(filename) writer.SetInputConnection(render_large.GetOutputPort()) self.ren_win.Render() writer.Write() del render_large
def renWriteJPEG(ren, args): #@c Save the current window image to a file #@c in jpeg format. If no filename is specified, #@c then an interactive window is popped up asking #@c for a name to be given. #@a ren: renderer #@a args: filename if (args == ""): filename = raw_input("Please enter image name to save") else: filename = args if (filename == ""): return jwriter = vtk.vtkJPEGWriter() jwriter.ProgressiveOff() jwriter.SetQuality(95) ren.GetRenderWindow().Render() w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(ren.GetRenderWindow()) w2i.Update() jwriter.SetInput(w2i.GetOutput()) jwriter.SetFileName(filename) jwriter.Write() del w2i del jwriter return
def OnExport(self, event): """Export to graphics filetype with extension ext.""" renWin = self.widget.GetRenderWindow() wif = vtk.vtkWindowToImageFilter() wif.SetInput(renWin) wildcard = "PNG (*.png)|*.png|" \ "Postscript (*.ps)|*.ps|" \ "JPEG (*.jpg)|*.jpg" # "TIFF (*.tif)|*.tif" dialog = wx.FileDialog(None, "Export Graphics", os.getcwd(), "", wildcard, wx.SAVE|wx.OVERWRITE_PROMPT) if dialog.ShowModal() == wx.ID_OK: path = dialog.GetPath() base, ext = os.path.splitext(path) if ext in ['.png', '.ps', '.jpg']: pass else: i = dialog.GetFilterIndex() ext = ['.png', '.ps', '.jpg'][i] # cases if ext == '.png': psw = vtk.vtkPNGWriter() elif ext == '.ps': psw = vtk.vtkPostScriptWriter() elif ext == '.jpg': psw = vtk.vtkJPEGWriter() psw.SetFileName(base + ext) psw.SetInput(wif.GetOutput()) psw.Write()
def writeJPEG(self, fn): filter = vtk.vtkWindowToImageFilter() filter.SetInput(self.ren_win) writer = vtk.vtkJPEGWriter() writer.SetInput(filter.GetOutput()) writer.SetFileName(fn) writer.Write()
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 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
def capture_image(self,obj,eve): self.renWin.Render() self.w2i = vtk.vtkWindowToImageFilter() self.w2i.SetInput(self.renWin) self.writer = vtk.vtkJPEGWriter() self.writer.SetInputConnection(self.w2i.GetOutputPort()) self.writer.SetFileName(`self.print_counter` + "screen_shot.jpg"); self.print_counter =1 + self.print_counter self.writer.Write()
def capture_image(self,obj,eve): self.renWin.Render() self.w2i = vtk.vtkWindowToImageFilter() self.w2i.SetInput(self.renWin) self.writer = vtk.vtkJPEGWriter() self.writer.SetInputConnection(self.w2i.GetOutputPort()) self.writer.SetFileName(`self.print_counter` + "vectorscreen.jpg"); self.print_counter =1 + self.print_counter self.writer.Write()
def screenshot(filename="screenshot.png", scale=None, returnNumpy=False): """ Save a screenshot of the current rendering window. :param int scale: set image magnification :param bool returnNumpy: return a numpy array of the image """ if not settings.plotter_instance or not settings.plotter_instance.window: colors.printc('~bomb screenshot(): Rendering window is not present, skip.', c=1) return if scale is None: scale = settings.screeshotScale if settings.screeshotLargeImage: w2if = vtk.vtkRenderLargeImage() w2if.SetInput(settings.plotter_instance.renderer) w2if.SetMagnification(scale) else: w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(settings.plotter_instance.window) if hasattr(w2if, 'SetScale'): w2if.SetScale(scale, scale) if settings.screenshotTransparentBackground: w2if.SetInputBufferTypeToRGBA() w2if.ReadFrontBufferOff() # read from the back buffer w2if.Update() if returnNumpy: w2ifout = w2if.GetOutput() npdata = vtk_to_numpy(w2ifout.GetPointData().GetArray("ImageScalars")) npdata = npdata[:,[0,1,2]] ydim, xdim, _ = w2ifout.GetDimensions() npdata = npdata.reshape([xdim, ydim, -1]) npdata = np.flip(npdata, axis=0) return npdata if filename.endswith('.png'): writer = vtk.vtkPNGWriter() writer.SetFileName(filename) writer.SetInputConnection(w2if.GetOutputPort()) writer.Write() elif filename.endswith('.jpg'): writer = vtk.vtkJPEGWriter() writer.SetFileName(filename) writer.SetInputConnection(w2if.GetOutputPort()) writer.Write() elif filename.endswith('.svg'): writer = vtk.vtkGL2PSExporter() #writer.SetFileFormatToPDF() #writer.SetFileFormatToTeX() writer.SetFileFormatToSVG() writer.CompressOff() writer.SetInput(settings.plotter_instance.window) writer.SetFilePrefix(filename.split('.')[0]) writer.Write()
def saveToImage(self,window,fileName): fileName = "{}.jpeg".format(fileName); w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(window) w2if.Update() writer = vtk.vtkJPEGWriter() writer.SetFileName(fileName); writer.SetInputConnection(w2if.GetOutputPort()) writer.Write() self.seq.append(fileName);
def plotToFile(fName, renWin, renderer, width, height,fileFormat): w2i = vtk.vtkWindowToImageFilter() writer = vtk.vtkJPEGWriter() w2i.SetInput(renWin) w2i.Update() writer.SetInputConnection(w2i.GetOutputPort()) writer.SetFileName(fName) renWin.Render() w2i.Update() writer.Write()
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.')
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()
def plot(self, fName): '''Plots window contents''' w2i = vtk.vtkWindowToImageFilter() writer = vtk.vtkJPEGWriter() w2i.SetInput(self.renWin) w2i.Update() writer.SetInputConnection(w2i.GetOutputPort()) writer.SetFileName(fName) self.renWin.Render() w2i.Update() writer.Write()
def plot(self,fName): '''Plots window contents''' w2i = vtk.vtkWindowToImageFilter() writer = vtk.vtkJPEGWriter() w2i.SetInput(self.renWin) w2i.Update() writer.SetInputConnection(w2i.GetOutputPort()) writer.SetFileName(fName) self.renWin.Render() w2i.Update() writer.Write()
def ExportAsJPG(reportName,renWin): vtkW2Image =vtk.vtkWindowToImageFilter() vtkW2Image.SetInputBufferTypeToRGB() vtkW2Image.SetInput(renWin) vtkW2Image.Update() vtkJPEGWriter=vtk.vtkJPEGWriter() vtkJPEGWriter.SetFileName(reportName) vtkJPEGWriter.SetInputData(vtkW2Image.GetOutput()) vtkJPEGWriter.Write()
def WriteAsJPEG(filename, renderingWindow): ##### Section for the JPEG Writer #################### win2img = vtk.vtkWindowToImageFilter() win2img.SetInput(renderingWindow) #win2img.SetMagnification(2) win2img.Update() jpegWriter = vtk.vtkJPEGWriter() jpegWriter.SetFileName(filename) jpegWriter.SetInputConnection(win2img.GetOutputPort()) jpegWriter.Write()
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')
def setImagewrite(filename): toImage =vtk.vtkWindowToImageFilter() toImage.SetInput(renWin) toImage.Modified() writer = vtk.vtkJPEGWriter() writer.SetQuality(100) writer.ProgressiveOn() writer.SetInput(toImage.GetOutput()) writer.SetFileName(filename) writer.Modified() print "writing to ",filename writer.Write()
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')
def ImageWriter(renderer, camera=None, outCompressionType="jpg", suppress=False, dimension=[400, 400], AAFrames=5): """ Write image from renderer to a figure. :param renderer: vtkRenderer :param dimension (Optional)Dimension of output, e.g. [x, y] :param camera: (Optional)vtkCameraObject :param outCompressionType: (Optional)Specify output format, support "png", "jpeg", default to "png" :param outFileName: (Optional)Filename of the output :param supress: (Optional)Suppress output file :return: Note: Depending on the version of vtk and graphics driver, the vtkRenderWindow.SetOffScreenRendering(1) may behave strangely, it is therefore advised to use the xvfbwrapper if you are hosting a headless server and comment the line that writes renderWin.SetOffScreenRendering(1) in this function. Alternatively, if you managed to compile VTK from souce with the option VTK_USE_OFFSCREEN on then you might simply use SetOffScreenRendering(1)/OffScreenRenderingOn() and suppress xvfbwrapper through the code by setting config.vdisplay=False """ renderWin = vtk.vtkRenderWindow() renderWin.AddRenderer(renderer) renderWin.OffScreenRenderingOn() renderWin.SetSize(int(dimension[0]), int(dimension[1])) renderWin.Render() # TODO: Error for nifti here renderWin.SetAAFrames(AAFrames) # ** Note that rendering does not work with the interactor. ** windowToImageFilter = vtk.vtkWindowToImageFilter() windowToImageFilter.SetInput(renderWin) windowToImageFilter.Update() if camera != None: renderer.SetActiveCamera(camera) # Writer the render to image if outCompressionType == "png": writer = vtk.vtkPNGWriter() if outCompressionType == "jpeg" or outCompressionType == "jpg": writer = vtk.vtkJPEGWriter() writer.SetWriteToMemory(1) writer.SetInputConnection(windowToImageFilter.GetOutputPort()) if suppress == False: writer.Write() result = writer.GetResult() return result
def onExportAsJpg(self): file_name = self.getFileName('Export to JPG', 'JPG files (*.jpg)', 'jpg') if file_name: windowToImageFilter = vtk.vtkWindowToImageFilter() windowToImageFilter.SetInput(self._vtk_render_window) windowToImageFilter.ReadFrontBufferOff() windowToImageFilter.Update() writer = vtk.vtkJPEGWriter() writer.SetFileName(file_name) writer.SetInputConnection(windowToImageFilter.GetOutputPort()) writer.Write()
def save_jpg(self, file_name="", quality=None, progressive=None): """Requires VTK 4 to work. Arguments: file_name if passed will be used, quality is the quality of the JPEG (10-100) are valid, the progressive arguments toggles progressive jpegs.""" debug ("In RenderWindow::save_jpg ()") try: ex = vtk.vtkJPEGWriter() except AttributeError: msg = "Saving to a JPEG file is not supported by your "\ "version of VTK. Versions 4.0 and above support this." Common.print_err (msg) return if not file_name: file_name = tk_fsave (title="Export to JPEG image", initialdir=Common.config.initial_dir, defaultextension=".jpg", filetypes=[("JPEG images", "*.jpg"), ("JPEG images", "*.jpeg"), ("All files", "*")]) if len (file_name) != 0: if not quality and not progressive: d = JPEGDialog (self.frame, [75, 1]) if d.result: quality, progressive = d.result else: return Common.state.busy () w2if = vtk.vtkWindowToImageFilter () w2if.SetMagnification (Common.config.magnification) self.lift () w2if.SetInput (self.renwin) ex = vtk.vtkJPEGWriter () ex.SetQuality (quality) ex.SetProgressive (progressive) ex.SetFileName (file_name) ex.SetInput (w2if.GetOutput ()) ex.Write () Common.state.idle ()
def plot(self, fName): '''Plots window contents''' self.renWin.Render() w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(self.renWin) w2if.SetScale(1) # image quality w2if.ReadFrontBufferOff() #Read from the front buffer. w2if.Update() writer = vtk.vtkJPEGWriter() writer.SetFileName(fName) writer.SetInputConnection(w2if.GetOutputPort()) writer.Write()
def saveGif(window, n): path = sys.argv[0] if os.path.isfile(path): path = os.path.dirname(path) path += '/Data/Gif/img%d.jpg' % n window_image_filter = vtk.vtkWindowToImageFilter() writer = vtk.vtkJPEGWriter() window_image_filter.SetInput(window) window_image_filter.Update() writer.SetInputConnection(window_image_filter.GetOutputPort()) writer.SetFileName(path) writer.Write()
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()
def plot(self,fileName): '''Plots window contents :param fileName: name of the image file, in none -> screen window. ''' self.renWin.Render() w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(self.renWin) w2if.SetScale(1) # image quality w2if.ReadFrontBufferOff(); #Read from the front buffer. w2if.Update() writer= vtk.vtkJPEGWriter() writer.SetFileName(fileName) writer.SetInputConnection(w2if.GetOutputPort()) writer.Write()
def save_image(self, filename="test.jpg"): img = vtk.vtkWindowToImageFilter() img.SetInput(self.render_window) img.SetMagnification(self.magnification) img.Update() #writer = vtk.vtkPNGWriter() writer = vtk.vtkJPEGWriter() if (vtk.vtkVersion().GetVTKMajorVersion() >= 6.0): writer.SetInputConnection(img.GetOutputPort()) else: writer.SetInput(img.GetOutput()) writer.SetFileName(filename) writer.Write() del writer del img
def _handleFailedImage(idiff, pngr, img_fname): """Writes all the necessary images when an image comparison failed.""" f_base, f_ext = os.path.splitext(img_fname) # write out the difference file in full. pngw = vtk.vtkPNGWriter() pngw.SetFileName(_getTempImagePath(f_base + ".diff.png")) pngw.SetInput(idiff.GetOutput()) pngw.Write() # write the difference image scaled and gamma adjusted for the # dashboard. sz = pngr.GetOutput().GetDimensions() if sz[1] <= 250.0: mag = 1.0 else: mag = 250.0 / sz[1] shrink = vtk.vtkImageResample() shrink.SetInput(idiff.GetOutput()) shrink.InterpolateOn() shrink.SetAxisMagnificationFactor(0, mag) shrink.SetAxisMagnificationFactor(1, mag) gamma = vtk.vtkImageShiftScale() gamma.SetInput(shrink.GetOutput()) gamma.SetShift(0) gamma.SetScale(10) jpegw = vtk.vtkJPEGWriter() jpegw.SetFileName(_getTempImagePath(f_base + ".diff.small.jpg")) jpegw.SetInput(gamma.GetOutput()) jpegw.SetQuality(85) jpegw.Write() # write out the image that was generated. shrink.SetInput(idiff.GetInput()) jpegw.SetInput(shrink.GetOutput()) jpegw.SetFileName(_getTempImagePath(f_base + ".test.small.jpg")) jpegw.Write() # write out the valid image that matched. shrink.SetInput(idiff.GetImage()) jpegw.SetInput(shrink.GetOutput()) jpegw.SetFileName(_getTempImagePath(f_base + ".small.jpg")) jpegw.Write()
def _handleFailedImage(idiff, pngr, img_fname): """Writes all the necessary images when an image comparison failed.""" f_base, f_ext = os.path.splitext(img_fname) # write out the difference file in full. pngw = vtk.vtkPNGWriter() pngw.SetFileName(_getTempImagePath(f_base + ".diff.png")) pngw.SetInput(idiff.GetOutput()) pngw.Write() # write the difference image scaled and gamma adjusted for the # dashboard. sz = pngr.GetOutput().GetDimensions() if sz[1] <= 250.0: mag = 1.0 else: mag = 250.0/sz[1] shrink = vtk.vtkImageResample() shrink.SetInput(idiff.GetOutput()) shrink.InterpolateOn() shrink.SetAxisMagnificationFactor(0, mag) shrink.SetAxisMagnificationFactor(1, mag) gamma = vtk.vtkImageShiftScale() gamma.SetInput(shrink.GetOutput()) gamma.SetShift(0) gamma.SetScale(10) jpegw = vtk.vtkJPEGWriter() jpegw.SetFileName(_getTempImagePath(f_base + ".diff.small.jpg")) jpegw.SetInput(gamma.GetOutput()) jpegw.SetQuality(85) jpegw.Write() # write out the image that was generated. shrink.SetInput(idiff.GetInput()) jpegw.SetInput(shrink.GetOutput()) jpegw.SetFileName(_getTempImagePath(f_base + ".test.small.jpg")) jpegw.Write() # write out the valid image that matched. shrink.SetInput(idiff.GetImage()) jpegw.SetInput(shrink.GetOutput()) jpegw.SetFileName(_getTempImagePath(f_base + ".small.jpg")) jpegw.Write()
def save(self, window, data): name, ok = self.gui.getInputName(window) if ok and name: name = str(name) dir = './Data/%s.jpg' % name render_window = window.qvtkWidget.GetRenderWindow() window_image_filter = vtk.vtkWindowToImageFilter() writer = vtk.vtkJPEGWriter() window_image_filter.SetInput(render_window) window_image_filter.Update() writer.SetInputConnection(window_image_filter.GetOutputPort()) writer.SetFileName(dir) render_window.Render() writer.Write() return True
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 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()
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()
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')
ren.ResetCamera(); (ren2.GetActiveCamera()).SetFocalPoint(planeCenter); upDirection = [float(point1Slice[0])-float(originSlice[0]),float(point1Slice[1])-float(originSlice[1]), float(point1Slice[2])-float(originSlice[2])]; (ren2.GetActiveCamera()).SetViewUp(upDirection); camPosition = [planeCenter[0]-planeNormal[0]*300, planeCenter[1]-planeNormal[1]*300, planeCenter[2]-planeNormal[2]*300]; (ren2.GetActiveCamera()).SetPosition(camPosition); win2imageFilter = vtk.vtkWindowToImageFilter(); win2imageFilter.SetInput(renWin); writerJPEG = vtk.vtkJPEGWriter(); writerJPEG.SetQuality(100); writerJPEG.SetInput(win2imageFilter.GetOutput()); writerJPEG.SetFileName(fileOutput+".jpg"); writerJPEG.Write(); for i in range(0,370,20): time.sleep(.03); (ren.GetActiveCamera()).Azimuth(-20); renWin.AddRenderer(ren); win2imageFilter = vtk.vtkWindowToImageFilter(); win2imageFilter.SetInput(renWin); writerJPEG = vtk.vtkJPEGWriter(); writerJPEG.SetInput(win2imageFilter.GetOutput()); writerJPEG.SetFileName(fileOutput+"_rotate_"+str(i)+".jpg");
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
#!/Users/seb/Work/code/ParaView/build/bin/pvpython import sys from vtk import vtkMetaImageReader, vtkProgrammableFilter, vtkUnsignedCharArray, vtkJPEGWriter, vtkPNGWriter basePath = '/Users/seb/Work/projects/NE-Phase2/' reader = vtkMetaImageReader() reader.SetFileName("/Users/seb/Work/projects/NE-Phase2/Patient05.mha") reader.Update() writer = vtkJPEGWriter() # vtkJPEGWriter() filter = vtkProgrammableFilter() def unfoldData(): inputDS = filter.GetInputDataObject(0, 0) outputDS = filter.GetImageDataOutput() dims = inputDS.GetDimensions() # dims[1] * dims[2] nbSlices = (dims[1] * dims[2]) / 2048 outputDS.SetDimensions(dims[0], dims[1] * dims[2] / nbSlices, nbSlices) outputDS.SetOrigin(0,0,0) outputDS.SetSpacing(1,1,1) for arrayIdx in range(inputDS.GetPointData().GetNumberOfArrays()): array = inputDS.GetPointData().GetArray(arrayIdx) size = dims[0] * dims[1] * dims[2]
mapper = vtk.vtkPolyDataMapper() #mapper.SetInput(coneSource.GetOutput()) mapper.SetInput(stlReader.GetOutput()) actor = vtk.vtkActor() actor.SetMapper(mapper) # Visualize renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(actor) renderer.SetBackground(.1, .2, .3) # Background color dark blue renderer.SetBackground(.3, .2, .1) # Background color dark red renderWindow.Render() # write render window to file windowToImage = vtk.vtkWindowToImageFilter() windowToImage.SetInput(renderWindow ) windowToImage.Update() jpgWriter = vtk.vtkJPEGWriter() jpgWriter.SetFileName( 'testtwo.jpg' ) jpgWriter.SetInput(windowToImage.GetOutput()) jpgWriter.Write() # interactive render #renderWindowInteractor.Start()
def WriteImageToDisk(self, filename): """Writes thumbnail to disk""" ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) ren.SetBackground(1.0, 1.0, 1.0) renWin.SetSize(200, 200) renWin.OffScreenRenderingOn() # determine image range self._image.Update() r = self._image.GetScalarRange() t = self._threshold # determine image spacing sp = self._image.GetSpacing() # cast image to unsigned char typ = self._image.GetScalarType() if ((typ != 3) or (typ != 5)): cast = vtk.vtkImageShiftScale() cast.SetInput(self._image) cast.SetOutputScalarTypeToUnsignedChar() cast.SetShift(-r[0]) if r[1] == r[0]: cast.SetScale(255.0 / (r[1] - r[0] + 1)) t = (self._threshold - r[0]) * (255.0 / (r[1] - r[0] + 1)) else: cast.SetScale(255.0 / (r[1] - r[0])) t = (self._threshold - r[0]) * (255.0 / (r[1] - r[0])) r = [0, 255.0] o = cast.GetOutput() else: o = self._image.GetOutput() # build a LUT tfun = vtk.vtkPiecewiseFunction() tfun.AddPoint(r[0], 0.0) tfun.AddPoint(t - (r[1] - r[0]) / 1024., 0.0) tfun.AddPoint(t, 0.2) tfun.AddPoint(r[1], 0.2) ctfun = vtk.vtkColorTransferFunction() ctfun.AddRGBPoint(r[0], 1, 1, 1) ctfun.AddRGBPoint(r[1], 1, 1, 1) function = vtk.vtkVolumeRayCastIsosurfaceFunction() # tunable function.SetIsoValue(t) volumeMapper = vtk.vtkVolumeRayCastMapper() volumeMapper.SetInput(o) volumeMapper.SetVolumeRayCastFunction(function) volumeMapper.SetSampleDistance(max(sp) * 1.0) # tunable volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(ctfun) volumeProperty.SetScalarOpacity(tfun) volumeProperty.SetInterpolationTypeToLinear() # tunable volumeProperty.ShadeOn() newvol = vtk.vtkVolume() newvol.SetMapper(volumeMapper) newvol.SetProperty(volumeProperty) # Add volume to renderer ren.AddVolume(newvol) # set up inital camera camera = ren.GetActiveCamera() camera.Elevation(-60.0) camera.SetViewAngle(20) # grab image renWin.Render() windowToimage = vtk.vtkWindowToImageFilter() windowToimage.SetInput(renWin) # save image writer = vtk.vtkJPEGWriter() writer.SetInput(windowToimage.GetOutput()) writer.SetFileName(filename) writer.SetQuality(85) writer.Write()
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
def createMorph(selectedImages,selectedPMs): """ Translates and rotate the bitmaps based on the shapedefining landmarks (selectedPMs) of the associated image to the target image (first image). Morphs the result so that the bitmap overlay on the first image is valid for the first image. """ #save the temporary results here later: os_temp_path = tempfile.gettempdir() #get the measurements for the first image (our targets) mainImage = OriginalImage.objects.all().get(id=selectedImages[0]) potentialids = [] #now get the associated measurements measures = Measurement.objects.all().filter(id__in=selectedPMs[0]).filter(mogelijkemeting__shapedefining=True) measures = [j for j in measures] measures.sort(key=lambda x: x.mogelijkemeting.name) coordsx = [] coordsy = [] for k, measurement in enumerate(measures): coordsx.append(float(measurement.x)) coordsy.append(float(measurement.y)) potentialids.append(measurement.mogelijkemeting.id) r1 = vtk.vtkJPEGReader() r1.SetFileName(settings.DATADIR + mainImage.id + ".jpg") r1.Update() # flip y coord (VTK has opposite convention), create 3-d coords (z=0) ydim = r1.GetOutput().GetDimensions()[1] coords = [(x, ydim - y, 0) for (x,y) in zip(coordsx, coordsy)] # convert everything to vtkPoints lmt = vtk.vtkPoints() lmt.SetNumberOfPoints(len(coords)) for i, coord in enumerate(coords): lmt.SetPoint(i,coord) #The target is clear, let's get to work, get the source images... images = [] #we don't need the first image or its measures anymore, because they don't need to be transformed or morphed selectedImages.pop(0) selectedPMs.pop(0) for id in selectedImages: images.append(OriginalImage.objects.all().get(id=id)) transformations = [] morphtransformations = [] #Create a new database object for the target image to associate the bitmaps with img = OriginalImage(project=mainImage.project, name='MorphedImage') img.save() imp = Image.open(settings.DATADIR + mainImage.id + '.jpg') imp.save(settings.DATADIR + img.id + '.jpg', 'JPEG') orig_bitmaps = Bitmap.objects.all().filter(image=mainImage) for bm in orig_bitmaps: #store bitmaps of mainImage as sub of img bitmap = Bitmap(project=img.project, name='warpedbitmap', image=img, mogelijkemeting=bm.mogelijkemeting, imagewidth=bm.imagewidth, imageheight=bm.imageheight, minx=bm.minx, miny=bm.miny, maxx=bm.maxx, maxy=bm.maxy) bitmap.save() bitmap_image = Image.open(settings.DATADIR + bm.id + '.gif') bitmap_image = bitmap_image.convert("RGBA") bitmap_image.save(settings.DATADIR + bitmap.id + '.gif', transparency=0) #now get the other images and perform our transformations for i in range(len(images)): measures = Measurement.objects.all().filter(id__in=selectedPMs[i]).filter(mogelijkemeting__shapedefining=True)#get measurements measures = [j for j in measures] measures.sort(key=lambda x: x.mogelijkemeting.name) coordsx = [] coordsy = [] for k, measurement in enumerate(measures): coordsx.append(float(measurement.x)) coordsy.append(float(measurement.y)) if potentialids[k] != measurement.mogelijkemeting.id: #the potentialmeasurements do not match up to the ones in the target image return img, 0 r = vtk.vtkJPEGReader() r.SetFileName(settings.DATADIR + images[i].id + ".jpg") r.Update() ydim = r.GetOutput().GetDimensions()[1] coordso = [(x, ydim - y, 0) for (x,y) in zip(coordsx, coordsy)] lms = vtk.vtkPoints() lms.SetNumberOfPoints(len(coordso)) for k, coord in enumerate(coordso): lms.SetPoint(k,coord) transformation = vtk.vtkLandmarkTransform() transformation.SetTargetLandmarks(lmt) lmt.Modified() transformation.SetSourceLandmarks(lms) lms.Modified() #size matters, so set the mode to Rigid Body (also known as do not scale please) transformation.SetModeToRigidBody() transformation.Inverse() transformation.Update() out = vtk.vtkPoints()#this will be the source of our morph transform transformation.TransformPoints(lms,out) transformations.append(transformation) ir = vtk.vtkImageReslice() # we're not using linear, because we want to improve the quality of the bitmaps ir.SetInterpolationModeToNearestNeighbor() ir.SetResliceTransform(transformation) ir.SetInput(r.GetOutput()) ir.SetInformationInput(r1.GetOutput()) w = vtk.vtkJPEGWriter() w.SetFileName(os_temp_path+'/translated'+images[i].id+'.jpg') w.SetInput(ir.GetOutput()) w.Write() r2 = vtk.vtkJPEGReader() r2.SetFileName(os_temp_path+'/translated'+images[i].id+'.jpg') r2.Update() # the mighty morphing ThinPlateSplineTransform morphtransform = vtk.vtkThinPlateSplineTransform() morphtransform.SetBasisToR2LogR() morphtransform.SetSourceLandmarks(lms) lms.Modified() morphtransform.SetTargetLandmarks(lmt) lmt.Modified() morphtransform.Inverse() morphtransform.Update() morphtransformations.append(morphtransform) #ir.SetInput(r2.GetOutput()) #ir.SetInformationInput(r1.GetOutput()) bitmaps = Bitmap.objects.all().filter(image=images[i]) #now perform the total transformation on all bitmaps for bm in bitmaps: location = settings.DATADIR + bm.id + ".gif" im = Image.open(location) im = im.convert("RGBA") im.save(settings.DATADIR + bm.id + ".png", "PNG") r3 = vtk.vtkPNGReader() r3.SetFileName(settings.DATADIR + bm.id + '.png') r3.Update() ir2 = vtk.vtkImageReslice() ir2.SetInterpolationModeToNearestNeighbor() ir2.SetResliceTransform(morphtransform) ir2.SetInput(r3.GetOutput()) ir2.SetInformationInput(r2.GetOutput()) w3 = vtk.vtkPNGWriter() w3.SetFileName(os_temp_path+'/morphed'+bm.id+'.png') w3.SetInput(ir2.GetOutput()) w3.Write() bitmap = Bitmap(project=img.project, name='warpedbitmap', image=img, mogelijkemeting=bm.mogelijkemeting, imagewidth=bm.imagewidth, imageheight=bm.imageheight, minx=bm.minx, miny=bm.miny, maxx=bm.maxx, maxy=bm.maxy) bitmap.save() im = Image.open(os_temp_path+'/morphed'+bm.id+'.png') im = im.convert("RGBA") im.save(settings.DATADIR + bitmap.id + '.gif', transparency=0) return img, 1
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() psw2.SetInputConnection(luminance.GetOutputPort()) psw2.SetFileName("" + str(dir) + "/psw2.ps") pngw1 = vtk.vtkPNGWriter() pngw1.SetInputConnection(image1.GetOutputPort()) pngw1.SetFileName("" + str(dir) + "/pngw1.png") pngw2 = vtk.vtkPNGWriter() pngw2.SetInputConnection(luminance.GetOutputPort()) pngw2.SetFileName("" + str(dir) + "/pngw2.png") jpgw1 = vtk.vtkJPEGWriter() jpgw1.SetInputConnection(image1.GetOutputPort()) jpgw1.SetFileName("" + str(dir) + "/jpgw1.jpg") jpgw2 = vtk.vtkJPEGWriter() jpgw2.SetInputConnection(luminance.GetOutputPort()) jpgw2.SetFileName("" + str(dir) + "/jpgw2.jpg") tiff1.Write() tiff2.Write() bmp1.Write() bmp2.Write() pnm1.Write() pnm2.Write() psw1.Write() psw2.Write() pngw1.Write() pngw2.Write()