| 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 |
||
| 60 | def create_dummy_dataset( |
||
| 61 | num_images: int, |
||
| 62 | size_range: Tuple[int, int], |
||
| 63 | directory: Optional[TypePath] = None, |
||
| 64 | suffix: str = '.nii.gz', |
||
| 65 | force: bool = False, |
||
| 66 | verbose: bool = False, |
||
| 67 | ): |
||
| 68 | from .data import Image, Subject |
||
| 69 | output_dir = tempfile.gettempdir() if directory is None else directory |
||
| 70 | output_dir = Path(output_dir) |
||
| 71 | images_dir = output_dir / 'dummy_images' |
||
| 72 | labels_dir = output_dir / 'dummy_labels' |
||
| 73 | |||
| 74 | if force: |
||
| 75 | shutil.rmtree(images_dir) |
||
| 76 | shutil.rmtree(labels_dir) |
||
| 77 | |||
| 78 | subjects: List[Subject] = [] |
||
| 79 | if images_dir.is_dir(): |
||
| 80 | for i in trange(num_images): |
||
| 81 | image_path = images_dir / f'image_{i}{suffix}' |
||
| 82 | label_path = labels_dir / f'label_{i}{suffix}' |
||
| 83 | subject = Subject( |
||
| 84 | one_modality=Image(image_path, INTENSITY), |
||
| 85 | segmentation=Image(label_path, LABEL), |
||
| 86 | ) |
||
| 87 | subjects.append(subject) |
||
| 88 | else: |
||
| 89 | images_dir.mkdir(exist_ok=True, parents=True) |
||
| 90 | labels_dir.mkdir(exist_ok=True, parents=True) |
||
| 91 | if verbose: |
||
| 92 | print('Creating dummy dataset...') |
||
| 93 | iterable = trange(num_images) |
||
| 94 | else: |
||
| 95 | iterable = range(num_images) |
||
| 96 | for i in iterable: |
||
| 97 | shape = np.random.randint(*size_range, size=3) |
||
| 98 | affine = np.eye(4) |
||
| 99 | image = np.random.rand(*shape) |
||
| 100 | label = np.ones_like(image) |
||
| 101 | label[image < 0.33] = 0 |
||
| 102 | label[image > 0.66] = 2 |
||
| 103 | image *= 255 |
||
| 104 | |||
| 105 | image_path = images_dir / f'image_{i}{suffix}' |
||
| 106 | nii = nib.Nifti1Image(image.astype(np.uint8), affine) |
||
| 107 | nii.to_filename(str(image_path)) |
||
| 108 | |||
| 109 | label_path = labels_dir / f'label_{i}{suffix}' |
||
| 110 | nii = nib.Nifti1Image(label.astype(np.uint8), affine) |
||
| 111 | nii.to_filename(str(label_path)) |
||
| 112 | |||
| 113 | subject = Subject( |
||
| 114 | one_modality=Image(image_path, INTENSITY), |
||
| 115 | segmentation=Image(label_path, LABEL), |
||
| 116 | ) |
||
| 117 | subjects.append(subject) |
||
| 118 | return subjects |
||
| 119 | |||
| 213 |