0
# Preprocessing Transforms
1
2
Comprehensive preprocessing transforms for medical images including spatial transformations (resampling, cropping, padding), intensity normalization (z-score, histogram standardization), and specialized medical imaging preprocessing. These transforms prepare medical images for analysis and training.
3
4
## Capabilities
5
6
### Spatial Preprocessing
7
8
Spatial transforms that modify the geometry, orientation, or spatial properties of medical images while preserving anatomical relationships.
9
10
#### Resampling
11
12
Resamples images to specified voxel spacing, enabling standardization of resolution across different imaging protocols and scanners.
13
14
```python { .api }
15
class Resample(SpatialTransform):
16
"""
17
Resample images to specified voxel spacing.
18
19
Parameters:
20
- target: Target voxel spacing in mm (float or tuple of 3 floats)
21
- image_interpolation: Interpolation for intensity images ('linear', 'nearest', 'bspline')
22
- label_interpolation: Interpolation for label images ('nearest')
23
"""
24
def __init__(
25
self,
26
target: TypeSpacing,
27
image_interpolation: str = 'linear',
28
label_interpolation: str = 'nearest'
29
): ...
30
```
31
32
#### Resize
33
34
Resizes images to specified shape, changing the number of voxels while maintaining physical spacing relationships.
35
36
```python { .api }
37
class Resize(SpatialTransform):
38
"""
39
Resize images to specified shape.
40
41
Parameters:
42
- target_shape: Target shape (int or tuple of 3 ints)
43
- image_interpolation: Interpolation method for intensity images
44
"""
45
def __init__(
46
self,
47
target_shape: TypeSpatialShape,
48
image_interpolation: str = 'linear'
49
): ...
50
```
51
52
#### Cropping and Padding
53
54
```python { .api }
55
class Crop(SpatialTransform):
56
"""
57
Crop images to specified region.
58
59
Parameters:
60
- cropping: Crop specification (int, tuple, or dict)
61
"""
62
def __init__(self, cropping: Union[int, tuple, dict]): ...
63
64
class Pad(SpatialTransform):
65
"""
66
Pad images with specified padding.
67
68
Parameters:
69
- padding: Padding specification (int, tuple, or dict)
70
- padding_mode: Padding mode ('constant', 'edge', 'wrap', 'empty')
71
"""
72
def __init__(
73
self,
74
padding: Union[int, tuple, dict],
75
padding_mode: str = 'constant'
76
): ...
77
78
class CropOrPad(SpatialTransform):
79
"""
80
Crop or pad images to achieve target shape.
81
82
Parameters:
83
- target_shape: Target spatial shape
84
- padding_mode: Padding mode for padding operations
85
"""
86
def __init__(
87
self,
88
target_shape: TypeSpatialShape,
89
padding_mode: str = 'constant'
90
): ...
91
```
92
93
#### Orientation and Canonical Transforms
94
95
```python { .api }
96
class ToCanonical(SpatialTransform):
97
"""
98
Reorient images to canonical orientation (RAS+).
99
100
Ensures consistent orientation across all images, with:
101
- Right-to-Left as first axis
102
- Anterior-to-Posterior as second axis
103
- Superior-to-Inferior as third axis
104
"""
105
def __init__(self): ...
106
107
class ToOrientation(SpatialTransform):
108
"""
109
Reorient images to specified orientation.
110
111
Parameters:
112
- target: Target orientation (e.g., 'RAS', 'LPS')
113
"""
114
def __init__(self, target: str): ...
115
116
class Transpose(SpatialTransform):
117
"""
118
Transpose image dimensions.
119
120
Parameters:
121
- axes: Permutation of axes (tuple of 3 ints)
122
"""
123
def __init__(self, axes: tuple[int, int, int]): ...
124
```
125
126
#### Specialized Spatial Transforms
127
128
```python { .api }
129
class ToReferenceSpace(SpatialTransform):
130
"""
131
Transform images to reference space defined by another image.
132
133
Parameters:
134
- reference: Reference image or path to reference image
135
"""
136
def __init__(self, reference: Union['Image', TypePath]): ...
137
138
class CopyAffine(SpatialTransform):
139
"""
140
Copy affine transformation from one image to others.
141
142
Parameters:
143
- target: Name of image to copy affine from
144
"""
145
def __init__(self, target: str): ...
146
147
class EnsureShapeMultiple(SpatialTransform):
148
"""
149
Ensure image shape is multiple of specified value.
150
151
Parameters:
152
- multiple: Value that shape dimensions should be multiple of
153
"""
154
def __init__(self, multiple: int): ...
155
```
156
157
Usage example:
158
159
```python
160
import torchio as tio
161
162
# Spatial preprocessing pipeline
163
spatial_preprocessing = tio.Compose([
164
tio.ToCanonical(), # Standardize orientation
165
tio.Resample(1), # Resample to 1mm isotropic
166
tio.CropOrPad((128, 128, 64)), # Standardize shape
167
tio.EnsureShapeMultiple(16), # Ensure shape divisible by 16
168
])
169
170
subject = tio.Subject(
171
t1=tio.ScalarImage('t1.nii.gz'),
172
seg=tio.LabelMap('segmentation.nii.gz')
173
)
174
175
transformed = spatial_preprocessing(subject)
176
```
177
178
### Intensity Preprocessing
179
180
Intensity transforms that normalize, standardize, or modify the intensity values of medical images while preserving spatial structure.
181
182
#### Normalization Transforms
183
184
```python { .api }
185
class ZNormalization(IntensityTransform):
186
"""
187
Z-score normalization (zero mean, unit variance).
188
189
Parameters:
190
- masking_method: Method for creating mask ('brain', 'label', etc.)
191
"""
192
def __init__(self, masking_method: str = None): ...
193
194
class RescaleIntensity(IntensityTransform):
195
"""
196
Rescale intensities to specified range.
197
198
Parameters:
199
- out_min_max: Output range (tuple of min, max values)
200
- percentiles: Input percentiles to use for scaling
201
"""
202
def __init__(
203
self,
204
out_min_max: tuple[float, float] = (0, 1),
205
percentiles: tuple[float, float] = (0.5, 99.5)
206
): ...
207
208
class HistogramStandardization(IntensityTransform):
209
"""
210
Histogram standardization using learned landmarks.
211
212
Parameters:
213
- landmarks: Dictionary mapping image keys to landmark arrays
214
"""
215
def __init__(self, landmarks: dict): ...
216
```
217
218
#### Intensity Manipulation
219
220
```python { .api }
221
class Clamp(IntensityTransform):
222
"""
223
Clamp intensity values to specified range.
224
225
Parameters:
226
- out_min_max: Output range (tuple of min, max values)
227
"""
228
def __init__(self, out_min_max: tuple[float, float]): ...
229
230
class Mask(IntensityTransform):
231
"""
232
Apply binary mask to images.
233
234
Parameters:
235
- masking_method: Masking method or mask image name
236
- mask_value: Value to use for masked regions
237
"""
238
def __init__(
239
self,
240
masking_method: Union[str, 'Image'],
241
mask_value: float = 0
242
): ...
243
```
244
245
#### Advanced Intensity Transforms
246
247
```python { .api }
248
class PCA(IntensityTransform):
249
"""
250
Principal Component Analysis for multi-channel images.
251
252
Parameters:
253
- num_components: Number of components to keep
254
"""
255
def __init__(self, num_components: int): ...
256
257
class To(IntensityTransform):
258
"""
259
Convert images to specified type or device.
260
261
Parameters:
262
- dtype: Target data type
263
- device: Target device ('cpu', 'cuda')
264
"""
265
def __init__(
266
self,
267
dtype: torch.dtype = None,
268
device: str = None
269
): ...
270
```
271
272
Usage example:
273
274
```python
275
# Intensity preprocessing pipeline
276
intensity_preprocessing = tio.Compose([
277
tio.RescaleIntensity(out_min_max=(0, 1)), # Scale to [0,1]
278
tio.ZNormalization(masking_method='brain'), # Z-score with brain mask
279
tio.Clamp(out_min_max=(-3, 3)), # Clamp outliers
280
])
281
282
subject = tio.Subject(
283
t1=tio.ScalarImage('t1.nii.gz'),
284
t2=tio.ScalarImage('t2.nii.gz')
285
)
286
287
normalized = intensity_preprocessing(subject)
288
```
289
290
### Label Preprocessing
291
292
Specialized transforms for processing segmentation and label images, including label manipulation, connectivity analysis, and label format conversions.
293
294
```python { .api }
295
class OneHot(LabelTransform):
296
"""
297
Convert labels to one-hot encoding.
298
299
Parameters:
300
- num_classes: Number of classes (optional, inferred if not provided)
301
"""
302
def __init__(self, num_classes: int = None): ...
303
304
class Contour(LabelTransform):
305
"""
306
Extract contours from label maps.
307
308
Parameters:
309
- radius: Radius for contour extraction
310
"""
311
def __init__(self, radius: int = 1): ...
312
313
class RemapLabels(LabelTransform):
314
"""
315
Remap label values according to mapping dictionary.
316
317
Parameters:
318
- remapping: Dictionary mapping old labels to new labels
319
"""
320
def __init__(self, remapping: dict[int, int]): ...
321
322
class RemoveLabels(LabelTransform):
323
"""
324
Remove specified labels by setting them to background.
325
326
Parameters:
327
- labels: Labels to remove (int or list of ints)
328
"""
329
def __init__(self, labels: Union[int, list[int]]): ...
330
331
class SequentialLabels(LabelTransform):
332
"""
333
Ensure labels are sequential starting from 0.
334
"""
335
def __init__(self): ...
336
337
class KeepLargestComponent(LabelTransform):
338
"""
339
Keep only the largest connected component for each label.
340
"""
341
def __init__(self): ...
342
```
343
344
Usage example:
345
346
```python
347
# Label preprocessing for segmentation task
348
label_preprocessing = tio.Compose([
349
tio.RemapLabels({1: 1, 2: 1, 3: 2}), # Merge some labels
350
tio.KeepLargestComponent(), # Remove small components
351
tio.SequentialLabels(), # Ensure sequential labels
352
])
353
354
subject = tio.Subject(
355
image=tio.ScalarImage('image.nii.gz'),
356
segmentation=tio.LabelMap('multi_label_seg.nii.gz')
357
)
358
359
processed = label_preprocessing(subject)
360
```
361
362
### Histogram Standardization Training
363
364
Utility function for training histogram standardization landmarks from a dataset.
365
366
```python { .api }
367
def train_histogram(
368
subjects_dataset: SubjectsDataset,
369
output_path: TypePath,
370
progress: bool = True
371
) -> dict:
372
"""
373
Train histogram standardization landmarks from dataset.
374
375
Parameters:
376
- subjects_dataset: Dataset to train landmarks from
377
- output_path: Path to save landmarks
378
- progress: Whether to show progress bar
379
380
Returns:
381
Dictionary with landmarks for each image type
382
"""
383
```
384
385
Usage example:
386
387
```python
388
# Train histogram standardization landmarks
389
subjects = [...] # List of training subjects
390
training_dataset = tio.SubjectsDataset(subjects)
391
392
landmarks = tio.train_histogram(
393
subjects_dataset=training_dataset,
394
output_path='histogram_landmarks.json'
395
)
396
397
# Use trained landmarks in preprocessing
398
hist_std = tio.HistogramStandardization(landmarks)
399
```