Conditions | 7 |
Total Lines | 59 |
Code Lines | 49 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | import ast |
||
52 | def create_dummy_dataset( |
||
53 | num_images: int, |
||
54 | size_range: Tuple[int, int], |
||
55 | directory: Optional[TypePath] = None, |
||
56 | suffix: str = '.nii.gz', |
||
57 | force: bool = False, |
||
58 | verbose: bool = False, |
||
59 | ): |
||
60 | from .data import ScalarImage, LabelMap, Subject |
||
61 | output_dir = tempfile.gettempdir() if directory is None else directory |
||
62 | output_dir = Path(output_dir) |
||
63 | images_dir = output_dir / 'dummy_images' |
||
64 | labels_dir = output_dir / 'dummy_labels' |
||
65 | |||
66 | if force: |
||
67 | shutil.rmtree(images_dir) |
||
68 | shutil.rmtree(labels_dir) |
||
69 | |||
70 | subjects: List[Subject] = [] |
||
71 | if images_dir.is_dir(): |
||
72 | for i in trange(num_images): |
||
73 | image_path = images_dir / f'image_{i}{suffix}' |
||
74 | label_path = labels_dir / f'label_{i}{suffix}' |
||
75 | subject = Subject( |
||
76 | one_modality=ScalarImage(image_path), |
||
77 | segmentation=LabelMap(label_path), |
||
78 | ) |
||
79 | subjects.append(subject) |
||
80 | else: |
||
81 | images_dir.mkdir(exist_ok=True, parents=True) |
||
82 | labels_dir.mkdir(exist_ok=True, parents=True) |
||
83 | if verbose: |
||
84 | print('Creating dummy dataset...') # noqa: T001 |
||
85 | iterable = trange(num_images) |
||
86 | else: |
||
87 | iterable = range(num_images) |
||
88 | for i in iterable: |
||
89 | shape = np.random.randint(*size_range, size=3) |
||
90 | affine = np.eye(4) |
||
91 | image = np.random.rand(*shape) |
||
92 | label = np.ones_like(image) |
||
93 | label[image < 0.33] = 0 |
||
94 | label[image > 0.66] = 2 |
||
95 | image *= 255 |
||
96 | |||
97 | image_path = images_dir / f'image_{i}{suffix}' |
||
98 | nii = nib.Nifti1Image(image.astype(np.uint8), affine) |
||
99 | nii.to_filename(str(image_path)) |
||
100 | |||
101 | label_path = labels_dir / f'label_{i}{suffix}' |
||
102 | nii = nib.Nifti1Image(label.astype(np.uint8), affine) |
||
103 | nii.to_filename(str(label_path)) |
||
104 | |||
105 | subject = Subject( |
||
106 | one_modality=ScalarImage(image_path), |
||
107 | segmentation=LabelMap(label_path), |
||
108 | ) |
||
109 | subjects.append(subject) |
||
110 | return subjects |
||
111 | |||
218 |