magmap.io.sitk_io module

Input/Output for SimpleITK/SimpleElastix objects.

Manage import and export of simpleitk.Image objects.

magmap.io.sitk_io.EXTS_3D: Sequence[str] = ('.mhd', '.mha', '.nii.gz', '.nii', '.nhdr', '.nrrd')

Extensions of 3D formats supported through SimpleITK.

magmap.io.sitk_io.convert_img(img, multichannel=None, to_sitk=None)[source]

Convert SimpleITK, ITK, and NumPy images.

Parameters:
  • img (Union[Image, itkTemplate, ndarray]) – SimpleITK Image, ITK Image, or NumPy array. Non-NumPy arrays will be converted to a NumPy array.

  • multichannel (Optional[bool], default: None) – True if the resulting SimpleITK or ITK Image should be multichannel. Defaults to None, which will attempt to auto-detect multichannel images. Only used if img is a NumPy array.

  • to_sitk (Optional[bool], default: None) – True to convert a NumPy img to a SimpleITK Image. If False, an ITK Image is output instead. If None, the parameter will be True if the SimpleITK library is found. Ignored if img is not a NumPy array.

Return type:

Union[Image, itkTemplate, ndarray]

Returns:

The converted image.

magmap.io.sitk_io.find_atlas_labels(labels_ref_path, drawn_labels_only, labels_ref_lookup)[source]

Find atlas label IDs from the labels directory.

Parameters:
  • labels_ref_path (str) – Path to labels reference from which to load labels from the original labels if drawn_labels_only is True.

  • drawn_labels_only (bool) – True to load the atlas in the load_labels folder to collect only labels drawn in this atlas; False to use all labels in labels_ref_lookup.

  • labels_ref_lookup (Dict) – Labels reverse lookup dictionary of label IDs to labels.

Return type:

List[int]

Returns:

List of label IDs.

magmap.io.sitk_io.itk_to_sitk_img(itk_img)[source]

Convert an ITK image to a SimpleITK Image.

Parameters:

itk_img (itkTemplate) – ITK Image. If None, will simply be returned.

Return type:

Image

Returns:

SimpleITK Image.

magmap.io.sitk_io.load_numpy_to_sitk(img5d, rotate=False, channel=None)[source]

Load Numpy image array to SimpleITK Image object.

Use channel to extract a single channel before generating a sitk.Image object for many SimpleITK filters that require single-channel (“scalar” rather than “vector”) images.

Parameters:
  • img5d (Union[str, Image5d]) – Path to Numpy archive file or Image5d instance.

  • rotate (bool, default: False) – True if the image should be rotated 180 deg; defaults to False.

  • channel (Union[int, Sequence[int], None], default: None) – Integer or sequence of integers specifying channels to keep.

Return type:

Image

Returns:

The image in SimpleITK format.

Raises:

FileNotFoundError – if the image is None.

magmap.io.sitk_io.load_registered_img(img_path, reg_name, get_sitk=False, return_path=False)[source]

Load atlas-based image that has been registered to another image.

Parameters:
  • img_path (str) – Path as had been given to generate the registered images, with the parent path of the registered images and base name of the original image.

  • reg_name (str) – Atlas image suffix to open. Can be an absolute path, which will be used directly, ignoring img_path.

  • get_sitk (bool, default: False) – True if the image should be returned as a SimpleITK image; defaults to False, in which case the corresponding Numpy array will be extracted instead.

  • return_path (bool, default: False) – True to return the path from which the image was loaded; defaults to False.

Returns:

the registered image as a Numpy array, or SimpleITK

Image if get_sitk is True

  • If return_path is True: the loaded path

Return type:

  • reg_img

Raises:

