Create a temporary nifti image on the disk and return the image name. User is responsible for deleting the temporary file when done with it.
(
array: NdarrayOrTensor, affine=None, dir=None, fname=None, suffix=".nii.gz", verbose=False, dtype=float
)
| 385 | |
| 386 | |
| 387 | def make_nifti_image( |
| 388 | array: NdarrayOrTensor, affine=None, dir=None, fname=None, suffix=".nii.gz", verbose=False, dtype=float |
| 389 | ): |
| 390 | """ |
| 391 | Create a temporary nifti image on the disk and return the image name. |
| 392 | User is responsible for deleting the temporary file when done with it. |
| 393 | """ |
| 394 | if isinstance(array, torch.Tensor): |
| 395 | array, *_ = convert_data_type(array, np.ndarray) |
| 396 | if isinstance(affine, torch.Tensor): |
| 397 | affine, *_ = convert_data_type(affine, np.ndarray) |
| 398 | if affine is None: |
| 399 | affine = np.eye(4) |
| 400 | test_image = nib.Nifti1Image(array.astype(dtype), affine) # type: ignore |
| 401 | |
| 402 | # if dir not given, create random. Else, make sure it exists. |
| 403 | if dir is None: |
| 404 | dir = tempfile.mkdtemp() |
| 405 | else: |
| 406 | os.makedirs(dir, exist_ok=True) |
| 407 | |
| 408 | # If fname not given, get random one. Else, concat dir, fname and suffix. |
| 409 | if fname is None: |
| 410 | temp_f, fname = tempfile.mkstemp(suffix=suffix, dir=dir) |
| 411 | os.close(temp_f) |
| 412 | else: |
| 413 | fname = os.path.join(dir, fname + suffix) |
| 414 | |
| 415 | nib.save(test_image, fname) |
| 416 | if verbose: |
| 417 | print(f"File written: {fname}.") |
| 418 | return fname |
| 419 | |
| 420 | |
| 421 | def make_rand_affine(ndim: int = 3, random_state: np.random.RandomState | None = None): |
no test coverage detected
searching dependent graphs…