Saving series of images from a Slice View

Hello,

I am trying to save a series of images from red, green, yellow slice to PNG format using the ‘execfile’ command. I am following the example from here
https://www.slicer.org/wiki/Documentation/Nightly/ScriptRepository#Capture

I copy and paste the code into a file and save it into the location e.g., Desktop\record.py (full path). But when I run the code in Python interactor → execfile(‘Desktop\record.py’) it throws errors

File “”, line 1, in
IOError: [Errno 2] No such file or directory: ‘C:\Users\Desktop\record.py’

Here is the line that displayed from my Python interactor.
Python 2.7.13 (default, Dec 20 2017, 00:45:45) [MSC v.1800 64 bit (AMD64)] on win32

I wonder if anybody can give me any hint on this issue?

Thanks

Dedy

In python you need to use forward slashes (‘c:/Users’ not ‘c:\Users’)

1 Like

Yes, \ is an escape character, so you either have to use \\ or / or indicate that it is a raw string by prefixing it with r. Any of these will work:

r'C:\Users\Desktop\record.py'
'C:\\Users\\Desktop\\record.py'
'C:/Users/Desktop/record.py'

Note that you can record slice sweeps into a series of png files, animated gif, or video by using ScreenCapture module. You can also use ScreenCapture module from script, for example:

import ScreenCapture
ScreenCapture.ScreenCaptureLogic().captureSliceSweep(getNode('vtkMRMLSliceNodeRed'), -125.0, 75.0, 30, r"c:\tmp", "image_%05d.png")
1 Like

oh yes. I am new to python. it works . many thanks.

Hi Andras,

Thank you for providing this information. I’ve managed to save images from slice view in PNG format.

However, is it possible to save the images without background color (black)?

I managed to do it in Matlab by adding alpha value to zero for background color of PNG images. But, I am curious if this could be also done in Slicer?

Thanks

Dedy

The easiest is to set the image size and zoom to include as much of the image and borders as you need.

Also note that this kind of exported data must not be used for further processing, only for visualization in presentations, etc. (for many reasons, including reduced bit depth, resampling, lack of image spacing information and other metadata).

If you use Matlab then you can run MatlabBridge extension to run Matlab functions directly from Slicer. Or, you can also use nrrdread.m function to read volumes saved in Slicer into Matlab (https://github.com/PerkLab/SlicerMatlabBridge/tree/master/MatlabCommander/commandserver). In the long term, you may consider switching from Matlab to Python, as Python can do almost everything as Matlab can, but Python has many advantages.

1 Like