magmap.cv.cv_nd module¶
Computer vision library functions for n-dimensions.
- magmap.cv.cv_nd.affine_nd(img_np, axis_along, axis_shift, shift, bounds, axis_attach=None, attach_far=False)[source]¶
Affine transform an image of arbitrary dimensions.
- Parameters:
img_np – Numpy array.
axis_along – Axis along which to shear, given as an int in standard Numpy axis convention.
axis_shift – Axis giving the direction in which to shear.
shift – Tuple of
(shift_start, shift_end), giving the distance in pixels by which to shear while progressing alongaxis_along.bounds – Tuple given as
((z_start, z_end), (y_start, ...) ...), with each value given in pixels demarcating the bounds of the ROI to transform.axis_attach (default:
None) – Axis along which the sheared region will remain attached to the original image to provide a smooth transition in the case of selective affines. Another affine will be performed to along this axis, starting with 0 shift at the point of attachment to the full shift for the given plane at the opposite side. The direction of shearing is based on the correspondingboundsfor this axis. Defaults to None, in which case this affine will be ignored.attach_far (default:
False) – True to attach from the opposite, farther side alongaxis_attach, from higher to lower indices; defaults to False.
- Returns:
The transformed image.
- magmap.cv.cv_nd.angle_indices(shape, offset, size, nsteps=None)[source]¶
Generate indices for an angled plane or other shape.
Can be used to construct a polygon mask with angled faces. Indices co-vary so that as
offset_z->offset_z + size_z,offset_y->offset_y + size_y, etc.- Parameters:
shape (
Sequence[int]) – Shape of object containing the desired plane.offset (
Sequence[int]) – Offset within the object in the orderrz, y, x.size (
Sequence[int]) – Size within the object corresponding to elements inoffset.nsteps (
Optional[int], default:None) – Number of steps to interpolate. Defaults to None, where the max ofshapex 10 is used to reduce chance of gaps.
- Returns:
Indices in the same order as for
shape.
Examples
See
magmap.tests.test_cv_nd.test_angle_indices().
- magmap.cv.cv_nd.borders_distance(borders_orig, borders_shifted, mask_orig=None, filter_size=None, gaus_sigma=None, spacing=None)[source]¶
Measure distance between borders.
- Parameters:
borders_orig – Original borders as a boolean mask.
borders_shifted – Shifted borders as a boolean mask, which should match the shape of
borders_orig.mask_orig (default:
None) – Mask of original image for signed distances; defaults to None, in which case all distances will be >= 0.filter_size (default:
None) – Size of structuring element to use in filter for smoothing the original border with a closing filter before finding distances. Defaults to None, in which case no filter will be applied.gaus_sigma (default:
None) – Low-pass filter distances with Gaussian kernel; defaults to None.spacing (default:
None) – Grid spacing sequence of same length as number of image axis dimensions; defaults to None.
- Returns:
Tuple of
dist_to_orig, a Numpy array the same shape asborders_origwith distances generated from a Euclidean distance transform to the original borders, or to the smoothed borders iffilter_sizeis given;indices, the distance transform indices inborders_origcorresponding to each pixel inborders_smoothed; andborders_origto allow accessing the smoothed borders.
- magmap.cv.cv_nd.build_heat_map(shape, coords)[source]¶
Build a heat map for an image based on point placement within it.
The heat map is scaled at the level of
shape, generally assuming thatcoordshave been scaled from a larger size. In other words, the heat map will show the density at the level of its pixels and can be further rescaled/resized to show density at different resolutions.- Parameters:
shape – Shape of image that contains
coords.coords – Array of coordinates of points. The array should have shape (n, m), where n = number of coordinate sets, and m = number of coordinate dimensions.
- Returns:
An image of shape
shapewith values corresponding to the number of point occurrences at each pixel.- Return type:
np.ndaarry
- magmap.cv.cv_nd.calc_compactness(ndim, size_borders, size_object)[source]¶
Compute the classical compactness, currently supported for 2D or 3D.
For 2D, the equation is given by: perimeter^2 / area. For 3D: area^3 / vol^2.
- magmap.cv.cv_nd.calc_isotropic_factor(scale=1, res=None)[source]¶
Calculate the isotropic factor based on the current image resolutions.
The resolutions are divided by their minimum value and multiplied by the given scaling factor. The resulting value can be used to rescale images or coordinates to be isotropic.
- Parameters:
scale (
Union[float,Sequence[float]], default:1) – Float scalar or sequence of scaling factors inz, y, xby which to multiply the currently loaded image’s resolutions. Defaults to 1.res (
Optional[Sequence[float]], default:None) – Resolutions in the same order as forscale. Default to None, in which casemagmap.settings.config.resolutionswill be used instead.
- Return type:
- Returns:
Isotropic factor.
- magmap.cv.cv_nd.carve(roi, thresh=None, holes_area=None, return_unfilled=False)[source]¶
Carve image by thresholding and filling in small holes.
- Parameters:
roi (
numpy.ndarray) – Image as Numpy array.thresh (float) – Value by which to threshold. Defaults to None, in which case a mean threshold will be applied.
holes_area (int) – Maximum area of holes to fill; defaults to None to leave unfilled.
return_unfilled (bool) – True to return the carved image without any filling; defaults to False.
- Returns:
The carved image and the mask used to carve this image. If
return_unfilledis True, also returns the carvedroiwithoutholes_areaapplied. All arrays are of the same shape as that ofroi.- Return type:
- magmap.cv.cv_nd.compactness_3d(img_np, spacing=None)[source]¶
Compute compactness with 3D area based on
surface_area_3d()and support for anisotropy.- Parameters:
img_np (
np.ndarray) – Mask of the object.spacing (List[float]) – Sequence of voxel spacing in same order as for
img_np; defaults to None.
- Returns:
Tuple of compactness metric value from
calc_compactness(), surface area, and volume.
- magmap.cv.cv_nd.compactness_count(mask_borders, mask_object)[source]¶
Compute compactness based on simple boundary and size counts.
- Parameters:
mask_borders (
np.ndarray) – Mask of the borders to find the perimeter (2D) or surface area (3D) by simple boundary pixel count.mask_object (
np.ndarray) – Mask of the object to find the area (2D) or volume (3D).
- Returns:
Tuple of compactness metric value from
calc_compactness(), borders measurement, and object size.
- magmap.cv.cv_nd.crop_to_labels(img_labels, img_ref, mask=None, dil_size=2, padding=5)[source]¶
Crop images to match the extent of a labels volume.
Both labels and reference images will be cropped to match the extent of labels with a small padding region. Reference image pixels outside of a small dilation of the labels mask will be turned to zero.
- Parameters:
img_labels (
np.ndarray) – Labels image.img_ref (
np.ndarray) – Reference image of same shape as that ofimg_labels.mask (
np.ndarray, optional) – Binary array of same shape as that ofimg_labelsto use in place of it for determining the extent of cropping. Defaults to None. Will not be used to mask out signal within the cropped in volume.dil_size (int, optional) – Size of structuring element for dilating the crop region; defaults to 2.
padding (int, optional) – Size of padding around the mask bounding box; defaults to 5.
- Returns:
Tuple of
extracted_labels, the cropped labels image;extracted_ref, the cropped reference image, extracting only pixels corresponding to the labels; andslices, a list of the bounding box slices by which the images were cropped.
- magmap.cv.cv_nd.exterior_nd(img_np)[source]¶
Get the exterior surrounding foreground, the pixels just beyond the foreground’s border, which can be used to find connected neighbors.
- Parameters:
img_np – Numpy array of arbitrary dimensions with foreground to dilate.
- Returns:
The pixels just outside the image as a boolean array where True represents the border that would have been eroded.
- magmap.cv.cv_nd.extract_region(labels_img, label_id)[source]¶
Wrapper for extracting a labeled region.
- Parameters:
- Return type:
- Returns:
Tuple of the bounding box of the region containing
label_idand the list of slices inlabels_imgdefining the extracted indices. If no bounding box was found, each value is returned as None. If multiple separate regions are found, only the first is returned.
- magmap.cv.cv_nd.filter_adaptive_size(mask, fn_filter, filter_size, min_filter_size=1, use_min_filter=False, min_size_ratio=None, name='')[source]¶
Filter morphologically with adaptive kernel sizes.
- Parameters:
mask (
numpy.ndarray) – Numpy array as a mask.fn_filter (func) – Morphological filter function to apply.
filter_size (int) – Starting filter kernel size.
min_filter_size (int) – Minimum kernel size.
use_min_filter (bool) – True to use the filtered result if the kernel size is below
min_filter_sizeeven if filter criteria are not met; defaults to False.min_size_ratio (float) – Minimum size ratio of filtered to original mask; defaults to None to use a ratio of 0.2.
name (str) – Name to prepend to output message; defaults to “”.
- Returns:
Filtered
maskand kernel size at whichmaskwas filtered, ornp.nanif not filtered.- Return type:
numpy.ndarray, int
- magmap.cv.cv_nd.get_bbox_region(bbox, padding=0, img_shape=None)[source]¶
Get slices from a bounding box from which to extract the ROI from the original image as a view and with an optional padding.
- Parameters:
bbox – Bounding box as given by :func:
get_label_bbox.padding (default:
0) – Int of padding in pixels outside of the box to include; defaults to 0.img_shape (default:
None) – Sequence of maximum output coordinates, where any end coordinate will be truncated to the corresponding value. Defaults to None.
- Returns:
Tuple of the ROI shape and list of ROI slices containing the start and end indices of the ROI along each axis.
- magmap.cv.cv_nd.get_label_bbox(labels_img_np, label_id)[source]¶
Get bounding box for a label or set of labels.
Assumes that only one set of properties will be found for a given label, returning only the first set.
- Parameters:
labels_img_np – Image as Numpy array.
label_id – Scalar or sequence of scalars of the label IDs to include in the bounding box.
- Returns:
Bounding box from :func:
measure.regionprops. If more than one set of properties are found, only the box from the first property will be returned.
- magmap.cv.cv_nd.get_label_props(labels_img_np, label_id)[source]¶
Get region properties for a label or set of labels.
- Parameters:
labels_img_np – Image as Numpy array.
label_id – Scalar or sequence of scalars of the label IDs to include in the bounding box.
- Returns:
Region properties from :func:
measure.regionprops.
- magmap.cv.cv_nd.get_selem(ndim)[source]¶
Get structuring element appropriate for the number of dimensions.
Currently only supports disk or ball structuring elements.
- Parameters:
ndim (int) – Number of dimensions.
- Returns:
func: Structuring element function. A
morphology.ball()is returned for 3 or more dimensions, otherwise amorphology.disk().
- magmap.cv.cv_nd.get_thresholded_regionprops(img_np, threshold=10, sort_reverse=False)[source]¶
Get the region properties for a thresholded image.
- Parameters:
- Returns:
List of
(prop, area), sorted by area from smallest to largest unless reversed bysort_reverse.
- magmap.cv.cv_nd.in_paint(roi, to_fill)[source]¶
In-paint to interpolate values into pixels to fill from nearest neighbors.
- Parameters:
roi (
numpy.ndarray) – ROI in which to fill pixels.to_fill (
numpy.ndarray) – Boolean array of same shape asroiwhere True values designate the pixels to fill.
- Returns:
Copy of ROI with pixels corresponding to
to_fillfilled with nearest neighbors.- Return type:
- magmap.cv.cv_nd.interpolate_contours(bottom, top, fracs)[source]¶
Interpolate contours between two planes.
- Parameters:
bottom (
np.ndarray) – Bottom plane as an binary mask.top (
np.ndarray) – Top plane as an binary mask.fracs (List[float]) – List of fractions from 0 to 1, inclusive, at which to interpolate contours. 0 corresponds to the bottom plane, and 1 is the top plane.
- Returns:
Array with each plane corresponding to the interpolated plane at the fractions corresponding to
fracs.- Return type:
np.ndarray
- magmap.cv.cv_nd.interpolate_label_between_planes(labels_img, label_id, axis, bounds)[source]¶
Interpolate between two planes for the given labeled region.
Assume that the given label ID has only been extended and not erased within the given image. This image will be updated in-place.
- Parameters:
labels_img – Labels image as a Numpy array in z,y,x dimensions.
label_id – ID of label whose planes will be replaced.
axis – Axis along which planes will be selected.
bounds – 2-element list demarcating the planes between which to interpolate. The list will be sorted, and the lower bound will mark the starting plane, while the upper bound will mark the ending plane, inclusive.
- magmap.cv.cv_nd.laplacian_of_gaussian_img(img, sigma=5, labels_img=None, thresh=None)[source]¶
Generate a Laplacian of Gaussian (LoG) image.
- Parameters:
img – Image as Numpy array from which the LoG will be generated.
sigma (default:
5) – Sigma for Gaussian filters; defaults to 5.labels_img (default:
None) – Labels image as Numpy array in same shape asimg, to use to assist with thresholding out background. Defaults to None to skip background removal.thresh (default:
None) – Threshold of atlas image to find background solely from atlas, without using labels;labels_imgwill be ignored ifthreshis given. Defaults to None.
- magmap.cv.cv_nd.make_isotropic(roi, scale=1, res=None, **kwargs)[source]¶
Make an array isotropic.
- Parameters:
roi (
ndarray) – Region of interest array inz, y, xformat.scale (
Union[float,Sequence[float]], default:1) – Float scalar or sequence of scaling factors inz, y, xby which to multiply the currently loaded image’s resolutions. Defaults to 1.res (
Optional[Sequence[float]], default:None) – Resolutions in the same order as forscale. Default to None, in which casemagmap.settings.config.resolutionswill be used instead.kwargs – Additional arguments to
rescale_resize().
- Return type:
- Returns:
Isotropic version of
roi.
- magmap.cv.cv_nd.meas_region(mask, res)[source]¶
Measure the dimensions of a masked region.
- Parameters:
mask (
np.ndarray) – Binary array as a region mask. Assumes that this mask defines a single foreground region.res (List[float]) – Sequence of resolutions/spacing by dimension in
mask.
- Returns:
Dimensions of the bounding box of the first region defined by
maskin the physical units ofres; total volume of the mask in physical units; the region properties ofmaskas given bymeasure.regionprops().- Return type:
- magmap.cv.cv_nd.perimeter_nd(img_np, largest_only=False, footprint=None)[source]¶
Get perimeter of image subtracting eroded image from given image.
- Parameters:
img_np (
ndarray) – Numpy array of arbitrary dimensions.largest_only (
bool, default:False) – True to retain only the largest connected component, typically the outer border; defaults to False.footprint (
Optional[Sequence[int]], default:None) – Structure element for eroding the interior, which sets the border thickness; defaults to None.
- Return type:
- Returns:
The perimeter as a boolean array where True represents the border that would have been eroded.
- magmap.cv.cv_nd.radial_dist(borders, centroid)[source]¶
Measure radial distance from borders to given center.
- Parameters:
borders – Original borders as a boolean mask.
centroid – Coordinates corresponding to chosen reference point.
- Returns:
A Numpy array the same shape as
borderswith distances measured from each point inborderstocentroidpoint.
- magmap.cv.cv_nd.radial_dist_diff(radial_orig, radial_shifted, indices)[source]¶
Measure the difference between corresponding points in radial distance arrays to get the relative distance from one set of borders to another with reference to the centroid from which the radial distances were calculated.
Shifted points with positive distances are farther from the reference point than the closest original point is.
- Parameters:
radial_orig – Radial original distances as a Numpy array.
radial_shifted – Radial shifted distances as a Numpy array.
- Returns:
A Numpy array the same shape as
radial_origwith differences in distance fromradial_shiftedto the corresponding points inradial_orig.
- magmap.cv.cv_nd.remove_bg_from_dil_fg(img, mask, selem)[source]¶
Remove background by converting the area outside of a dilated foreground mask to background.
- Parameters:
img (
np.ndarray) – Image array whose pixels outside of the dilatedmaskwill be zeroed in-place.mask (
np.ndarray) – Foreground as a binary array of same size asimgthat will be dilated.selem (
np.ndarray) – Array of the same dimensions asimgto serve as the structuring element for dilation.
- magmap.cv.cv_nd.rescale_resize(roi, target_size=None, multichannel=False, preserve_range=False, **kwargs)[source]¶
Rescale or resize an array.
- Parameters:
roi (
ndarray) – Array to rescale or resize, in ``z, y, x, [c]` order.target_size (
Union[float,Sequence[int],None], default:None) – Target rescaling size for the given sub-ROI inz, y, x, or a single number by which to rescale.multichannel (
bool, default:False) – True if the final dimension is for channels; defaults to False.preserve_range (
bool, default:False) – True to preserve the range ofroi; defaults to False.kwargs – Additional arguments passed to
transform.rescale()ortransform.resize(), such asorderfor label images.
- Return type:
- Returns:
Rescaled array.
- magmap.cv.cv_nd.rotate90(roi, rotate, axes=None, multichannel=False)[source]¶
Rotate an image by increments of 90 degrees.
Serves as a wrapper for
numpy.rot90()with default rotation in the xy plane.- Parameters:
roi (
ndarray) – Image as a 3D+/-channel array. Can be None to return as-is.rotate (
int) – Number of times to rotate 90 degrees.axes (
Optional[Sequence[int]], default:None) – Sequence of two axes defining the plane to rotate; defaults to None to use[-2, -1], the 2nd to last and last axes.multichannel (
bool, default:False) – True if the image is multichannel; defaults to False. Only used ifaxescontains negative axis indices.
- Return type:
- Returns:
Rotated image.
- magmap.cv.cv_nd.rotate_nd(img_np, angle, axis=0, order=1, resize=False)[source]¶
Rotate an image of arbitrary dimensions along a given axis.
This function is essentially a wrapper of
skimage.transform.rotate(), applied to each 2D plane along a given axis for volumetric rotation.- Parameters:
img_np (
ndarray) – 2D or higher dimensional NumPy array.angle (
float) – Angle by which to rotate.axis (
int, default:0) – Axis along which to rotate, given as an int in standard Numpy axis convention; defaults to 0order (
int, default:1) – Spline interpolation order; defaults to 1.resize (
bool, default:False) – True to resize the output image to avoid any image cropping; defaults to False.
- Return type:
- Returns:
The rotated image.
- magmap.cv.cv_nd.signed_distance_transform(borders, mask=None, return_indices=False, spacing=None)[source]¶
Signed version of Euclidean distance transform where values within a given mask are considered negative.
This version can be applied to the case of a border where distances inside the border, defined as those within the original image from which the borders were construcuted, are considered negative.
- Parameters:
borders – Borders as a boolean mask, typically where borders are False and non-borders are True.
mask (default:
None) – Mask where distances will be considered neg, such as a mask of the full image for the borders. Defaults to None, in which case distances will be given as-is.return_indices (default:
False) – True if distance transform indices should be given; defaults to False.spacing (default:
None) – Grid spacing sequence of same length as number of image axis dimensions; defaults to None.
- Returns:
transformas the signed distances. Ifreturn_indicesis True,indicesis also returned. If nomaskis given, returns the same output as from :meth:ndimage.distance_transform_edt.
- magmap.cv.cv_nd.surface_area_3d(img_np, level=0.0, spacing=None)[source]¶
Measure the surface area for a 3D volume.
Wrapper for
measure.marching_cubes_lewiner()andmeasure.mesh_surface_area().- Parameters:
img_np (
ndarray) – 3D image array, which can be a mask.level (
float, default:0.0) – Contour value formeasure.marching_cubes_lewiner(); defaults to 0.0.spacing (
Optional[Sequence[float]], default:None) – Sequence of voxel spacing in same order as forimg_np; defaults to None, which will use a value ofnp.ones(3).
- Return type:
- Returns:
Surface area in the coordinate units squared.
- magmap.cv.cv_nd.zero_crossing(img, filter_size)[source]¶
Apply a zero-crossing detector to an image, such as an image produced by a Laplacian of Gaussian.
- Parameters:
img – Image as a Numpy array.
filter_size – Size of structuring element, where larger sizes give thicker edges.
- Returns:
Array of same size as
imgas a mask of edges.