|
1
|
|
|
# pylint: disable=import-outside-toplevel |
|
2
|
|
|
|
|
3
|
|
|
"""Console script for torchio.""" |
|
4
|
|
|
import sys |
|
5
|
|
|
import click |
|
6
|
|
|
|
|
7
|
|
|
|
|
8
|
|
|
@click.command() |
|
9
|
|
|
@click.argument('input-path', type=click.Path(exists=True)) |
|
10
|
|
|
@click.argument('transform-name', type=str) |
|
11
|
|
|
@click.argument('output-path', type=click.Path()) |
|
12
|
|
|
@click.option( |
|
13
|
|
|
'--kwargs', '-k', |
|
14
|
|
|
type=str, |
|
15
|
|
|
help='String of kwargs, e.g. "degrees=(-5,15) num_transforms=3".', |
|
16
|
|
|
) |
|
17
|
|
|
@click.option( |
|
18
|
|
|
'--seed', '-s', |
|
19
|
|
|
type=int, |
|
20
|
|
|
help='Seed for PyTorch random number generator.', |
|
21
|
|
|
) |
|
22
|
|
|
@click.option( |
|
23
|
|
|
'--verbose/--no-verbose', '-v', |
|
24
|
|
|
type=bool, |
|
25
|
|
|
default=False, |
|
26
|
|
|
help='Print random transform parameters.', |
|
27
|
|
|
) |
|
28
|
|
|
def main( |
|
29
|
|
|
input_path, |
|
30
|
|
|
transform_name, |
|
31
|
|
|
output_path, |
|
32
|
|
|
kwargs, |
|
33
|
|
|
seed, |
|
34
|
|
|
verbose, |
|
35
|
|
|
): |
|
36
|
|
|
"""Apply transform to an image. |
|
37
|
|
|
|
|
38
|
|
|
\b |
|
39
|
|
|
Example: |
|
40
|
|
|
$ torchio-transform -k "degrees=(-5,15) num_transforms=3" input.nrrd RandomMotion output.nii |
|
41
|
|
|
""" |
|
42
|
|
|
# Imports are placed here so that the tool loads faster if not being run |
|
43
|
|
|
import torch |
|
44
|
|
|
import torchio.transforms as transforms |
|
45
|
|
|
from torchio.utils import apply_transform_to_file |
|
46
|
|
|
|
|
47
|
|
|
try: |
|
48
|
|
|
transform_class = getattr(transforms, transform_name) |
|
49
|
|
|
except AttributeError as error: |
|
50
|
|
|
message = f'Transform "{transform_name}" not found in torchio' |
|
51
|
|
|
raise ValueError(message) from error |
|
52
|
|
|
|
|
53
|
|
|
params_dict = get_params_dict_from_kwargs(kwargs) |
|
54
|
|
|
transform = transform_class(**params_dict) |
|
55
|
|
|
if seed is not None: |
|
56
|
|
|
torch.manual_seed(seed) |
|
57
|
|
|
apply_transform_to_file( |
|
58
|
|
|
input_path, |
|
59
|
|
|
transform, |
|
60
|
|
|
output_path, |
|
61
|
|
|
verbose=verbose, |
|
62
|
|
|
) |
|
63
|
|
|
return 0 |
|
64
|
|
|
|
|
65
|
|
|
|
|
66
|
|
|
def get_params_dict_from_kwargs(kwargs): |
|
67
|
|
|
from torchio.utils import guess_type |
|
68
|
|
|
params_dict = {} |
|
69
|
|
|
if kwargs is not None: |
|
70
|
|
|
for substring in kwargs.split(): |
|
71
|
|
|
try: |
|
72
|
|
|
key, value_string = substring.split('=') |
|
73
|
|
|
except ValueError as error: |
|
74
|
|
|
message = f'Arguments string "{kwargs}" not valid' |
|
75
|
|
|
raise ValueError(message) from error |
|
76
|
|
|
|
|
77
|
|
|
value = guess_type(value_string) |
|
78
|
|
|
params_dict[key] = value |
|
79
|
|
|
return params_dict |
|
80
|
|
|
|
|
81
|
|
|
|
|
82
|
|
|
if __name__ == '__main__': |
|
83
|
|
|
# pylint: disable=no-value-for-parameter |
|
84
|
|
|
sys.exit(main()) # pragma: no cover |
|
85
|
|
|
|