0
# I/O Operations
1
2
Comprehensive input/output functionality for reading and writing images in various formats including DICOM, NIfTI, PNG, JPEG, TIFF, and many scientific formats. SimpleITK provides both procedural functions for simple operations and class-based interfaces for advanced control over the I/O process.
3
4
## Capabilities
5
6
### Procedural I/O Functions
7
8
Simple functions for common read/write operations with automatic format detection.
9
10
```python { .api }
11
def ReadImage(filename: str, pixelType: int = None) -> Image:
12
"""
13
Read image from file with automatic format detection.
14
15
Args:
16
filename: Path to image file
17
pixelType: Optional pixel type to cast to (e.g., sitk.sitkFloat32)
18
19
Returns:
20
SimpleITK Image object
21
22
Supported formats: DICOM, NIfTI, Analyze, MetaImage, PNG, JPEG,
23
TIFF, BMP, LSM, Bio-Rad, Stimulate, VTK, Nrrd
24
"""
25
26
def WriteImage(image: Image, filename: str, useCompression: bool = False):
27
"""
28
Write image to file with automatic format detection based on extension.
29
30
Args:
31
image: SimpleITK Image to write
32
filename: Output file path
33
useCompression: Enable compression if supported by format
34
"""
35
36
def Show(image: Image, title: str = "", debugOn: bool = False):
37
"""
38
Display image using external viewer (ImageJ/Fiji by default).
39
40
Args:
41
image: Image to display
42
title: Window title
43
debugOn: Enable debug output
44
"""
45
```
46
47
### ImageFileReader Class
48
49
Advanced image reading with metadata access and format control.
50
51
```python { .api }
52
class ImageFileReader:
53
def __init__(self):
54
"""Initialize image file reader"""
55
56
def SetFileName(self, filename: str):
57
"""Set input filename"""
58
59
def GetFileName(self) -> str:
60
"""Get input filename"""
61
62
def Execute(self) -> Image:
63
"""Read image file and return Image object"""
64
65
def ReadImageInformation(self):
66
"""
67
Read only metadata without loading pixel data.
68
Call this before accessing image information methods.
69
"""
70
71
# Image information methods (valid after ReadImageInformation or Execute)
72
def GetSize(self) -> tuple:
73
"""Get image dimensions"""
74
75
def GetOrigin(self) -> tuple:
76
"""Get image origin"""
77
78
def GetSpacing(self) -> tuple:
79
"""Get pixel spacing"""
80
81
def GetDirection(self) -> tuple:
82
"""Get direction matrix"""
83
84
def GetNumberOfComponents(self) -> int:
85
"""Get number of components per pixel"""
86
87
def GetPixelID(self) -> int:
88
"""Get pixel type identifier"""
89
90
def GetPixelIDValue(self) -> int:
91
"""Get pixel type value"""
92
93
def GetDimension(self) -> int:
94
"""Get number of dimensions"""
95
96
def GetMetaDataKeys(self) -> list:
97
"""Get list of metadata keys"""
98
99
def GetMetaData(self, key: str) -> str:
100
"""Get metadata value for key"""
101
102
def HasMetaDataKey(self, key: str) -> bool:
103
"""Check if metadata key exists"""
104
105
# ImageIO control
106
def SetImageIO(self, imageio: str):
107
"""
108
Override automatic ImageIO selection.
109
110
Args:
111
imageio: ImageIO name (e.g., 'GDCMImageIO', 'NiftiImageIO')
112
"""
113
114
def GetImageIO(self) -> str:
115
"""Get name of ImageIO being used"""
116
117
def GetRegisteredImageIOs(self) -> list:
118
"""Get list of available ImageIO names"""
119
```
120
121
### ImageFileWriter Class
122
123
Advanced image writing with compression and format control.
124
125
```python { .api }
126
class ImageFileWriter:
127
def __init__(self):
128
"""Initialize image file writer"""
129
130
def SetFileName(self, filename: str):
131
"""Set output filename"""
132
133
def GetFileName(self) -> str:
134
"""Get output filename"""
135
136
def Execute(self, image: Image):
137
"""Write image to file"""
138
139
def SetUseCompression(self, compress: bool):
140
"""Enable or disable compression"""
141
142
def GetUseCompression(self) -> bool:
143
"""Get compression setting"""
144
145
def SetCompressionLevel(self, level: int):
146
"""
147
Set compression level (format dependent).
148
149
Args:
150
level: Compression level (typically 0-9)
151
"""
152
153
def GetCompressionLevel(self) -> int:
154
"""Get compression level"""
155
156
def SetImageIO(self, imageio: str):
157
"""Override automatic ImageIO selection"""
158
159
def GetImageIO(self) -> str:
160
"""Get name of ImageIO being used"""
161
162
def GetRegisteredImageIOs(self) -> list:
163
"""Get list of available ImageIO names"""
164
```
165
166
### ImageSeriesReader Class
167
168
Read image series (e.g., DICOM series, multi-file datasets).
169
170
```python { .api }
171
class ImageSeriesReader:
172
def __init__(self):
173
"""Initialize image series reader"""
174
175
def SetFileNames(self, filenames: list):
176
"""
177
Set list of filenames to read as series.
178
179
Args:
180
filenames: List of file paths in correct order
181
"""
182
183
def GetFileNames(self) -> list:
184
"""Get list of filenames"""
185
186
def Execute(self) -> Image:
187
"""Read series as single 3D image"""
188
189
def SetMetaDataDictionaryArrayUpdate(self, update: bool):
190
"""Enable metadata dictionary updates"""
191
192
def GetMetaDataDictionaryArrayUpdate(self) -> bool:
193
"""Get metadata dictionary update setting"""
194
195
def SetImageIO(self, imageio: str):
196
"""Set ImageIO for series reading"""
197
198
def GetImageIO(self) -> str:
199
"""Get ImageIO name"""
200
201
# DICOM-specific methods
202
def GetGDCMSeriesFileNames(self, directory: str, seriesID: str = "") -> list:
203
"""
204
Get DICOM series filenames from directory.
205
206
Args:
207
directory: Directory containing DICOM files
208
seriesID: Specific series ID to read (empty for first series)
209
210
Returns:
211
List of filenames in correct order
212
"""
213
214
def GetGDCMSeriesIDs(self, directory: str) -> list:
215
"""
216
Get list of DICOM series IDs in directory.
217
218
Args:
219
directory: Directory containing DICOM files
220
221
Returns:
222
List of series IDs
223
"""
224
```
225
226
### ImageSeriesWriter Class
227
228
Write image series to multiple files.
229
230
```python { .api }
231
class ImageSeriesWriter:
232
def __init__(self):
233
"""Initialize image series writer"""
234
235
def SetFileNames(self, filenames: list):
236
"""
237
Set output filenames for series.
238
239
Args:
240
filenames: List of output file paths
241
"""
242
243
def GetFileNames(self) -> list:
244
"""Get output filenames"""
245
246
def Execute(self, image: Image):
247
"""
248
Write 3D image as series of 2D images.
249
250
Args:
251
image: 3D image to write as series
252
"""
253
254
def SetUseCompression(self, compress: bool):
255
"""Enable compression"""
256
257
def GetUseCompression(self) -> bool:
258
"""Get compression setting"""
259
260
def SetImageIO(self, imageio: str):
261
"""Set ImageIO for series writing"""
262
263
def GetImageIO(self) -> str:
264
"""Get ImageIO name"""
265
```
266
267
### Image Viewer
268
269
Display images using external viewers.
270
271
```python { .api }
272
class ImageViewer:
273
def __init__(self):
274
"""Initialize image viewer"""
275
276
def SetTitle(self, title: str):
277
"""Set viewer window title"""
278
279
def GetTitle(self) -> str:
280
"""Get viewer window title"""
281
282
def SetApplication(self, app: str, args: str = ""):
283
"""
284
Set external viewer application.
285
286
Args:
287
app: Path to viewer executable
288
args: Command line arguments
289
"""
290
291
def GetApplication(self) -> tuple:
292
"""Get viewer application and arguments"""
293
294
def Execute(self, image: Image):
295
"""Display image using configured viewer"""
296
297
# Global viewer settings
298
def SetGlobalDefaultDebug(debug: bool):
299
"""Set global debug mode for viewer"""
300
301
def GetGlobalDefaultDebug() -> bool:
302
"""Get global debug mode setting"""
303
304
def SetGlobalDefaultDebugOn():
305
"""Enable global debug mode"""
306
307
def SetGlobalDefaultDebugOff():
308
"""Disable global debug mode"""
309
```
310
311
### Supported File Formats
312
313
SimpleITK supports numerous medical and scientific image formats through the ITK ImageIO framework:
314
315
```python { .api }
316
# Medical formats
317
DICOM_FORMATS = [".dcm", ".dicom", ".ima"]
318
NIFTI_FORMATS = [".nii", ".nii.gz", ".hdr", ".img"]
319
ANALYZE_FORMATS = [".hdr", ".img"]
320
MINC_FORMATS = [".mnc", ".mnc2"]
321
322
# Scientific formats
323
META_FORMATS = [".mhd", ".mha"]
324
NRRD_FORMATS = [".nrrd", ".nhdr"]
325
VTK_FORMATS = [".vtk"]
326
GIPL_FORMATS = [".gipl"]
327
328
# Standard image formats
329
RASTER_FORMATS = [".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp"]
330
HDR_FORMATS = [".hdr", ".pic"]
331
332
# Microscopy formats
333
LSM_FORMATS = [".lsm"]
334
BIO_RAD_FORMATS = [".pic"]
335
STIMULATE_FORMATS = [".spr"]
336
```
337
338
### Usage Examples
339
340
#### Basic File Operations
341
342
```python
343
import SimpleITK as sitk
344
345
# Simple read/write
346
image = sitk.ReadImage('input.dcm')
347
sitk.WriteImage(image, 'output.png')
348
349
# Read with specific pixel type
350
float_image = sitk.ReadImage('input.dcm', sitk.sitkFloat32)
351
352
# Write with compression
353
sitk.WriteImage(image, 'output.nii.gz', True)
354
```
355
356
#### Advanced Reading with Metadata
357
358
```python
359
import SimpleITK as sitk
360
361
# Create reader
362
reader = sitk.ImageFileReader()
363
reader.SetFileName('medical_image.dcm')
364
365
# Read only metadata first
366
reader.ReadImageInformation()
367
368
# Check image properties before loading
369
print(f"Image size: {reader.GetSize()}")
370
print(f"Pixel type: {reader.GetPixelID()}")
371
print(f"Spacing: {reader.GetSpacing()}")
372
373
# Check for specific metadata
374
if reader.HasMetaDataKey('0010|0010'): # Patient Name
375
patient = reader.GetMetaData('0010|0010')
376
print(f"Patient: {patient}")
377
378
# Now read the actual image
379
image = reader.Execute()
380
```
381
382
#### DICOM Series Reading
383
384
```python
385
import SimpleITK as sitk
386
import os
387
388
# Directory containing DICOM files
389
dicom_dir = "/path/to/dicom/series"
390
391
# Create series reader
392
series_reader = sitk.ImageSeriesReader()
393
394
# Get series IDs in directory
395
series_ids = series_reader.GetGDCMSeriesIDs(dicom_dir)
396
print(f"Found {len(series_ids)} series")
397
398
# Read first series
399
if series_ids:
400
series_id = series_ids[0]
401
dicom_files = series_reader.GetGDCMSeriesFileNames(dicom_dir, series_id)
402
print(f"Series contains {len(dicom_files)} files")
403
404
series_reader.SetFileNames(dicom_files)
405
image = series_reader.Execute()
406
407
print(f"3D image size: {image.GetSize()}")
408
```
409
410
#### Writing Image Series
411
412
```python
413
import SimpleITK as sitk
414
415
# Read 3D image
416
image_3d = sitk.ReadImage('volume.nii')
417
418
# Create output filenames
419
num_slices = image_3d.GetSize()[2]
420
filenames = [f'slice_{i:03d}.png' for i in range(num_slices)]
421
422
# Write as series
423
series_writer = sitk.ImageSeriesWriter()
424
series_writer.SetFileNames(filenames)
425
series_writer.Execute(image_3d)
426
```
427
428
#### Custom Viewer Setup
429
430
```python
431
import SimpleITK as sitk
432
433
# Set custom viewer (ImageJ/Fiji)
434
viewer = sitk.ImageViewer()
435
viewer.SetApplication('/path/to/ImageJ', '-eval "run(\\"Enhance Contrast\\", \\"saturated=0.35\\")"')
436
437
# Display image
438
image = sitk.ReadImage('data.dcm')
439
viewer.SetTitle('Medical Image')
440
viewer.Execute(image)
441
442
# Or use simple Show function
443
sitk.Show(image, 'Quick View', debugOn=True)
444
```
445
446
#### Format-Specific Options
447
448
```python
449
import SimpleITK as sitk
450
451
# Force specific ImageIO
452
reader = sitk.ImageFileReader()
453
reader.SetFileName('ambiguous_file')
454
reader.SetImageIO('GDCMImageIO') # Force DICOM reading
455
image = reader.Execute()
456
457
# Check available ImageIOs
458
available_ios = reader.GetRegisteredImageIOs()
459
print(f"Available ImageIOs: {available_ios}")
460
461
# Write with specific format options
462
writer = sitk.ImageFileWriter()
463
writer.SetFileName('output.tiff')
464
writer.SetUseCompression(True)
465
writer.SetCompressionLevel(6) # Medium compression
466
writer.Execute(image)
467
```