The range is from -500mm to 500mm, and all I know is I can save it by clicking Annotation Screenshot, and choosing Red Slice View
It would be great if someone could provide a Python script to save the Red Slice every 10 mm as png in an absolute directory, for example, C:\Users\jp1234\Documents
import os
import slicer
# Define the directory to save images
output_directory = "C:/Users/yourname/Documents/SlicerOutput"
if not os.path.exists(output_directory):
os.makedirs(output_directory)
# Define the range and step size
start = -500
end = 500
step = 10
# Get the Red Slice widget
red_logic = slicer.app.layoutManager().sliceWidget("Red").sliceLogic()
# Function to take and save screenshot
def saveScreenshot(sliceLogic, filename):
layoutManager = slicer.app.layoutManager()
sliceNode = sliceLogic.GetSliceNode()
sliceView = layoutManager.sliceWidget(sliceNode.GetLayoutName()).sliceView()
sliceView.forceRender()
w2i = vtk.vtkWindowToImageFilter()
w2i.SetInput(sliceView.renderWindow())
w2i.Update()
writer = vtk.vtkPNGWriter()
writer.SetFileName(filename)
writer.SetInputConnection(w2i.GetOutputPort())
writer.Write()
# Iterate over the range and save images
for position in range(start, end + 1, step):
# Set the slice offset
red_logic.SetSliceOffset(position)
# Define the file path
filename = f"Red_Slice_{position}mm.png"
filepath = os.path.join(output_directory, filename)
# Save the screenshot
saveScreenshot(red_logic, filepath)
# Optional: Print the file path to confirm saving
print("Saved:", filepath)
print("All slices saved successfully.")