magmap.cv.segmenter module#
Segment regions based on blobs, labels, and underlying features.
- class magmap.cv.segmenter.LabelToMarkerErosion[source]#
Bases:
SharedArrsContainerConvert a label to an eroded marker for multiprocessing
Uses class methods as an encapsulated way to use in forked multiprocessing without requirement for global variables. In non-forked multiprocessing (eg “spawn” on Windows), regions and weights should be pickled directly.
- Variables:
labels_img – Integer labels images as a Numpy array.
wt_dists – Array of distances by which to weight the filter size.
- classmethod erode_label(label_id, filter_size, target_frac=None, min_filter_size=1, use_min_filter=False, skel_eros_filt_size=False, wt=None)[source]#
Convert a label to a marker as an eroded version of the label.
By default, labels will be eroded with the given
filter_sizeas long as their final size is > 20% of the original volume. If the eroded volume is below threshold,filter_sizewill be progressively decreased until the filter cannot be reduced further.Skeletonization of the labels recovers some details by partially preserving the original labels’ extent, including thin regions that would be eroded away, thus serving a similar function as that of adaptive morphological filtering.
skel_eros_filt_sizeallows titrating the amount of the labels` extent to be preserved.If
wt_distsis present, the label’s distance will be used to weight the starting filter size.- Parameters:
label_id (
int) – ID of label to erode.filter_size (
int) – Size of structing element to start erosion.target_frac (
Optional[float], default:None) – Target fraction of original label to erode. Erosion will start withfilter_sizeand use progressively smaller filters until remaining above this target. Defaults to None to use a fraction of 0.2. Titrates the relative amount of erosion allowed.min_filter_size (
int, default:1) – Minimum filter size, below which the original, uneroded label will be used instead. Defaults to 1. Use 0 to erode at size 1 even if belowtarget_frac. Titrates the absolute amount of erosion allowed.use_min_filter (
bool, default:False) – True to erode atmin_filter_sizeif a smaller filter size would otherwise be required; defaults to False to revert to original, uneroded size if a filter smaller thanmin_filter_sizewould be needed.skel_eros_filt_size (
Union[int,bool], default:False) – Erosion filter size before skeletonization to balance how much of the labels’ extent will be preserved during skeletonization. Increase to reduce the skeletonization. Defaults to False, which will cause skeletonization to be skipped.wt (
Optional[float], default:None) – Multiplier weight forfilter_size. Defaults to None, in which case the weighte will be calculated from :attr:wt_distsif available, or ignored if not.
- Return type:
Tuple[Tuple[int,ndarray,ndarray,Any],Union[List[slice],None,Any],Any]- Returns:
Tuple of stats,including
label_idfor reference and sizes of labels; list of slices denoting where to insert the eroded label; and the eroded label itself.- Raises:
ValueError – if
regionis None andlabels_imgis not available.
- classmethod meas_wt(labels_img, label_id, wt_dists)[source]#
Measure the weight for a label based on weighted distances.
- class magmap.cv.segmenter.SubSegmenter[source]#
Bases:
objectSub-segment a label based on anatomical boundaries.
All images should be of the same shape.
- Variables:
labels_img_np – Integer labels image as a Numpy array.
atlas_edge – Numpy array of atlas reduced to binary image of its edges.
- atlas_edge = None#
- labels_img_np = None#
- classmethod sub_segment(label_id, dtype)[source]#
Calculate metrics for a given label or set of labels.
Wrapper to call :func:
measure_variationand :func:measure_edge_dist.- Parameters:
label_id – Integer of the label in :attr:
labels_img_npto sub-divide.- Returns:
Tuple of the given label ID, list of slices where the label resides in :attr:
labels_img_np, and an array in the same shape of the original label, now sub-segmented. The base value of this sub-segmented array is multiplied by :const:config.SUB_SEG_MULT, with each sub-region incremented by 1.
- magmap.cv.segmenter.labels_to_markers_blob(labels_img)[source]#
Convert a labels image to markers as blobs.
These markers can be used in segmentation algorithms such as watershed.
- Parameters:
labels_img – Labels image as an integer Numpy array, where each unique int is a separate label.
- Returns:
Image array of the same shape as
imgand the same number of labels as inlabels_img, with labels reduced to smaller markers.
- magmap.cv.segmenter.labels_to_markers_erosion(labels_img, filter_size=8, target_frac=None, min_filter_size=None, use_min_filter=False, skel_eros_filt_size=None, wt_dists=None, multiprocess=True)[source]#
Convert a labels image to markers as eroded labels via multiprocessing.
These markers can be used in segmentation algorithms such as watershed.
- Parameters:
labels_img (
ndarray) – Labels image as an integer Numpy array, where each unique int is a separate label.filter_size (
int, default:8) – Size of structing element for erosion, which should be > 0; defaults to 8.target_frac (
Optional[float], default:None) – Target fraction of original label to erode, passed toLabelToMarkerErosion.erode_label(). Defaults to None.min_filter_size (
Optional[int], default:None) – Minimum erosion filter size; defaults to None to use half offilter_size, rounded down.use_min_filter (
bool, default:False) – True to erode even ifmin_filter_sizeis reached; defaults to False to avoid any erosion if this size is reached.skel_eros_filt_size (
Optional[int], default:None) – Erosion filter size before skeletonization inLabelToMarkerErosion.erode_labels(). Defaults to None to use the minimum filter size, which is half offilter_size.wt_dists (
Optional[ndarray], default:None) – Array of distances by which to weight the filter size, such as a distance transform to the outer perimeter oflabels_imgto weight central labels more heavily. Defaults to None.multiprocess (
bool, default:True) – True to use multiprocessing; defaults to True.
- Return type:
- Returns:
Tuple of an image array of the same shape as
imgand the same number of labels as inlabels_img, with eroded labels, and a data frame of erosion metrics.
- magmap.cv.segmenter.mask_atlas(atlas, labels_img)[source]#
Generate a mask of an atlas by combining its thresholded image with its associated labels image.
The labels image may be insufficient to find the whole atlas foreground if the labels have missing regions or around edges, while the thresholded atlas may have many holes. As a simple workaround, combine these foregrounds to obtain a more complete mask of the atlas.
- Parameters:
img – Image as a Numpy array to segment.
labels_img – Labels image of the same shape as
img, where all values except 0 will be taken as an additional part of the resulting mask.
- Returns:
Boolean array the same shape as
imgwith True for all pixels above threshold inimgor within the foreground oflabels_img.
- magmap.cv.segmenter.segment_from_labels(edges, markers, labels_img, atlas_img=None, exclude_labels=None, mask_filt=SmoothingModes.opening, mask_filt_size=2)[source]#
Segment an image using markers from a labels image.
Labels images may have been generally manually and thus may not perfectly match the underlying image. As a way to check or augment the label image, segment the underlying image using the labels as the seeds to prescribe the number and initial location of each label.
- Parameters:
edges (
np.ndarray) – Image as a Numpy array to segment, typically an edge-detected image of the main atlas.markers (
np.ndarray) – Image as an integer Numpy array of same shape asimgto use as seeds for the watershed segmentation. This array is generally constructed from an array similar tolabels_img.labels_img (
np.ndarray) – Labels image as Numpy array of same shape asimg, used to generate a mask for the watershed. If None, a mask will be generated from a thresholded version ofatlas_img, so should only be None ifatlas_imgis not None.atlas_img (
np.ndarray) – Atlas image as a Numpy array to use for finding foreground; defaults to None. If bothlabels_imgandatlas_imgare not None, their combined volume will be used as a mask.exclude_labels (List[int]) – Sequence of labels to exclude from the segmentation; defaults to None.
mask_filt (
config.SmoothingModes) – Enumeration for a filter mode to use for the watershed mask; defaults toconfig.SmoothingModes.opening. Ignored ifatlas_imgor bothatlas_imgandlabels_imgare given to generate the mask.mask_filt_size (int) – Size of structuring element for the filter specified by
mask_filt; defaults to 2.
- Returns:
Segmented image of the same shape as
imgwith the same number of labels as inmarkers.- Return type:
np.ndarray
- magmap.cv.segmenter.segment_rw(roi, channel, beta=50.0, vmin=0.6, vmax=0.65, remove_small=None, erosion=None, blobs=None, get_labels=False)[source]#
Segments an image using the Random-Walker algorithm.
- Parameters:
roi – Region of interest to segment.
channel – Channel to pass to :func:
plot_3d.setup_channels.beta (default:
50.0) – Random-Walker beta term.vmin (default:
0.6) – Values under which to exclude in markers; defaults to 0.6. Ignored ifblobsis given.vmax (default:
0.65) – Values above which to exclude in markers; defaults to 0.65. Ignored ifblobsis given.remove_small (default:
None) – Threshold size of small objects to remove; defaults to None to ignore.erosion (default:
None) – Structuring element size for erosion; defaults to None to ignore.blobs (default:
None) – Blobs to use for markers; defaults to None, in which case markers will be determined based onvmin/vmaxthresholds.get_labels (default:
False) – True to measure and return labels from the resulting segmentation instead of returning the segmentations themselves; defaults to False.
- Returns:
List of the Random-Walker segmentations for the given channels, If
get_labelsis True, the measured labels for the segmented regions will be returned instead of the segmentations themselves.
- magmap.cv.segmenter.segment_ws(roi, channel, thresholded=None, blobs=None)[source]#
Segment an image using a compact watershed, including the option to use a 3D-seeded watershed approach.
- Parameters:
roi – ROI as a Numpy array in (z, y, x) order.
channel – Channel to pass to :func:
plot_3d.setup_channels.thresholded (default:
None) – Thresholded image such as a segmentation into foreground/ background given by Random-walker (:func:segment_rw). Defaults to None, in which case Otsu thresholding will be performed.blobs (default:
None) – Blobs as a Numpy array in [[z, y, x, …], …] order, which are used as seeds for the watershed. Defaults to None, in which case peaks on a distance transform will be used.
- Returns:
List of watershed labels for each given channel, with each set of labels given as an image of the same shape as
roi.
- magmap.cv.segmenter.sub_segment_labels(labels_img_np, atlas_edge)[source]#
Sub-segment a labels image into sub-labels based on anatomical boundaries.
- Parameters:
labels_img_np – Integer labels image as a Numpy array.
atlas_edge – Numpy array of atlas reduced to binary image of its edges.
- Returns:
Image as a Numpy array of same shape as
labels_img_npwith each label sub-segmented based on anatomical boundaries. Labels in this image will correspond to the original labels multiplied by :const:config.SUB_SEG_MULTto make room for sub-labels, which will each be incremented by 1.
- magmap.cv.segmenter.watershed_distance(foreground, markers=None, num_peaks=inf, compactness=0, mask=None)[source]#
Perform watershed segmentation based on distance from foreground to background.
- Parameters:
foreground – Boolean array where True represents foreground. The distances will be measured from foreground to the nearest background.
markers (default:
None) – Array of same size asforegroundwith seeds to use for the watershed. Defaults to None, in which case markers will be generated from local peaks in the distance transform.num_peaks (default:
inf) – Number of peaks to include when generating markers; defaults to infinity.compactness (float) – Compactness factor for watershed; defaults to 0.
mask (default:
None) – Boolean or binary array of same size asforegroundwhere True or 1 pixels will be filled by the watershed; defaults to None to fill the whole image.
- Returns:
The segmented image as an array of the same shape as that of
foreground.