magmap.atlas.register module¶
Register images to one another.
The registration type can be given on the command-line (see :mod:cli) as
outlined here. Each type can be coupled with additional arguments in cli.
single: Register a single image to a reference atlas. Filenamesshould be given in :attr:
config.filenames, where the first filename is the fixed image (eg the experiment), and the second image is the moving image (eg the atlas). The atlas rather than the experimental image is typically moved here since the experimental image is usually much larger and more difficult to move. For faster registration, a downsampled image can be given as this experiment image, and the third argument tofilenamescan optionally be given as a name prefix corresponding to the original experiment file.flipcan also be given to flip the
group: Register multiple experimental images to one another viagroupwise registration. All the images given in :attr:
config.filenameswill be registered to one another, except the last filename, which will be used as the output name prefix.
overlays: Overlay the moving image on top of the fixed image tovisualize alignment.
flipcan be given to flip the moving image.
volumes: Calculate volumes for each region in the experimentalimage based on the corresponding registered labels image.
labelsshould be given to specify the labels file and level.rescaleis used to find the rescaled, typically downsampled images to use as a much faster way to calculate volumes.no_showsuppresses graph display.
densities: Similar tovolumesbut include nuclei densities per region by loading the processed stack file.
export_vols: Export regional volumes and related measures to CSV file.
export_regions: Export atlas annotation region information such as region ID to name CSV file and region network SIF file.
new_atlas: Based on “single” registration, outputting registered files in the naming format of a new atlas and bypassing label truncation.
- class magmap.atlas.register.RegImgs(exp_orig=None, exp=None, atlas=None, labels=None, labels_markers=None, borders=None, exp_mask=None, atlas_mask=None)[source]¶
Bases:
objectData class for tracking registered images.
- magmap.atlas.register.curate_img(fixed_img, labels_img, imgs=None, inpaint=True, carve=True, thresh=None, holes_area=None)[source]¶
Curate an image by the foreground of another.
In-painting where corresponding pixels are present in fixed image but not labels or other images and removing pixels present in those images but not the fixed image.
- Parameters:
fixed_img (
Image) – Image in SimpleITK format by which to curate other images.labels_img (
Image) – Labels image in SimpleITK format, used to determine missing pixels and measure overlap.imgs (
Optional[List[Image]], default:None) – Array of additional images to curate corresponding pixels as those curated inlabels_img. Defaults to None.inpaint (
bool, default:True) – True to in-paint; defaults to True.carve (
bool, default:True) – True to carve based onfixed_img; defaults to True. Ifinpaintis True,carveshould typically be True as well.thresh (
Optional[float], default:None) – Threshold to use for carving; defaults to None to determine by taking the mean threshold offixed_img.holes_area (
Optional[int], default:None) – Maximum area of holes to fill when carving.
- Return type:
List[Image]- Returns:
A list of images in SimpleITK format that have been curated, starting with the curated
labels_img, followed by the images inimgs.
- magmap.atlas.register.get_scaled_regionprops(img_region, scaling)[source]¶
Get the scaled regionprops for an image mask
- Parameters:
img_region – Mask of the region.
scaling – Scaling factor for the labels image size compared with the experiment image.
- Returns:
A tuple of
props, bbox, centroid.propsis theregionpropsproperties for the given region.bboxis the bounding box of this region scaled back to the experiment image.centroidis the centroid position also scaled to the experiment. Note that the bounding box may encompass many pixels not included in the region itself, including border pixels or even internal pixels in irregularly shaped or sparsely scattered regions. If so, the centroid position may in fact be outside of the region. To ensure that a coordinate within the region tree forlabel_idis returned, use :func:ontology.get_region_middleinstead.
- magmap.atlas.register.main()[source]¶
Handle registration processing tasks
Tasks are specified in
magmap.config.register_type.
- magmap.atlas.register.make_label_ids_set(labels_ref_path, labels_ref_lookup, max_level, combine_sides, label_ids=None)[source]¶
Make a set of label IDs for the given level and sides.
- Parameters:
labels_ref_path (
str) – Path to labels reference from which to load original labels ifmax_levelis None. Can be None iflabels_idis given.labels_ref_lookup (
Dict[int,Any]) – The labels reference lookup, assumed to be an OrderedDict generated byontology.create_reverse_lookup()to look up by ID while preserving key order to ensure that parents of any child will be reached prior to the child.max_level (
int) – Integer of maximum ontological level to measure. Giving this value changes the measurement to volumes by ontology, where all children of each label are included in the label rather than taking the label at face value, the default drawn label. Labels at levels up to and including this value will be included. Defaults to None to take labels at face value only.combine_sides (
bool) – True to combine corresponding labels from opposite sides of the sample; defaults to True. Corresponding positive and negative numbers will always be included, and this flag will only determine whether the sides are combined rather than kept separate.label_ids (
Optional[Sequence[int]], default:None) – Sequence of IDs; defaults to None to get usinglabels_ref_path.
- Return type:
- Returns:
List of label IDs.
- magmap.atlas.register.overlay_registered_imgs(fixed_file, moving_file_dir, plane=None, rotate=None, name_prefix=None, out_plane=None)[source]¶
Shows overlays of previously saved registered images.
Should be run after
register()has written out images in default (xy) orthogonal orientation. Also output the Dice similiarity coefficient.- Parameters:
fixed_file – Path to the fixed file.
moving_file_dir – Moving files directory, from which the original atlas will be retrieved.
plane (default:
None) – Orthogonal plane to flip the moving image.rotate (int) – Number of 90 degree rotations; defaults to None.
name_prefix (default:
None) – Path with base name where registered files are located; defaults to None, in which case the fixed_file path will be used.out_plane (default:
None) – Output plane to view.
- magmap.atlas.register.register(fixed_file, moving_img_path, show_imgs=True, write_imgs=True, name_prefix=None, new_atlas=False, transformix=None)[source]¶
Register an atlas to a sample image using the Elastix library.
Loads the images, applies any transformations to the moving image, and registers the moving to the sample images. Applies the identical registration to the associated atlas labels image as well. The specific moving images can be adjusted through
magmap.settings.config.reg_suffixes, where the “atlas” image is the intensity image used for registration, “annotation” is the atlas labels, “fixed_mask” is the mask forfixed_file(optional), and “moving_mask” is the mask for the “atlas” image (optional). If either mask is given, both should be given as required by Elastix. Multiple “annotation” images can be given, which will each be transformed identially to the “atlas” image.Uses the first channel in
config.channel, or the first image channel if this value is None.- Fallbacks:
If the registration does not complete, the moving image origin and direction will be changed to that of the fixed image
If no reg, the spacing will also be matched
If still no reg, the atlas will be output as-is
If the atlas profile
fallbackparameter sets a DSC threshold and alternate registration settings, the image will be re-registered under these new settings if below the threshold
- Parameters:
fixed_file – The image to register, given as a Numpy archive file to be read by :importer:`read_file`.
moving_img_path (str) – Moving image base path from which an intensity and a labels image will be loaded using registered image suffixes. Falls back to atlas volume for the intensity image and annotation for the labels image. The intensity image will be used for registration. The atlas is currently used as the moving file since it is likely to be lower resolution than the Numpy file.
show_imgs (default:
True) – True if the output images should be displayed; defaults to True.write_imgs (default:
True) – True if the images should be written to file; defaults to False.name_prefix (default:
None) – Path with base name where registered files will be output; defaults to None, in which case the fixed_file path will be used.new_atlas (default:
False) – True to generate registered images that will serve as a new atlas; defaults to False.transformix (default:
None) – Elastix transformation filter from prior run; defaults to None.
- Returns:
The Elastix transformation filter generated by the registration.
- magmap.atlas.register.register_duo(fixed_img, moving_img, path=None, fixed_mask=None, moving_mask=None, regs=None)[source]¶
Register two images to one another using
Elastix.Supports Elastix provided by SimpleITK or ITK. If SimpleITK images are given with Elastix enabled in SimpleITK, registration will be performed in SimpleITK. If Elastix is not enabled, however, the images will be converted to ITK, and registration will use ITK-Elastix. If ITK images are given, ITK-Elastix is assumed to be present; no conversion will take place to SimpleITK.
- Parameters:
fixed_img – The image to be registered to.
moving_img – The image to register to
fixed_img.path (default:
None) – Path as string from whose parent directory the points-based registration filesfix_pts.txtandmov_pts.txtwill be found. If None, points-based reg will be ignored even if set.fixed_mask (default:
None) – Mask forfixed_img, typically a uint8 image.moving_mask (default:
None) – Mask formoving_img, typically a uint8 image.regs (default:
None) – Sequence of atlas profile registration keys or registration parameter objects. The default of None gives all three major registration types, “reg_translation”, “reg_affine”, “reg_bspline”.
- Returns:
Tuple of the registered image and a Transformix filter with the registration’s parameters to reapply them on other images.
- magmap.atlas.register.register_group(img_files, rotate=None, show_imgs=True, write_imgs=True, name_prefix=None, scale=None)[source]¶
Group registers several images to one another.
Uses the first channel in
config.channelor the first channel in each image.Registration parameters are assumed to be in a “b-spline”
magmap.settings.atlas_prof.RegParamMap.Performs registration using SimpleITK if the package is present, otherwise using ITK-Elastix.
- Parameters:
img_files (
Sequence[str]) – Paths to image files to register. A minimum of 4 images is required for groupwise registration.rotate (
Optional[Sequence[int]], default:None) – List of number of 90 degree rotations for images corresponding toimg_files; defaults to None, in which case the config.transform rotate attribute will be used.show_imgs (
bool, default:True) – True if the output images should be displayed.write_imgs (
bool, default:True) – True if the images should be written to file.name_prefix (
Optional[str], default:None) – Path with base name where registered files will be output; defaults to None, in which case the fixed_file path will be used.scale (
Optional[float], default:None) – Rescaling factor as a scalar value, used to find the rescaled, smaller images corresponding toimg_files.
- magmap.atlas.register.register_repeat(transformix_img_filter, img, preserve_idents=False)[source]¶
Transform labels to match a prior registration.
Uses an Elastix Transformix filter to reproduce a transformation on a labels image. This filter can be from SimpleITK or ITK. Ensures that the output pixel type remains the same as the input.
- Parameters:
transformix_img_filter – Filter generated from a prior registration.
img – SimpleITK or ITK image.
preserve_idents (default:
False) – True to ensure that identities inimgare preserved. Typically used for label images. Defaults to False.
- Returns:
Transformed image.
- magmap.atlas.register.register_rev(fixed_path, moving_path, reg_base=None, reg_names=None, plane=None, prefix=None, suffix=None, show=True)[source]¶
Reverse registration from
register(), registering a sample image (moving image) to an atlas image (fixed image).Useful for registering a sample image and associated registered atlas images to another image. For example, registered images can be registered back to the atlas.
This method can also be used to move unregistered original images that have simply been copied as
config.RegNames.IMG_EXP.valueduring registration. This copy can be registered “back” to the atlas, reversing the fixed/moving images in :meth:registerto move all experimental images into the same space.- Parameters:
fixed_path – Path to he image to be registered to in :class``SimpleITK.Image`` format.
moving_path – Path to the image in :class``SimpleITK.Image`` format to register to the image at
fixed_path.reg_base (default:
None) – Registration suffix to combine withmoving_path. Defaults to None to usemoving_pathas-is, with output name based on :const:config.RegNames.IMG_EXP.value.reg_names (default:
None) – List of additional registration suffixes associated withmoving_pathto be registered using the same transformation. Defaults to None.plane (default:
None) – Planar orientation to which the atlas will be transposed, considering the atlas’ original plane as “xy”. Defaults to None to avoid planar transposition.prefix (default:
None) – Base path to use for output; defaults to None to usemoving_pathinstead.suffix (default:
None) – String to combine withmoving_pathto load images; defaults to None.show (default:
True) – True to show images after registration; defaults to True.
- magmap.atlas.register.volumes_by_id(img_paths, labels_ref_path=None, suffix=None, unit_factor=None, groups=None, max_level=None, combine_sides=True, extra_metrics=None)[source]¶
Get volumes and additional label metrics for each single labels ID.
Atlas (intensity) and annotation (labels) images can be configured in
magmap.settings.config.reg_suffixes.magmap.settings.config.plot_labelscan be used to configure the condition field with themagmap.settings.config.PlotLabels.CONDITIONkey.- Parameters:
labels_ref_path (str) – Labels reference path(s).
suffix (
Optional[str], default:None) – Modifier to append to end ofimg_pathbasename for registered image files that were output to a modified name; defaults to None to use “original” as the condition.unit_factor (
Optional[str], default:None) – Factor by which volumes will be divided to adjust units; defaults to None.groups (
Optional[Dict], default:None) – Dictionary of sample grouping metadata, where each entry is a list with a values corresponding toimg_paths.max_level (
Optional[int], default:None) – Integer of maximum ontological level to measure. Defaults to None to take labels at face value only.combine_sides (default:
True) – True to combine corresponding labels from opposite sides of the sample; defaults to True.extra_metrics (List[Enum]) – List of enums from
config.MetricGroupsspecifying additional stats; defaults to None.
- Returns:
Tuple of Pandas data frames with volume-related metrics for each sample, the first with all each region for each sample in a separate row, and the second with all regions combined in a weighted fashion. This second data frame will be None if
max_levelsis not None since subregions are already included in each label.
- magmap.atlas.register.volumes_by_id_compare(img_paths, labels_ref_paths, unit_factor=None, groups=None, max_level=None, combine_sides=True, offset=None, roi_size=None)[source]¶
Compare label volumes metrics between different sets of atlases.
Label identities can be translated using CSV files specified in the
config.atlas_labels[config.AtlasLabels.TRANSLATE_LABELSvalue to compare labels from different atlases or groups of labels that do not fit exclusively into a single super-structure. Each file will be mapped to the corresponding paths in theimg_pathsandlabels_ref_pathssequences. Theconfig.atlas_labels[config.AtlasLabels.TRANSLATE_CHILDRENallows specifying whether to include the children of each label. Labels default to use the last value in each of these sequences.- Parameters:
img_paths (Sequence[str]) – Paths from which registered labels images will be loaded to compare.
labels_ref_paths (Union[str, Sequence[str]) – Labels reference path(s). If multiple paths are provided, the corresponding reference to the labels translation paths will be used for translation, and the last reference will be used to find labels. If fewer references than translation paths are provided, the last reference will be used for the remaining translation paths.
unit_factor (default:
None) – Factor by which volumes will be divided to adjust units; defaults to None.groups (default:
None) – Dictionary of sample grouping metadata, where each entry is a list with a values corresponding toimg_paths.max_level (default:
None) – Integer of maximum ontological level to measure. Defaults to None to take labels at face value only.combine_sides (default:
True) – True to combine corresponding labels from opposite sides of the sample; defaults to True.offset (List[int]) – ROI offset in
x,y,z; defaults to None to use the whole image.roi_size (List[int]) – ROI shape in
x,y,z; defaults to None to use the whole image.
- Returns:
Pandas data frame with volume-related metrics.
- Return type:
pd.DataFrame