FileNotFoundError` if the path cannot be found

magmap.io.sitk_io.load_registered_imgs(img_path, reg_names, *args, **kwargs)[source]

Load atlas-based images registered to another image.

Parameters:
  • img_path (str) – Base image path passed to load_registered_img().

  • reg_names (Sequence[str]) – Atlas image suffixes, passed to above function.

  • args – Arguments passed to above function.

  • kwargs – Arguments passed to above function.

Return type:

Dict[str, Union[ndarray, Image, Tuple[Union[ndarray, Image], str]]]

Returns:

A dictionary of load_registered_img() output with reg_names values as keys and any unloaded file ignored.

magmap.io.sitk_io.match_world_info(source, target, spacing=True, origin=True, direction=True)[source]

Transfer world information from one image object to another.

Supported world information is spacing, origin, direction. Matching this information is sometimes necessary for slight differences in metadata perhaps from founding that may prevent ITK filters from executing.

Parameters:
  • source (Union[Image, itkTemplate]) – Source object whose relevant metadata will be copied into target.

  • target (Union[Image, itkTemplate]) – Target object whose corresponding metadata will be overwritten by that of source.

  • spacing (Union[bool, Tuple[int], List[int]], default: True) – True to copy the spacing from source to target, or the spacing to set in target; defaults to True.

  • origin (Union[bool, Tuple[int], List[int]], default: True) – True to copy the origin from source to target, or the origin to set in target; defaults to True.

  • direction (Union[bool, Tuple[int], List[int]], default: True) – True to copy the direction from source to target, or the direction to set in target; defaults to True.

magmap.io.sitk_io.merge_images(img_paths, reg_name, prefix=None, suffix=None, fn_combine=<function sum>)[source]

Merge images from multiple paths.

Assumes that the images are relatively similar in size, but will resize them to the size of the first image to combine the images.

Parameters:
  • img_paths (Sequence[str]) – Paths from which registered paths will be found.

  • reg_name (str) – Registration suffix to load for the given paths in img_paths.

  • prefix (Optional[str], default: None) – Start of output path. If None, the first path in img_paths will be used instead.

  • suffix (Optional[str], default: None) – Portion of path to be combined with each path in img_paths and output path.

  • fn_combine (Callable[[Sequence[ndarray]], ndarray], default: <function sum at 0x7fb5f2fd3cf0>) – Function to apply to combine images with axis=0. If None, each image will be inserted as a separate channel.

Return type:

Image

Returns:

The combined image in SimpleITK format.

magmap.io.sitk_io.read_img(path)[source]

Read an image file into SimpleITK or ITK Image format.

Parameters:

path – Path, including prioritized extension to check first.

Return type:

Union[Image, itkTemplate]

Returns:

Image object located at path. Loads into SimpleITK format if the library is available, otherwise into ITK format.

magmap.io.sitk_io.read_sitk(path, dryrun=False)[source]

Read an image file into SimpleITK or ITK Image format

Checks for alternative supported extensions if necessary.

Parameters:
  • path (str) – Path, including prioritized extension to check first.

  • dryrun (bool, default: False) – True to find an existing path if available, without loading the image; defaults to False.

Returns:

  • img_sitk: Image object located at path with the found extension, or None if unable to load. Type is determined by read_img()

  • path_loaded: the loaded path, or None if no matching, existing path is found. If a file at path cannot be found, its extension is replaced successively with remaining extensions in :const:EXTS_3D until a file is found.

Return type:

Tuple of

magmap.io.sitk_io.read_sitk_files(filename_sitk, reg_names=None, return_sitk=False, make_3d=False)[source]

Read image files through SimpleITK.

Supports identifying files based on registered suffixes and combining multiple registered image files into a single image.

Also sets up spacing from the first loaded image in magmap.settings.config.resolutions if not already set.

Parameters:
  • filename_sitk (str) – Path to file in a format that can be read by SimpleITK.

  • reg_names (Union[str, Sequence[str], None], default: None) – Path or sequence of paths of registered names. Can be a registered suffix or a full path. Defaults to None to open filename_sitk as-is through read_sitk().

  • return_sitk (bool, default: False) – True to return the loaded SimpleITK Image object.

  • make_3d (bool, default: False) – True to convert 2D images to 3D; defaults to False.

Returns:

Image5d instance with the loaded image in Numpy 5D format (or 4D if not multi-channel, and 3D if originally 2D and make_3d is False). Associated metadata is loaded into :module:`magmap.settings.config` attributes.

If return_sitk is True, also returns the first loaded image in SimpleITK format.

Return type:

img5d

Raises:
  • FileNotFoundError` if filename_sitk cannot be found, afte

  • attempting to load metadata from filename_np.

magmap.io.sitk_io.reg_out_path(file_path, reg_name, match_ext=False)[source]

Generate a path for a file registered to another file.

