I have drawn the blue box by hand to understand the problem.
I want to save the blue box content as PNG file.
I can find the coordinates of the boundary points of the blue box.
ModelNode = slicer.mrmlScene.GetFirstNodeByName('Model')
Vertices = numpy_support.vtk_to_numpy(ModelNode.GetPolyData().GetPoints().GetData())
blueboxMin=[Vertices[:,0].min(), Vertices[:,1].min(), Vertices[:,2].min()]
blueboxMax=[Vertices[:,0].max(), Vertices[:,1].max(), Vertices[:,2].max()]
But I don’t know how to save this region inside as PNG.
If you want a quick image of the 3D View, you can right-click in the view and select “Copy image” which will copy it to your clipboard and then you can paste it to your application of choice for saving as a png, or paste it directly into a power point file.
You can also use the “Screen Capture” module to save images of the various slice views.
Thanks Jame,
I found the solution to the problem:
# Set background to black (required for transparent background)
view = slicer.app.layoutManager().threeDWidget(0).threeDView()
view.rotateToViewAxis(3) # look from anterior direction
#view.resetFocalPoint() # reset the 3D view cube size and center it
#view.resetCamera() # reset camera zoom
after that
# Capture RGBA image
renderWindow = view.renderWindow()
renderWindow.SetAlphaBitPlanes(1)
wti = vtk.vtkWindowToImageFilter()
wti.SetInputBufferTypeToRGBA()
wti.SetInput(renderWindow)
writer = vtk.vtkPNGWriter()
writer.SetFileName("C:/Users/Administrator/Desktop/Slicer/face.png")
writer.SetInputConnection(wti.GetOutputPort())
writer.Write()
and cropping RGB
image = Image.open("C:/Users/Administrator/Desktop/Slicer/face.png")
image = image.convert("RGBA")
width, height = image.size
left = width
top = height
right = 0
bottom = 0
for x in range(width):
for y in range(height):
pixel = image.getpixel((x, y))
if pixel[3] != 0:
left = min(left, x)
top = min(top, y)
right = max(right, x)
bottom = max(bottom, y)
cropped_image = image.crop((left, top, right + 1, bottom + 1))
cropped_image.save("cropped_face.png")