MCPcopy Create free account
hub / github.com/Project-MONAI/MONAI / make_nifti_image

Function make_nifti_image

tests/test_utils.py:387–418  ·  view source on GitHub ↗

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
)

Source from the content-addressed store, hash-verified

385
386
387def 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
421def make_rand_affine(ndim: int = 3, random_state: np.random.RandomState | None = None):

Callers 11

setUpMethod · 0.90
test_make_niftiMethod · 0.90
test_orientationMethod · 0.90
test_consistencyMethod · 0.90
setUpMethod · 0.90
setUpMethod · 0.90
setUpMethod · 0.90
test_invertMethod · 0.90
test_invertMethod · 0.90
setUpClassMethod · 0.90

Calls 4

convert_data_typeFunction · 0.90
astypeMethod · 0.80
saveMethod · 0.80
closeMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…