本文整理汇总了Python中vtk.vtkPNGWriter函数的典型用法代码示例。如果您正苦于以下问题:Python vtkPNGWriter函数的具体用法?Python vtkPNGWriter怎么用?Python vtkPNGWriter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了vtkPNGWriter函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save_png
def save_png (self, file_name=""):
"""Requires VTK 4 to work."""
debug ("In RenderWindow::save_png ()")
try:
ex = vtk.vtkPNGWriter ()
except AttributeError:
msg = "Saving to a PNG 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 PNG image",
initialdir=Common.config.initial_dir,
defaultextension=".png",
filetypes=[("PNG images", "*.png"),
("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.vtkPNGWriter ()
ex.SetFileName (file_name)
ex.SetInput (w2if.GetOutput ())
ex.Write ()
Common.state.idle ()
示例2: run
def run(self):
global vtk_error
#----- verify extension ------------------
extension = VerifyDataType(self.filepath)
file_name = self.filepath.split(os.path.sep)[-1]
n_array = ReadBitmap(self.filepath)
if not(isinstance(n_array, numpy.ndarray)):
return False
image = converters.to_vtk(n_array, spacing=(1,1,1),\
slice_number=1, orientation="AXIAL")
dim = image.GetDimensions()
x = dim[0]
y = dim[1]
img = vtk.vtkImageResample()
img.SetInputData(image)
img.SetAxisMagnificationFactor ( 0, 0.25 )
img.SetAxisMagnificationFactor ( 1, 0.25 )
img.SetAxisMagnificationFactor ( 2, 1 )
img.Update()
tp = img.GetOutput().GetScalarTypeAsString()
image_copy = vtk.vtkImageData()
image_copy.DeepCopy(img.GetOutput())
thumbnail_path = tempfile.mktemp()
write_png = vtk.vtkPNGWriter()
write_png.SetInputConnection(img.GetOutputPort())
write_png.AddObserver("WarningEvent", VtkErrorPNGWriter)
write_png.SetFileName(thumbnail_path)
write_png.Write()
if vtk_error:
img = vtk.vtkImageCast()
img.SetInputData(image_copy)
img.SetOutputScalarTypeToUnsignedShort()
#img.SetClampOverflow(1)
img.Update()
write_png = vtk.vtkPNGWriter()
write_png.SetInputConnection(img.GetOutputPort())
write_png.SetFileName(thumbnail_path)
write_png.Write()
vtk_error = False
id = wx.NewId()
bmp_item = [self.filepath, thumbnail_path, extension, x, y,\
str(x) + ' x ' + str(y), file_name, id]
self.bmp_file.Add(bmp_item)
示例3: write_picture
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()
示例4: png
def png(self, file, width=None,height=None,units=None,draw_white_background = 0):
if self.renWin is None:
raise Exception,"Nothing to dump aborting"
if not file.split('.')[-1].lower() in ['png']:
file+='.png'
try:
os.remove(file)
except:
pass
if width is not None and height is not None:
self.renWin.SetSize(width,height)
#self.renWin.Render()
imgfiltr = vtk.vtkWindowToImageFilter()
imgfiltr.SetInput(self.renWin)
# imgfiltr.SetMagnification(3)
imgfiltr.SetInputBufferTypeToRGBA()
imgfiltr.Update()
writer = vtk.vtkPNGWriter()
writer.SetInputConnection(imgfiltr.GetOutputPort())
writer.SetFileName(file)
writer.Write()
示例5: show
def show(window, name=None, magnification=2):
interactor = vtk.vtkRenderWindowInteractor()
interactor.SetRenderWindow(window)
interactor.Initialize()
window.Render()
interactor.Start()
windowToImageFilter = vtk.vtkWindowToImageFilter()
windowToImageFilter.SetInput(window)
windowToImageFilter.SetMagnification(magnification)
windowToImageFilter.SetInputBufferTypeToRGBA()
windowToImageFilter.ReadFrontBufferOff()
windowToImageFilter.Update()
writer = vtk.vtkPNGWriter()
if name is None:
filehandler = NamedTemporaryFile(delete=False)
else:
filehandler = open(name, 'w')
writer.SetFileName(filehandler.name)
writer.SetInputConnection(windowToImageFilter.GetOutputPort())
writer.Write()
window.Finalize()
interactor.TerminateApp()
del interactor
axes = plt.subplot()
axes.imshow(img.imread(filehandler.name))
axes.axis('off')
if name is None:
os.unlink(filehandler.name)
示例6: WriteImage
def WriteImage(self, m_outFileName="./Dump/tmp.png", m_dimension=[400, 400]):
"""
Write current renderer to a png file. For Debug
:param m_outFileName: [str] Output name of the file, can be directory name. Default="./Dump/tmp.png"
:param m_dimension: [x, y]. Dimension, i.e. width and height of the image file.
:return:
"""
if self._renderer.GetRenderWindow() == None:
self._renderWindow.AddRenderer(self._renderer)
elif self._renderer.GetRenderWindow() != self._renderWindow:
self._renderer.GetRenderWindow().Finalize()
self._renderWindow = vtk.vtkRenderWindow()
self._renderWindow.AddRenderer(self._renderer)
else:
self._renderWindow = vtk.vtkRenderWindow()
self._renderWindow.AddRenderer(self._renderer)
self._renderWindow.SetOffScreenRendering(1)
self._renderWindow.SetSize(m_dimension)
self._renderWindow.Render()
self._renderWindow.SetAAFrames(10)
m_writer = vtk.vtkPNGWriter()
m_wintoim = vtk.vtkWindowToImageFilter()
m_wintoim.SetInput(self._renderWindow)
m_wintoim.Update()
m_writer.SetInputConnection(m_wintoim.GetOutputPort())
m_writer.SetFileName(m_outFileName)
m_writer.Write()
pass
示例7: takeSimShot
def takeSimShot(self, fileName):
# print MODULENAME,' takeSimShot: fileName=',fileName
# DON'T REMOVE!
# Better quality
# Passes vtkRenderer. Takes actual screenshot of the region within the widget window
# If other application are present within this region it will shoot them also
renderLarge = vtk.vtkRenderLargeImage()
renderLarge.SetInput(self.graphicsFrameWidget.ren)
renderLarge.SetMagnification(1)
# 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.
# writer = vtk.vtkPNGWriter()
writer = vtk.vtkPNGWriter()
writer.SetInputConnection(renderLarge.GetOutputPort())
print MODULENAME,"takeSimShot(): vtkPNGWriter, fileName=",fileName
writer.SetFileName(fileName)
print 'TRYING TO WRITE ',fileName
writer.Write()
print 'WROTE ',fileName
示例8: output_screenshot
def output_screenshot(self, screenshot_fname):
"""
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()
renWin = vtk.vtkRenderWindow()
renWin.SetOffScreenRendering(1)
renWin.AddRenderer(ren)
renWin.Render()
windowToImageFilter = vtk.vtkWindowToImageFilter()
windowToImageFilter.SetInput(renWin)
windowToImageFilter.Update()
writer = vtk.vtkPNGWriter()
# writer.SetFileName('D:/CC3D_GIT/CompuCell3D/player5/GraphicsOffScreen/{screenshot_name}.png'.format(
# screenshot_name=screenshot_fname))
writer.SetFileName(screenshot_fname)
writer.SetInputConnection(windowToImageFilter.GetOutputPort())
writer.Write()
示例9: OnExport
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()
示例10: drawLineLineTest
def drawLineLineTest():
myscreen = ovdvtk.VTKScreen()
myscreen.camera.SetPosition(0.01, 0, 1000 )
myscreen.camera.SetFocalPoint(0, 0, 0)
myscreen.camera.SetClippingRange(-100,3000)
w2if = vtk.vtkWindowToImageFilter()
w2if.SetInput(myscreen.renWin)
lwr = vtk.vtkPNGWriter()
lwr.SetInput( w2if.GetOutput() )
l1 = Line( math.cos(1), math.sin(1) , 1 , +1) # first line-site
drawLine(myscreen, l1, ovdvtk.yellow )
l2 = Line( math.cos(3), math.sin(3) , 1 , -1) # second line-site
drawLine(myscreen, l2, ovdvtk.orange )
l1l2 = LineLine( l1, l2 ) # bisectors
l2l1 = LineLine( l2, l1 ) # it should not matter if we call with (l1,l2) or (l2,l1) (?)
print l1l2
print l2l1
b1= Bisector( l1l2 )
b2= Bisector( l2l1 )
drawBisector( myscreen, b1 )
drawBisector( myscreen, b2 )
myscreen.render()
myscreen.iren.Start()
示例11: save_png
def save_png(image, filename):
from vtk import vtkPNGWriter
writer = vtkPNGWriter()
writer.SetFileName(filename)
writer.SetInputData(image)
writer.Update()
writer.Write()
示例12: save
def save(self, frames, outfile='animated.mp4'):
'''
takes a snapshot of the frames at given t, and returns the paths
'''
windowToImage = vtk.vtkWindowToImageFilter()
windowToImage.SetInput(self.renWin)
writer = vtk.vtkPNGWriter()
writer.SetInput(windowToImage.GetOutput())
slide_paths = []
for t in frames:
# f = NamedTemporaryFile(suffix='.png', delete=False)
f = open("img{:0>3}.png".format(t), 'w')
self.update_all(t=t)
windowToImage.Modified()
writer.SetFileName(f.name)
writer.Write()
slide_paths.append( f.name )
if len(slide_paths)==1:
if not outfile.endswith('.png'):
raise Exception("Cannot save single snapshot videos")
call(["mv","img000.png",outfile])
elif outfile.endswith('.mp4'):
call(["rm","-f", outfile])
call(["/usr/local/bin/ffmpeg",
"-i","img%03d.png",
"-c:v","libx264","-r","30",
"-pix_fmt","yuv420p", outfile])
call(["rm"]+slide_paths)
示例13: WritePNGImageFile
def WritePNGImageFile(self):
if (self.OutputFileName == ''):
self.PrintError('Error: no OutputFileName.')
self.PrintLog('Writing PNG 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.vtkPNGWriter()
writer.SetInputData(outputImage)
if self.Image.GetDimensions()[2] == 1:
writer.SetFileName(self.OutputFileName)
else:
writer.SetFilePrefix(self.OutputFileName)
writer.SetFilePattern("%s%04d.png")
writer.Write()
示例14: saveToPNG
def saveToPNG(self, filename):
""" saveToPNG(filename: str) -> filename or vtkUnsignedCharArray
Save the current widget contents to an image file. If
str==None, then it returns the vtkUnsignedCharArray containing
the PNG image. Otherwise, the filename is returned.
"""
w2i = vtk.vtkWindowToImageFilter()
w2i.ReadFrontBufferOff()
w2i.SetInput(self.mRenWin)
# Render twice to get a clean image on the back buffer
if self.mRenWin.GetInteractor():
self.mRenWin.GetInteractor().Render()
self.mRenWin.GetInteractor().Render()
else:
self.mRenWin.Render()
self.mRenWin.Render()
w2i.Update()
writer = vtk.vtkPNGWriter()
writer.SetInputConnection(w2i.GetOutputPort())
if filename!=None:
writer.SetFileName(filename)
else:
writer.WriteToMemoryOn()
writer.Write()
if filename:
return filename
else:
return writer.GetResult()
示例15: SavePNG
def SavePNG():
png_number=__main__.png_number
option_verbose=__main__.option_verbose
option_prefix=__main__.option_prefix
renwin=__main__.renwin
rtTimer=vtk.vtkTimerLog
my_print(option_verbose,'----------------------------')
my_print(option_verbose,'Saving PNG')
rtStartCPU=rtTimer.GetCPUTime()
w2i = vtk.vtkWindowToImageFilter()
w2i.SetInput(renwin)
w2i.Update()
filepng=option_prefix+'_%03d.png' %png_number
my_print(option_verbose,'Start writing PNG file', filepng)
pngw = vtk.vtkPNGWriter()
pngw.SetInputConnection(w2i.GetOutputPort())
pngw.SetFileName(filepng)
pngw.Write()
rtEndCPU=rtTimer.GetCPUTime()
my_print(option_verbose,'End writing PNG file')
my_print(option_verbose,'CPU time:', rtEndCPU-rtStartCPU)
__main__.png_number=png_number+1