Need help for a script of saving screenshot for many times

Hi, I am working on this red slice


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
image
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

Thank you!

This snippet from the repository should get you started …

Thanks, I created this one, and copied it to the Python Console, but nothing shows up

layoutName = "Red"
imagePathPattern = "C:/Users/jp1234/Documents/red_slice-%03d.png"
startOffset = -10
endOffset = 50
stepSize = 10

widget = slicer.app.layoutManager().sliceWidget(layoutName)
view = widget.sliceView()
logic = widget.sliceLogic()
bounds = [0,]*6
logic.GetSliceBounds(bounds)

currentOffset = startOffset
stepCount = 0

while currentOffset <= endOffset:
    logic.SetSliceOffset(currentOffset)
    view.forceRender()
    image = view.grab().toImage()
    image.save(imagePathPattern % stepCount)
    
    currentOffset += stepSize
    stepCount += 1

then I tried the example, but [Qt] QPixmap::grabWidget is deprecated, use QWidget::grab() instead

so I use this

img = qt.QWidget.grab(slicer.util.mainWindow()).toImage()
img.save("C:/Users/jp1234/Documents/red_slice-%03d.png")

Still nothing shows up

ChatGPT is here to help:-)

https://chat.openai.com/share/b43f0fe7-44c3-49a5-afad-fffa27d1c5aa

The last code iteration works:

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.")