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 ifimgis a NumPy array.to_sitk (
Optional[bool], default:None) – True to convert a NumPyimgto 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 ifimgis not a NumPy array.
- Return type:
- 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 ifdrawn_labels_onlyis True.drawn_labels_only (
bool) – True to load the atlas in theload_labelsfolder to collect only labels drawn in this atlas; False to use all labels inlabels_ref_lookup.labels_ref_lookup (
Dict) – Labels reverse lookup dictionary of label IDs to labels.
- Return type:
- 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
channelto extract a single channel before generating asitk.Imageobject for many SimpleITK filters that require single-channel (“scalar” rather than “vector”) images.- Parameters:
- 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, ignoringimg_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_sitkis True
If
return_pathis 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 toload_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 withreg_namesvalues 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 intotarget.target (
Union[Image,itkTemplate]) – Target object whose corresponding metadata will be overwritten by that ofsource.spacing (
Union[bool,Tuple[int],List[int]], default:True) – True to copy the spacing fromsourcetotarget, or the spacing to set intarget; defaults to True.origin (
Union[bool,Tuple[int],List[int]], default:True) – True to copy the origin fromsourcetotarget, or the origin to set intarget; defaults to True.direction (
Union[bool,Tuple[int],List[int]], default:True) – True to copy the direction fromsourcetotarget, or the direction to set intarget; 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 inimg_paths.prefix (
Optional[str], default:None) – Start of output path. If None, the first path inimg_pathswill be used instead.suffix (
Optional[str], default:None) – Portion of path to be combined with each path inimg_pathsand output path.fn_combine (
Callable[[Sequence[ndarray]],ndarray], default:<function sum at 0x7fb5f2fd3cf0>) – Function to apply to combine images withaxis=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
Imageformat.- 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
ImageformatChecks for alternative supported extensions if necessary.
- Parameters:
- Returns:
img_sitk: Image object located atpathwith the found extension, or None if unable to load. Type is determined byread_img()path_loaded: the loaded path, or None if no matching, existing path is found. If a file atpathcannot be found, its extension is replaced successively with remaining extensions in :const:EXTS_3Duntil 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.resolutionsif 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 openfilename_sitkas-is throughread_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_3dis False). Associated metadata is loaded into :module:`magmap.settings.config` attributes.If
return_sitkis 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.serieswill be appended unlessfile_pathis a directory.reg_name – Suffix for type of registration, eg :const:
IMG_LABELS.match_ext (default:
False) – True to change the extension ofreg_nameto match that offile_path.
- Returns:
Full path with the registered filename including appropriate extension at the end.
- Return type:
- magmap.io.sitk_io.replace_sitk_with_numpy(img_sitk, img_np, multichannel=None)[source]¶
Generate a :class:
sitk.Imageobject based on another Image object, but replace its array with a new Numpy array.- Parameters:
- Return type:
Union[Image,itkTemplate]- Returns:
New SimpleITK or ITK
sitk.Imageobject with same spacing, origin, and direction as that ofimg_sitkand array replaced byimg_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.
- 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).
- 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}, wheresuffixis a registered images suffix, such as :const:IMAGE_LABELS, andimageis 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 withsuffixas 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 treatprefixas a directory. If False, will use the directory name ofprefix.
- 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 throughload_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. Ifimg_sitkis 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:
FileExistsError – if
overwriteis false and existing file is at the output path.FileNotFoundError – if template image cannot be found.