Parameters:
  • file_path – Full path of file registered to. config.series will be appended unless file_path is a directory.

  • reg_name – Suffix for type of registration, eg :const:IMG_LABELS.

  • match_ext (default: False) – True to change the extension of reg_name to match that of file_path.

Returns:

Full path with the registered filename including appropriate extension at the end.

Return type:

str

magmap.io.sitk_io.replace_sitk_with_numpy(img_sitk, img_np, multichannel=None)[source]

Generate a :class:sitk.Image object based on another Image object, but replace its array with a new Numpy array.

Parameters:
  • img_sitk (Union[Image, itkTemplate]) – Image object to use as template.

  • img_np (ndarray) – Numpy array to swap in.

  • multichannel (Optional[bool], default: None) – True for multichannel images. Defaults to None, where the multichannel setting from img_sitk will be used.

Return type:

Union[Image, itkTemplate]

Returns:

New SimpleITK or ITK sitk.Image object with same spacing, origin, and direction as that of img_sitk and array replaced by img_np.

magmap.io.sitk_io.sitk_to_itk_img(sitk_img)[source]

Convert a SimpleITK image to an ITK Image.

Parameters:

sitk_img (Image) – SimpleITK Image. If None, will simply be returned.

Return type:

itkTemplate

Returns:

ITK Image.

magmap.io.sitk_io.write_img(img, path, compression=False, **kwargs)[source]

Write SimpleITK/ITK images.

Parameters:
  • img (Union[Image, itkTemplate]) – Image as SimpleITK or ITK type.

  • path (str) – Path to save the image.

  • compression (bool, default: False) – True to use compression.

  • kwargs – Additional arguments to underlying sitk.WriteImage() or itk.imwrite().

magmap.io.sitk_io.write_pts(path, pts, pt_type='index')[source]

Write file for corresponding points in Elastix.

See format described in the Elastix manual, section 4.2 (as of Elastix 5.0.1).

Parameters:
  • path (str) – Output path.

  • pts (Sequence[Sequence[int]]) – Points as a nested sequence of ints, in x, y, [z] order.

  • pt_type (str, default: 'index') – Point type, either “index” (default) for points as image indices, or “points” as physical coordinates.

magmap.io.sitk_io.write_reg_images(imgs_write, prefix, copy_to_suffix=False, ext=None, prefix_is_dir=False)[source]

Write registered images to file.

Parameters:
  • imgs_write (Dict[str, Union[Image, itkTemplate]]) – Dictionary of {suffix: image}, where suffix is a registered images suffix, such as :const:IMAGE_LABELS, and image is a SimpleITK or ITK image object. If the image does not exist, the file will not be written.

  • prefix (str) – Base path from which to construct registered file paths. Parent directories will be created if necessary.

  • copy_to_suffix (bool, default: False) – If True, copy the output path to a file in the same directory with suffix as the filename, which may be useful when setting the registered images as the main images in the directory.

  • ext (Optional[str], default: None) – Replace extension with this value if given; defaults to None.

  • prefix_is_dir (bool, default: False) – True to treat prefix as a directory. If False, will use the directory name of prefix.

magmap.io.sitk_io.write_registered_image(img_np, img_path, reg_name, img_sitk=None, load_reg_names=None, overwrite=False)[source]

Write a Numpy array as a registered 3D image file through SimpleITK.

To find metadata for the output image, another SimpleITK image must be given or discovered as a registered image.

Parameters:
  • img_np (ndarray) – Image array to write.

  • img_path (str) – Base path from which to construct output path.

  • reg_name (str) – Registered image suffix, which will also specify the output file format.

  • img_sitk (Optional[Image], default: None) – SimpleITK Image object to use as a template for image metadata; defaults to None, in which case a registered image will be loaded through load_reg_names.

  • load_reg_names (Optional[Sequence[str]], default: None) – Sequence of registered image suffixes from which to load a template image for metdata. Names are checked until the first image loads successfully. Defaults to None to use the atlas volume followed by the experimental image. If img_sitk is None and no registered image can be found, writing will be aborted.

  • overwrite (bool, default: False) – True to overwrite any existing image at the output path; defaults to False.

Return type:

Image

Returns:

The saved image as a SimpleITK Image object.

Raises: