Convert an image to 16-bit signed integer format.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
The values are scaled between -32768 and 32767. If the input data-type is positive-only (e.g., uint8), then the output image will still only have positive values.


Convert an image to 8-bit unsigned integer format.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
Negative input values will be clipped. Positive values are scaled between 0 and 255.


Convert an image to 16-bit unsigned integer format.
Input image.
Force a copy of the data, irrespective of its current dtype.
Output image.
Negative input values will be clipped. Positive values are scaled between 0 and 65535.


Utilities to read and write images in various formats.
The following plug-ins are available:
Plugin
Description
qt
Fast image display using the Qt library. Deprecated since 0.18. Will be removed in 0.20.
imread
Image reading and writing via imread
gdal
Image reading via the GDAL Library (www.gdal.org)
simpleitk
Image reading and writing via SimpleITK
gtk
Fast image display using the GTK library
pil
Image reading via the Python Imaging Library
fits
FITS image reading via PyFITS
matplotlib
Display or save images using Matplotlib
tifffile
Load and save TIFF and TIFF-based images using tifffile.py
imageio
Image reading via the ImageIO Library
skimage.io.call_plugin(kind, *args, **kwargs)
Find the appropriate plugin of ‘kind’ and execute it.
skimage.io.concatenate_images(ic)
Concatenate all images in the image collection into an array.
skimage.io.find_available_plugins([loaded])
List available plugins.
skimage.io.imread(fname[, as_gray, plugin])
Load an image from file.
skimage.io.imread_collection(load_pattern[, …])
Load a collection of images.
skimage.io.imread_collection_wrapper(imread)
skimage.io.imsave(fname, arr[, plugin, …])
Save an image to file.
skimage.io.imshow(arr[, plugin])
Display an image.
skimage.io.imshow_collection(ic[, plugin])
Display a collection of images.
skimage.io.load_sift(f)
Read SIFT or SURF features from externally generated file.
skimage.io.load_surf(f)
Read SIFT or SURF features from externally generated file.
skimage.io.plugin_info(plugin)
Return plugin meta-data.
skimage.io.plugin_order()
Return the currently preferred plugin order.
skimage.io.pop()
Pop an image from the shared image stack.
skimage.io.push(img)
Push an image onto the shared image stack.
skimage.io.reset_plugins()
skimage.io.show()
Display pending images.
skimage.io.use_plugin(name[, kind])
Set the default plugin for a specified operation.
skimage.io.ImageCollection(load_pattern[, …])
Load and manage a collection of image files.
skimage.io.MultiImage(filename[, …])
A class containing all frames from multi-frame images.
skimage.io.collection
Data structures to hold collections of images, with optional caching.
skimage.io.manage_plugins
Handle image reading, writing and plotting plugins.
skimage.io.sift
skimage.io.util
Find the appropriate plugin of ‘kind’ and execute it.
Function to look up.
Plugin to load. Defaults to None, in which case the first matching plugin is used.
Passed to the plugin function.
Concatenate all images in the image collection into an array.
The images to be concatenated.
An array having one more dimension than the images in ic.
If images in ic don’t have identical shapes.
See also
concatenate_images receives any iterable object containing images, including ImageCollection and MultiImage, and returns a NumPy array.
List available plugins.
If True, show only those plugins currently loaded. By default, all plugins are shown.
Dictionary with plugin names as keys and exposed functions as values.
Load an image from file.
Image file name, e.g. test.jpg or URL.
If True, convert color images to gray-scale (64-bit floats). Images that are already in gray-scale format are not converted.
Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found. If not given and fname is a tiff file, the tifffile plugin will be used.
The different color bands/channels are stored in the third dimension, such that a gray-image is MxN, an RGB-image MxNx3 and an RGBA-image MxNx4.
Passed to the given plugin.
Load a collection of images.
List of objects to load. These are usually filenames, but may vary depending on the currently active plugin. See the docstring for ImageCollection for the default behaviour of this parameter.
If True, never keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded.
Collection of images.
Passed to the given plugin.
Save an image to file.
Target filename.
Image data.
Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found. If not given and fname is a tiff file, the tifffile plugin will be used.
Check for low contrast and print warning (default: True).
Passed to the given plugin.
When saving a JPEG, the compression ratio may be controlled using the quality keyword argument which is an integer with values in [1, 100] where 1 is worst quality and smallest file size, and 100 is best quality and largest file size (default 75). This is only available when using the PIL and imageio plugins.
Display an image.
Image data or name of image file.
Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found.
Passed to the given plugin.
Explore 3D images (of cells)
Display a collection of images.
Collection to display.
Name of plugin to use. By default, the different plugins are tried until a suitable candidate is found.
Passed to the given plugin.
Read SIFT or SURF features from externally generated file.
This routine reads SIFT or SURF files generated by binary utilities from http://people.cs.ubc.ca/~lowe/keypoints/ and http://www.vision.ee.ethz.ch/~surf/.
This routine does not generate SIFT/SURF features from an image. These algorithms are patent encumbered. Please use skimage.feature.CENSURE instead.
Input file generated by the feature detectors from http://people.cs.ubc.ca/~lowe/keypoints/ or http://www.vision.ee.ethz.ch/~surf/ .
Kind of descriptor used to generate filelike.
row position of feature
column position of feature
feature scale
feature orientation
feature values
Read SIFT or SURF features from externally generated file.
This routine reads SIFT or SURF files generated by binary utilities from http://people.cs.ubc.ca/~lowe/keypoints/ and http://www.vision.ee.ethz.ch/~surf/.
This routine does not generate SIFT/SURF features from an image. These algorithms are patent encumbered. Please use skimage.feature.CENSURE instead.
Input file generated by the feature detectors from http://people.cs.ubc.ca/~lowe/keypoints/ or http://www.vision.ee.ethz.ch/~surf/ .
Kind of descriptor used to generate filelike.
row position of feature
column position of feature
feature scale
feature orientation
feature values
Return plugin meta-data.
Name of plugin.
Meta data as specified in plugin .ini.
Return the currently preferred plugin order.
Dictionary of preferred plugin order, with function name as key and plugins (in order of preference) as value.
Pop an image from the shared image stack.
Image popped from the stack.
Push an image onto the shared image stack.
Image to push.
Display pending images.
Launch the event loop of the current gui plugin, and display all pending images, queued via imshow. This is required when using imshow from non-interactive scripts.
A call to show will block execution of code until all windows have been closed.
Set the default plugin for a specified operation. The plugin will be loaded if it hasn’t been already.
Name of plugin.
Set the plugin for this function. By default, the plugin is set for all functions.
See also
List of available plugins
To use Matplotlib as the default image reader, you would write:
To see a list of available plugins run io.available_plugins. Note that this lists plugins that are defined, but the full list may not be usable if your system does not have the required libraries installed.
Bases: object
Load and manage a collection of image files.
Pattern string or list of strings to load. The filename path can be absolute or relative.
If True, ImageCollection does not keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded.
imread by default. See notes below.
Note that files are always returned in alphanumerical order. Also note that slicing returns a new ImageCollection, not a view into the data.
ImageCollection can be modified to load images from an arbitrary source by specifying a combination of load_pattern and load_func. For an ImageCollection ic, ic[5] uses load_func(load_pattern[5]) to load the image.
Imagine, for example, an ImageCollection that loads every third frame from a video file:
Another use of load_func would be to convert all images to uint8:
If a pattern string is given for load_pattern, this attribute stores the expanded file list. Otherwise, this is equal to load_pattern.
Load and manage a collection of images.
Concatenate all images in the collection into an array.
An array having one more dimension than the images in self.
If images in the ImageCollection don’t have identical shapes.
See also
Clear the image cache.
Clear the cache for this image only. By default, the entire cache is erased.
Bases: skimage.io.collection.ImageCollection
A class containing all frames from multi-frame images.
Pattern glob or filenames to load. The path can be absolute or relative.
Whether to conserve memory by only caching a single frame. Default is True.
imread by default. See notes below.
If conserve_memory=True the memory footprint can be reduced, however the performance can be affected because frames have to be read from file more often.
The last accessed frame is cached, all other frames will have to be read from file.
The current implementation makes use of tifffile for Tiff files and PIL otherwise.
Load a multi-img.


Find the appropriate plugin of ‘kind’ and execute it.
Function to look up.
Plugin to load. Defaults to None, in which case the first matching plugin is used.
Passed to the plugin function.


Concatenate all images in the image collection into an array.
The images to be concatenated.
An array having one more dimension than the images in ic.
If images in ic don’t have identical shapes.
See also
concatenate_images receives any iterable object containing images, including ImageCollection and MultiImage, and returns a NumPy array.


List available plugins.
If True, show only those plugins currently loaded. By default, all plugins are shown.
Dictionary with plugin names as keys and exposed functions as values.


Bases: object
Load and manage a collection of image files.
Pattern string or list of strings to load. The filename path can be absolute or relative.
If True, ImageCollection does not keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded.
imread by default. See notes below.
Note that files are always returned in alphanumerical order. Also note that slicing returns a new ImageCollection, not a view into the data.
ImageCollection can be modified to load images from an arbitrary source by specifying a combination of load_pattern and load_func. For an ImageCollection ic, ic[5] uses load_func(load_pattern[5]) to load the image.
Imagine, for example, an ImageCollection that loads every third frame from a video file:
Another use of load_func would be to convert all images to uint8:
If a pattern string is given for load_pattern, this attribute stores the expanded file list. Otherwise, this is equal to load_pattern.
Load and manage a collection of images.
Concatenate all images in the collection into an array.
An array having one more dimension than the images in self.
If images in the ImageCollection don’t have identical shapes.
See also
Clear the image cache.
Clear the cache for this image only. By default, the entire cache is erased.


Concatenate all images in the collection into an array.
An array having one more dimension than the images in self.
If images in the ImageCollection don’t have identical shapes.
See also


Clear the image cache.
Clear the cache for this image only. By default, the entire cache is erased.


Load an image from file.
Image file name, e.g. test.jpg or URL.
If True, convert color images to gray-scale (64-bit floats). Images that are already in gray-scale format are not converted.
Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found. If not given and fname is a tiff file, the tifffile plugin will be used.
The different color bands/channels are stored in the third dimension, such that a gray-image is MxN, an RGB-image MxNx3 and an RGBA-image MxNx4.
Passed to the given plugin.


Load a collection of images.
List of objects to load. These are usually filenames, but may vary depending on the currently active plugin. See the docstring for ImageCollection for the default behaviour of this parameter.
If True, never keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded.
Collection of images.
Passed to the given plugin.


Save an image to file.
Target filename.
Image data.
Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found. If not given and fname is a tiff file, the tifffile plugin will be used.
Check for low contrast and print warning (default: True).
Passed to the given plugin.
When saving a JPEG, the compression ratio may be controlled using the quality keyword argument which is an integer with values in [1, 100] where 1 is worst quality and smallest file size, and 100 is best quality and largest file size (default 75). This is only available when using the PIL and imageio plugins.


Display an image.
Image data or name of image file.
Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found.
Passed to the given plugin.


Display a collection of images.
Collection to display.
Name of plugin to use. By default, the different plugins are tried until a suitable candidate is found.
Passed to the given plugin.


Read SIFT or SURF features from externally generated file.
This routine reads SIFT or SURF files generated by binary utilities from http://people.cs.ubc.ca/~lowe/keypoints/ and http://www.vision.ee.ethz.ch/~surf/.
This routine does not generate SIFT/SURF features from an image. These algorithms are patent encumbered. Please use skimage.feature.CENSURE instead.
Input file generated by the feature detectors from http://people.cs.ubc.ca/~lowe/keypoints/ or http://www.vision.ee.ethz.ch/~surf/ .
Kind of descriptor used to generate filelike.
row position of feature
column position of feature
feature scale
feature orientation
feature values


Bases: skimage.io.collection.ImageCollection
A class containing all frames from multi-frame images.
Pattern glob or filenames to load. The path can be absolute or relative.
Whether to conserve memory by only caching a single frame. Default is True.
imread by default. See notes below.
If conserve_memory=True the memory footprint can be reduced, however the performance can be affected because frames have to be read from file more often.
The last accessed frame is cached, all other frames will have to be read from file.
The current implementation makes use of tifffile for Tiff files and PIL otherwise.
Load a multi-img.


Return plugin meta-data.
Name of plugin.
Meta data as specified in plugin .ini.


Return the currently preferred plugin order.
Dictionary of preferred plugin order, with function name as key and plugins (in order of preference) as value.


Pop an image from the shared image stack.
Image popped from the stack.


Push an image onto the shared image stack.
Image to push.


Display pending images.
Launch the event loop of the current gui plugin, and display all pending images, queued via imshow. This is required when using imshow from non-interactive scripts.
A call to show will block execution of code until all windows have been closed.


Set the default plugin for a specified operation. The plugin will be loaded if it hasn’t been already.
Name of plugin.
Set the plugin for this function. By default, the plugin is set for all functions.
See also
List of available plugins
To use Matplotlib as the default image reader, you would write:
To see a list of available plugins run io.available_plugins. Note that this lists plugins that are defined, but the full list may not be usable if your system does not have the required libraries installed.


Do a keyword search on scikit-image docstrings.
Words to look for.


skimage.measure.approximate_polygon(coords, …)
Approximate a polygonal chain with the specified tolerance.
skimage.measure.block_reduce(image, block_size)
Downsample image by applying function func to local blocks.
skimage.measure.euler_number(image[, …])
Calculate the Euler characteristic in binary image.
skimage.measure.find_contours(image[, …])
Find iso-valued contours in a 2D array for a given level value.
skimage.measure.grid_points_in_poly(shape, verts)
Test whether points on a specified grid are inside a polygon.
skimage.measure.inertia_tensor(image[, mu])
Compute the inertia tensor of the input image.
skimage.measure.inertia_tensor_eigvals(image)
Compute the eigenvalues of the inertia tensor of the image.
skimage.measure.label(input[, background, …])
Label connected regions of an integer array.
skimage.measure.marching_cubes(volume[, …])
Marching cubes algorithm to find surfaces in 3d volumetric data.
skimage.measure.marching_cubes_classic(volume)
Classic marching cubes algorithm to find surfaces in 3d volumetric data.
skimage.measure.marching_cubes_lewiner(volume)
Lewiner marching cubes algorithm to find surfaces in 3d volumetric data.
skimage.measure.mesh_surface_area(verts, faces)
Compute surface area, given vertices & triangular faces
skimage.measure.moments(image[, order])
Calculate all raw image moments up to a certain order.
skimage.measure.moments_central(image[, …])
Calculate all central image moments up to a certain order.
skimage.measure.moments_coords(coords[, order])
Calculate all raw image moments up to a certain order.
skimage.measure.moments_coords_central(coords)
Calculate all central image moments up to a certain order.
skimage.measure.moments_hu(nu)
Calculate Hu’s set of image moments (2D-only).
skimage.measure.moments_normalized(mu[, order])
Calculate all normalized central image moments up to a certain order.
skimage.measure.perimeter(image[, neighbourhood])
Calculate total perimeter of all objects in binary image.
skimage.measure.perimeter_crofton(image[, …])
Calculate total Crofton perimeter of all objects in binary image.
skimage.measure.points_in_poly(points, verts)
Test whether points lie inside a polygon.
skimage.measure.profile_line(image, src, dst)
Return the intensity profile of an image measured along a scan line.
skimage.measure.ransac(data, model_class, …)
Fit a model to data with the RANSAC (random sample consensus) algorithm.
skimage.measure.regionprops(label_image[, …])
Measure properties of labeled image regions.
skimage.measure.regionprops_table(label_image)
Compute image properties and return them as a pandas-compatible table.
skimage.measure.shannon_entropy(image[, base])
Calculate the Shannon entropy of an image.
skimage.measure.subdivide_polygon(coords[, …])
Subdivision of polygonal curves using B-Splines.
skimage.measure.CircleModel()
Total least squares estimator for 2D circles.
skimage.measure.EllipseModel()
Total least squares estimator for 2D ellipses.
skimage.measure.LineModelND()
Total least squares estimator for N-dimensional lines.
Approximate a polygonal chain with the specified tolerance.
It is based on the Douglas-Peucker algorithm.
Note that the approximated polygon is always within the convex hull of the original polygon.
Coordinate array.
Maximum distance from original points of polygon to approximated polygonal chain. If tolerance is 0, the original coordinate array is returned.
Approximated polygonal chain where M <= N.
https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
Downsample image by applying function func to local blocks.
This function is useful for max and mean pooling, for example.
N-dimensional input image.
Array containing down-sampling integer factor along each axis.
Function object which is used to calculate the return value for each local block. This function must implement an axis parameter. Primary functions are numpy.sum, numpy.min, numpy.max, numpy.mean and numpy.median. See also func_kwargs.
Constant padding value if image is not perfectly divisible by the block size.
Keyword arguments passed to func. Notably useful for passing dtype argument to np.mean. Takes dictionary of inputs, e.g.: func_kwargs={'dtype': np.float16}).
Down-sampled image with same number of dimensions as input image.
Calculate the Euler characteristic in binary image.
For 2D objects, the Euler number is the number of objects minus the number of holes. For 3D objects, the Euler number is obtained as the number of objects plus the number of holes, minus the number of tunnels, or loops.
2D or 3D images. If image is not binary, all values strictly greater than zero are considered as the object.
Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If None, a full connectivity of input.ndim is used. 4 or 8 neighborhoods are defined for 2D images (connectivity 1 and 2, respectively). 6 or 26 neighborhoods are defined for 3D images, (connectivity 1 and 3, respectively). Connectivity 2 is not defined.
Euler characteristic of the set of all objects in the image.
The Euler characteristic is an integer number that describes the topology of the set of all objects in the input image. If object is 4-connected, then background is 8-connected, and conversely.
The computation of the Euler characteristic is based on an integral geometry formula in discretized space. In practice, a neighbourhood configuration is constructed, and a LUT is applied for each configuration. The coefficients used are the ones of Ohser et al.
It can be useful to compute the Euler characteristic for several connectivities. A large relative difference between results for different connectivities suggests that the image resolution (with respect to the size of objects and holes) is too low.
S. Rivollier. Analyse d’image geometrique et morphometrique par diagrammes de forme et voisinages adaptatifs generaux. PhD thesis, 2010. Ecole Nationale Superieure des Mines de Saint-Etienne. https://tel.archives-ouvertes.fr/tel-00560838
Ohser J., Nagel W., Schladitz K. (2002) The Euler Number of Discretized Sets - On the Choice of Adjacency in Homogeneous Lattices. In: Mecke K., Stoyan D. (eds) Morphology of Condensed Matter. Lecture Notes in Physics, vol 600. Springer, Berlin, Heidelberg.
Euler number
Find iso-valued contours in a 2D array for a given level value.
Uses the “marching squares” method to compute a the iso-valued contours of the input 2D array for a particular level value. Array values are linearly interpolated to provide better precision for the output contours.
Input image in which to find contours.
Value along which to find contours in the array. By default, the level is set to (max(image) + min(image)) / 2
Changed in version 0.18: This parameter is now optional.
Indicates whether array elements below the given level value are to be considered fully-connected (and hence elements above the value will only be face connected), or vice-versa. (See notes below for details.)
Indicates whether the output contours will produce positively-oriented polygons around islands of low- or high-valued elements. If ‘low’ then contours will wind counter- clockwise around elements below the iso-value. Alternately, this means that low-valued elements are always on the left of the contour. (See below for details.)
A boolean mask, True where we want to draw contours. Note that NaN values are always excluded from the considered region (mask is set to False wherever array is NaN).
Each contour is an ndarray of shape (n, 2), consisting of n (row, column) coordinates along the contour.
See also
The marching squares algorithm is a special case of the marching cubes algorithm [1]. A simple explanation is available here:
http://users.polytech.unice.fr/~lingrand/MarchingCubes/algo.html
There is a single ambiguous case in the marching squares algorithm: when a given 2 x 2-element square has two high-valued and two low-valued elements, each pair diagonally adjacent. (Where high- and low-valued is with respect to the contour value sought.) In this case, either the high-valued elements can be ‘connected together’ via a thin isthmus that separates the low-valued elements, or vice-versa. When elements are connected together across a diagonal, they are considered ‘fully connected’ (also known as ‘face+vertex-connected’ or ‘8-connected’). Only high-valued or low-valued elements can be fully-connected, the other set will be considered as ‘face-connected’ or ‘4-connected’. By default, low-valued elements are considered fully-connected; this can be altered with the ‘fully_connected’ parameter.
Output contours are not guaranteed to be closed: contours which intersect the array edge or a masked-off region (either where mask is False or where array is NaN) will be left open. All other contours will be closed. (The closed-ness of a contours can be tested by checking whether the beginning point is the same as the end point.)
Contours are oriented. By default, array values lower than the contour value are to the left of the contour and values greater than the contour value are to the right. This means that contours will wind counter-clockwise (i.e. in ‘positive orientation’) around islands of low-valued pixels. This behavior can be altered with the ‘positive_orientation’ parameter.
The order of the contours in the output list is determined by the position of the smallest x,y (in lexicographical order) coordinate in the contour. This is a side-effect of how the input array is traversed, but can be relied upon.
Warning
Array coordinates/values are assumed to refer to the center of the array element. Take a simple example input: [0, 1]. The interpolated position of 0.5 in this array is midway between the 0-element (at x=0) and the 1-element (at x=1), and thus would fall at x=0.5.
This means that to find reasonable contours, it is best to find contours midway between the expected “light” and “dark” values. In particular, given a binarized array, do not choose to find contours at the low or high value of the array. This will often yield degenerate contours, especially around structures that are a single array element wide. Instead choose a middle value, as above.
Lorensen, William and Harvey E. Cline. Marching Cubes: A High Resolution 3D Surface Construction Algorithm. Computer Graphics (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). DOI:10.1145/37401.37422
Contour finding
Measure region properties
Test whether points on a specified grid are inside a polygon.
For each (r, c) coordinate on a grid, i.e. (0, 0), (0, 1) etc., test whether that point lies inside a polygon.
Shape of the grid.
Specify the V vertices of the polygon, sorted either clockwise or anti-clockwise. The first point may (but does not need to be) duplicated.
True where the grid falls inside the polygon.
See also
Compute the inertia tensor of the input image.
The input image.
The pre-computed central moments of image. The inertia tensor computation requires the central moments of the image. If an application requires both the central moments and the inertia tensor (for example, skimage.measure.regionprops), then it is more efficient to pre-compute them and pass them to the inertia tensor call.
The inertia tensor of the input image. \(T_{i, j}\) contains the covariance of image intensity along axes \(i\) and \(j\).
https://en.wikipedia.org/wiki/Moment_of_inertia#Inertia_tensor
Bernd Jähne. Spatio-Temporal Image Processing: Theory and Scientific Applications. (Chapter 8: Tensor Methods) Springer, 1993.
Compute the eigenvalues of the inertia tensor of the image.
The inertia tensor measures covariance of the image intensity along the image axes. (See inertia_tensor.) The relative magnitude of the eigenvalues of the tensor is thus a measure of the elongation of a (bright) object in the image.
The input image.
The pre-computed central moments of image.
The pre-computed inertia tensor. If T is given, mu and image are ignored.
The eigenvalues of the inertia tensor of image, in descending order.
Computing the eigenvalues requires the inertia tensor of the input image. This is much faster if the central moments (mu) are provided, or, alternatively, one can provide the inertia tensor (T) directly.
Label connected regions of an integer array.
Two pixels are connected when they are neighbors and have the same value. In 2D, they can be neighbors either in a 1- or 2-connected sense. The value refers to the maximum number of orthogonal hops to consider a pixel/voxel a neighbor:
Image to label.
Consider all pixels with this value as background pixels, and label them as 0. By default, 0-valued pixels are considered as background pixels.
Whether to return the number of assigned labels.
Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If None, a full connectivity of input.ndim is used.
Labeled array, where all connected regions are assigned the same integer value.
Number of labels, which equals the maximum label index and is only returned if return_num is True.
See also
Christophe Fiorio and Jens Gustedt, “Two linear time Union-Find strategies for image processing”, Theoretical Computer Science 154 (1996), pp. 165-181.
Kensheng Wu, Ekow Otoo and Arie Shoshani, “Optimizing connected component labeling algorithms”, Paper LBNL-56864, 2005, Lawrence Berkeley National Laboratory (University of California), http://repositories.cdlib.org/lbnl/LBNL-56864
Measure region properties
Euler number
Segment human cells (in mitosis)
Marching cubes algorithm to find surfaces in 3d volumetric data.
In contrast with Lorensen et al. approach [2], Lewiner et al. algorithm is faster, resolves ambiguities, and guarantees topologically correct results. Therefore, this algorithm generally a better choice.
Input data volume to find isosurfaces. Will internally be converted to float32 if necessary.
Contour value to search for isosurfaces in volume. If not given or None, the average of the min and max of vol is used.
Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in volume.
Controls if the mesh was generated from an isosurface with gradient descent toward objects of interest (the default), or the opposite, considering the left-hand rule. The two options are: * descent : Object was greater than exterior * ascent : Exterior was greater than object
Step size in voxels. Default 1. Larger steps yield faster but coarser results. The result will always be topologically correct though.
Whether to allow degenerate (i.e. zero-area) triangles in the end-result. Default True. If False, degenerate triangles are removed, at the cost of making the algorithm slower.
One of ‘lewiner’, ‘lorensen’ or ‘_lorensen’. Specify witch of Lewiner et al. or Lorensen et al. method will be used. The ‘_lorensen’ flag correspond to an old implementation that will be deprecated in version 0.19.
Boolean array. The marching cube algorithm will be computed only on True elements. This will save computational time when interfaces are located within certain region of the volume M, N, P-e.g. the top half of the cube-and also allow to compute finite surfaces-i.e. open surfaces that do not end at the border of the cube.
Spatial coordinates for V unique mesh vertices. Coordinate order matches input volume (M, N, P). If allow_degenerate is set to True, then the presence of degenerate triangles in the mesh can make this array have duplicate vertices.
Define triangular faces via referencing vertex indices from verts. This algorithm specifically outputs triangles, so each face has exactly three indices.
The normal direction at each vertex, as calculated from the data.
Gives a measure for the maximum value of the data in the local region near each vertex. This can be used by visualization tools to apply a colormap to the mesh.
See also
The algorithm [1] is an improved version of Chernyaev’s Marching Cubes 33 algorithm. It is an efficient algorithm that relies on heavy use of lookup tables to handle the many different cases, keeping the algorithm relatively easy. This implementation is written in Cython, ported from Lewiner’s C++ implementation.
To quantify the area of an isosurface generated by this algorithm, pass verts and faces to skimage.measure.mesh_surface_area.
Regarding visualization of algorithm output, to contour a volume named myvolume about the level 0.0, using the mayavi package:
Similarly using the visvis package:
To reduce the number of triangles in the mesh for better performance, see this example using the mayavi package.
Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan Tavares. Efficient implementation of Marching Cubes’ cases with topological guarantees. Journal of Graphics Tools 8(2) pp. 1-15 (december 2003). DOI:10.1080/10867651.2003.10487582
Lorensen, William and Harvey E. Cline. Marching Cubes: A High Resolution 3D Surface Construction Algorithm. Computer Graphics (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). DOI:10.1145/37401.37422
Classic marching cubes algorithm to find surfaces in 3d volumetric data.
Note that the marching_cubes() algorithm is recommended over this algorithm, because it’s faster and produces better results.
Input data volume to find isosurfaces. Will be cast to np.float64.
Contour value to search for isosurfaces in volume. If not given or None, the average of the min and max of vol is used.
Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in volume.
Controls if the mesh was generated from an isosurface with gradient descent toward objects of interest (the default), or the opposite. The two options are: * descent : Object was greater than exterior * ascent : Exterior was greater than object
Spatial coordinates for V unique mesh vertices. Coordinate order matches input volume (M, N, P). If allow_degenerate is set to True, then the presence of degenerate triangles in the mesh can make this array have duplicate vertices.
Define triangular faces via referencing vertex indices from verts. This algorithm specifically outputs triangles, so each face has exactly three indices.
See also
The marching cubes algorithm is implemented as described in [1]. A simple explanation is available here:
There are several known ambiguous cases in the marching cubes algorithm. Using point labeling as in [1], Figure 4, as shown:
Most notably, if v4, v8, v2, and v6 are all >= level (or any generalization of this case) two parallel planes are generated by this algorithm, separating v4 and v8 from v2 and v6. An equally valid interpretation would be a single connected thin surface enclosing all four points. This is the best known ambiguity, though there are others.
This algorithm does not attempt to resolve such ambiguities; it is a naive implementation of marching cubes as in [1], but may be a good beginning for work with more recent techniques (Dual Marching Cubes, Extended Marching Cubes, Cubic Marching Squares, etc.).
Because of interactions between neighboring cubes, the isosurface(s) generated by this algorithm are NOT guaranteed to be closed, particularly for complicated contours. Furthermore, this algorithm does not guarantee a single contour will be returned. Indeed, ALL isosurfaces which cross level will be found, regardless of connectivity.
The output is a triangular mesh consisting of a set of unique vertices and connecting triangles. The order of these vertices and triangles in the output list is determined by the position of the smallest x,y,z (in lexicographical order) coordinate in the contour. This is a side-effect of how the input array is traversed, but can be relied upon.
The generated mesh guarantees coherent orientation as of version 0.12.
To quantify the area of an isosurface generated by this algorithm, pass outputs directly into skimage.measure.mesh_surface_area.
Lorensen, William and Harvey E. Cline. Marching Cubes: A High Resolution 3D Surface Construction Algorithm. Computer Graphics (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). DOI:10.1145/37401.37422
Lewiner marching cubes algorithm to find surfaces in 3d volumetric data.
In contrast to marching_cubes_classic(), this algorithm is faster, resolves ambiguities, and guarantees topologically correct results. Therefore, this algorithm generally a better choice, unless there is a specific need for the classic algorithm.
Input data volume to find isosurfaces. Will internally be converted to float32 if necessary.
Contour value to search for isosurfaces in volume. If not given or None, the average of the min and max of vol is used.
Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in volume.
Controls if the mesh was generated from an isosurface with gradient descent toward objects of interest (the default), or the opposite, considering the left-hand rule. The two options are: * descent : Object was greater than exterior * ascent : Exterior was greater than object
Step size in voxels. Default 1. Larger steps yield faster but coarser results. The result will always be topologically correct though.
Whether to allow degenerate (i.e. zero-area) triangles in the end-result. Default True. If False, degenerate triangles are removed, at the cost of making the algorithm slower.
If given and True, the classic marching cubes by Lorensen (1987) is used. This option is included for reference purposes. Note that this algorithm has ambiguities and is not guaranteed to produce a topologically correct result. The results with using this option are not generally the same as the marching_cubes_classic() function.
Boolean array. The marching cube algorithm will be computed only on True elements. This will save computational time when interfaces are located within certain region of the volume M, N, P-e.g. the top half of the cube-and also allow to compute finite surfaces-i.e. open surfaces that do not end at the border of the cube.
Spatial coordinates for V unique mesh vertices. Coordinate order matches input volume (M, N, P). If allow_degenerate is set to True, then the presence of degenerate triangles in the mesh can make this array have duplicate vertices.
Define triangular faces via referencing vertex indices from verts. This algorithm specifically outputs triangles, so each face has exactly three indices.
The normal direction at each vertex, as calculated from the data.
Gives a measure for the maximum value of the data in the local region near each vertex. This can be used by visualization tools to apply a colormap to the mesh.
See also
The algorithm [1] is an improved version of Chernyaev’s Marching Cubes 33 algorithm. It is an efficient algorithm that relies on heavy use of lookup tables to handle the many different cases, keeping the algorithm relatively easy. This implementation is written in Cython, ported from Lewiner’s C++ implementation.
To quantify the area of an isosurface generated by this algorithm, pass verts and faces to skimage.measure.mesh_surface_area.
Regarding visualization of algorithm output, to contour a volume named myvolume about the level 0.0, using the mayavi package:
Similarly using the visvis package:
Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan Tavares. Efficient implementation of Marching Cubes’ cases with topological guarantees. Journal of Graphics Tools 8(2) pp. 1-15 (december 2003). DOI:10.1080/10867651.2003.10487582
Compute surface area, given vertices & triangular faces
Array containing (x, y, z) coordinates for V unique mesh vertices.
List of length-3 lists of integers, referencing vertex coordinates as provided in verts
Surface area of mesh. Units now [coordinate units] ** 2.
See also
The arguments expected by this function are the first two outputs from skimage.measure.marching_cubes. For unit correct output, ensure correct spacing was passed to skimage.measure.marching_cubes.
This algorithm works properly only if the faces provided are all triangles.
Calculate all raw image moments up to a certain order.
Note that raw moments are neither translation, scale nor rotation invariant.
Rasterized shape as image.
Maximum order of moments. Default is 3.
Raw image moments.
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
https://en.wikipedia.org/wiki/Image_moment
Calculate all central image moments up to a certain order.
The center coordinates (cr, cc) can be calculated from the raw moments as: {M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]}.
Note that central moments are translation invariant but not scale and rotation invariant.
Rasterized shape as image.
Coordinates of the image centroid. This will be computed if it is not provided.
The maximum order of moments computed.
Central image moments.
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
https://en.wikipedia.org/wiki/Image_moment
Calculate all raw image moments up to a certain order.
Note that raw moments are neither translation, scale nor rotation invariant.
Array of N points that describe an image of D dimensionality in Cartesian space.
Maximum order of moments. Default is 3.
Raw image moments. (D dimensions)
Johannes Kilian. Simple Image Analysis By Moments. Durham University, version 0.2, Durham, 2001.
Calculate all central image moments up to a certain order.
Note that raw moments are neither translation, scale nor rotation invariant.
Array of N points that describe an image of D dimensionality in Cartesian space. A tuple of coordinates as returned by np.nonzero is also accepted as input.
Coordinates of the image centroid. This will be computed if it is not provided.
Maximum order of moments. Default is 3.
Central image moments. (D dimensions)
Johannes Kilian. Simple Image Analysis By Moments. Durham University, version 0.2, Durham, 2001.
As seen above, for symmetric objects, odd-order moments (columns 1 and 3, rows 1 and 3) are zero when centered on the centroid, or center of mass, of the object (the default). If we break the symmetry by adding a new point, this no longer holds:
Image moments and central image moments are equivalent (by definition) when the center is (0, 0):
Calculate Hu’s set of image moments (2D-only).
Note that this set of moments is proofed to be translation, scale and rotation invariant.
Normalized central image moments, where M must be >= 4.
Hu’s set of image moments.
M. K. Hu, “Visual Pattern Recognition by Moment Invariants”, IRE Trans. Info. Theory, vol. IT-8, pp. 179-187, 1962
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
https://en.wikipedia.org/wiki/Image_moment
Calculate all normalized central image moments up to a certain order.
Note that normalized central moments are translation and scale invariant but not rotation invariant.
Central image moments, where M must be greater than or equal to order.
Maximum order of moments. Default is 3.
Normalized central image moments.
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
https://en.wikipedia.org/wiki/Image_moment
Calculate total perimeter of all objects in binary image.
2D binary image.
Neighborhood connectivity for border pixel determination. It is used to compute the contour. A higher neighbourhood widens the border on which the perimeter is computed.
Total perimeter of all objects in binary image.
K. Benkrid, D. Crookes. Design and FPGA Implementation of a Perimeter Estimator. The Queen’s University of Belfast. http://www.cs.qub.ac.uk/~d.crookes/webpubs/papers/perimeter.doc
Different perimeters
Calculate total Crofton perimeter of all objects in binary image.
2D image. If image is not binary, all values strictly greater than zero are considered as the object.
Number of directions used to approximate the Crofton perimeter. By default, 4 is used: it should be more accurate than 2. Computation time is the same in both cases.
Total perimeter of all objects in binary image.
This measure is based on Crofton formula [1], which is a measure from integral geometry. It is defined for general curve length evaluation via a double integral along all directions. In a discrete space, 2 or 4 directions give a quite good approximation, 4 being more accurate than 2 for more complex shapes.
Similar to perimeter(), this function returns an approximation of the perimeter in continuous space.
https://en.wikipedia.org/wiki/Crofton_formula
S. Rivollier. Analyse d’image geometrique et morphometrique par diagrammes de forme et voisinages adaptatifs generaux. PhD thesis, 2010. Ecole Nationale Superieure des Mines de Saint-Etienne. https://tel.archives-ouvertes.fr/tel-00560838
Different perimeters
Test whether points lie inside a polygon.
Input points, (x, y).
Vertices of the polygon, sorted either clockwise or anti-clockwise. The first point may (but does not need to be) duplicated.
True if corresponding point is inside the polygon.
See also
Return the intensity profile of an image measured along a scan line.
The image, either grayscale (2D array) or multichannel (3D array, where the final axis contains the channel information).
The coordinates of the start point of the scan line.
The coordinates of the end point of the scan line. The destination point is included in the profile, in contrast to standard numpy indexing.
Width of the scan, perpendicular to the line
The order of the spline interpolation, default is 0 if image.dtype is bool and 1 otherwise. The order has to be in the range 0-5. See skimage.transform.warp for detail.
How to compute any values falling outside of the image.
If mode is ‘constant’, what constant value to use outside the image.
Function used to calculate the aggregation of pixel values perpendicular to the profile_line direction when linewidth > 1. If set to None the unreduced array will be returned.
The intensity profile along the scan line. The length of the profile is the ceil of the computed length of the scan line.
The destination point is included in the profile, in contrast to standard numpy indexing. For example:
For different reduce_func inputs:
The unreduced array will be returned when reduce_func is None or when reduce_func acts on each pixel value individually.
Fit a model to data with the RANSAC (random sample consensus) algorithm.
RANSAC is an iterative algorithm for the robust estimation of parameters from a subset of inliers from the complete data set. Each iteration performs the following tasks:
These steps are performed either a maximum number of times or until one of the special stop criteria are met. The final model is estimated using all inlier samples of the previously determined best model.
Data set to which the model is fitted, where N is the number of data points and the remaining dimension are depending on model requirements. If the model class requires multiple input data arrays (e.g. source and destination coordinates of skimage.transform.AffineTransform), they can be optionally passed as tuple or list. Note, that in this case the functions estimate(*data), residuals(*data), is_model_valid(model, *random_data) and is_data_valid(*random_data) must all take each data array as separate arguments.
Object with the following object methods:
where success indicates whether the model estimation succeeded (True or None for success, False for failure).
The minimum number of data points to fit a model to.
Maximum distance for a data point to be classified as an inlier.
This function is called with the randomly selected data before the model is fitted to it: is_data_valid(*random_data).
This function is called with the estimated model and the randomly selected data: is_model_valid(model, *random_data), .
Maximum number of iterations for random sample selection.
Stop iteration if at least this number of inliers are found.
Stop iteration if sum of residuals is less than or equal to this threshold.
RANSAC iteration stops if at least one outlier-free set of the training data is sampled with probability >= stop_probability, depending on the current best model’s inlier ratio and the number of trials. This requires to generate at least N samples (trials):
N >= log(1 - probability) / log(1 - e**m)
where the probability (confidence) is typically set to a high value such as 0.99, e is the current fraction of inliers w.r.t. the total number of samples, and m is the min_samples value.
If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random.
Initial samples selection for model estimation
Best model with largest consensus set.
Boolean mask of inliers classified as True.
“RANSAC”, Wikipedia, https://en.wikipedia.org/wiki/RANSAC
Generate ellipse data without tilt and add noise:
Add some faulty data:
Estimate ellipse model using all available data:
Estimate ellipse model using RANSAC:
RANSAC can be used to robustly estimate a geometric transformation. In this section, we also show how to use a proportion of the total samples, rather than an absolute number.
Measure properties of labeled image regions.
Labeled input image. Labels with value 0 are ignored.
Changed in version 0.14.1: Previously, label_image was processed by numpy.squeeze and so any number of singleton dimensions was allowed. This resulted in inconsistent handling of images with singleton dimensions. To recover the old behaviour, use regionprops(np.squeeze(label_image), ...).
Intensity (i.e., input) image with same size as labeled image, plus optionally an extra dimension for multichannel data. Default is None.
Changed in version 0.18.0: The ability to provide an extra dimension for channels was added.
Determine whether to cache calculated properties. The computation is much faster for cached properties, whereas the memory consumption increases.
This argument is deprecated and will be removed in a future version of scikit-image.
See Coordinate conventions for more details.
Deprecated since version 0.16.0: Use “rc” coordinates everywhere. It may be sufficient to call numpy.transpose on your label image to get the same values as 0.15 and earlier. However, for some properties, the transformation will be less trivial. For example, the new orientation is \(\frac{\pi}{2}\) plus the old orientation.
Add extra property computation functions that are not included with skimage. The name of the property is derived from the function name, the dtype is inferred by calling the function on a small sample. If the name of an extra property clashes with the name of an existing property the extra property wil not be visible and a UserWarning is issued. A property computation function must take a region mask as its first argument. If the property requires an intensity image, it must accept the intensity image as the second argument.
Each item describes one labeled region, and can be accessed using the attributes listed below.
See also
The following properties can be accessed as attributes or keys:
Number of pixels of the region.
Bounding box (min_row, min_col, max_row, max_col). Pixels belonging to the bounding box are in the half-open interval [min_row; max_row) and [min_col; max_col).
Number of pixels of bounding box.
Centroid coordinate tuple (row, col).
Number of pixels of convex hull image, which is the smallest convex polygon that encloses the region.
Binary convex hull image which has the same size as bounding box.
Coordinate list (row, col) of the region.
Eccentricity of the ellipse that has the same second-moments as the region. The eccentricity is the ratio of the focal distance (distance between focal points) over the major axis length. The value is in the interval [0, 1). When it is 0, the ellipse becomes a circle.
The diameter of a circle with the same area as the region.
Euler characteristic of the set of non-zero pixels. Computed as number of connected components subtracted by number of holes (input.ndim connectivity). In 3D, number of connected components plus number of holes subtracted by number of tunnels.
Ratio of pixels in the region to pixels in the total bounding box. Computed as area / (rows * cols)
Maximum Feret’s diameter computed as the longest distance between points around a region’s convex hull contour as determined by find_contours. [5]
Number of pixels of the region will all the holes filled in. Describes the area of the filled_image.
Binary region image with filled holes which has the same size as bounding box.
Sliced binary region image which has the same size as bounding box.
Inertia tensor of the region for the rotation around its mass.
The eigenvalues of the inertia tensor in decreasing order.
Image inside region bounding box.
The label in the labeled input image.
Centroid coordinate tuple (row, col), relative to region bounding box.
The length of the major axis of the ellipse that has the same normalized second central moments as the region.
Value with the greatest intensity in the region.
Value with the mean intensity in the region.
Value with the least intensity in the region.
The length of the minor axis of the ellipse that has the same normalized second central moments as the region.
Spatial moments up to 3rd order:
where the sum is over the row, col coordinates of the region.
Central moments (translation invariant) up to 3rd order:
where the sum is over the row, col coordinates of the region, and row_c and col_c are the coordinates of the region’s centroid.
Hu moments (translation, scale and rotation invariant).
Normalized moments (translation and scale invariant) up to 3rd order:
where m_00 is the zeroth spatial moment.
Angle between the 0th axis (rows) and the major axis of the ellipse that has the same second moments as the region, ranging from -pi/2 to pi/2 counter-clockwise.
Perimeter of object which approximates the contour as a line through the centers of border pixels using a 4-connectivity.
Perimeter of object approximated by the Crofton formula in 4 directions.
A slice to extract the object from the source image.
Ratio of pixels in the region to pixels of the convex hull image.
Centroid coordinate tuple (row, col) weighted with intensity image.
Centroid coordinate tuple (row, col), relative to region bounding box, weighted with intensity image.
Spatial moments of intensity image up to 3rd order:
where the sum is over the row, col coordinates of the region.
Central moments (translation invariant) of intensity image up to 3rd order:
where the sum is over the row, col coordinates of the region, and row_c and col_c are the coordinates of the region’s weighted centroid.
Hu moments (translation, scale and rotation invariant) of intensity image.
Normalized moments (translation and scale invariant) of intensity image up to 3rd order:
where wm_00 is the zeroth spatial moment (intensity-weighted area).
Each region also supports iteration, so that you can do:
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
https://en.wikipedia.org/wiki/Image_moment
W. Pabst, E. Gregorová. Characterization of particles and particle systems, pp. 27-28. ICT Prague, 2007. https://old.vscht.cz/sil/keramika/Characterization_of_particles/CPPS%20_English%20version_.pdf
Add custom measurements by passing functions as extra_properties
Measure region properties
Compute image properties and return them as a pandas-compatible table.
The table is a dictionary mapping column names to value arrays. See Notes section below for details.
New in version 0.16.
Labeled input image. Labels with value 0 are ignored.
Intensity (i.e., input) image with same size as labeled image, plus optionally an extra dimension for multichannel data. Default is None.
Changed in version 0.18.0: The ability to provide an extra dimension for channels was added.
Properties that will be included in the resulting dictionary For a list of available properties, please see regionprops(). Users should remember to add “label” to keep track of region identities.
Determine whether to cache calculated properties. The computation is much faster for cached properties, whereas the memory consumption increases.
For non-scalar properties not listed in OBJECT_COLUMNS, each element will appear in its own column, with the index of that element separated from the property name by this separator. For example, the inertia tensor of a 2D region will appear in four columns: inertia_tensor-0-0, inertia_tensor-0-1, inertia_tensor-1-0, and inertia_tensor-1-1 (where the separator is -).
Object columns are those that cannot be split in this way because the number of columns would change depending on the object. For example, image and coords.
Add extra property computation functions that are not included with skimage. The name of the property is derived from the function name, the dtype is inferred by calling the function on a small sample. If the name of an extra property clashes with the name of an existing property the extra property wil not be visible and a UserWarning is issued. A property computation function must take a region mask as its first argument. If the property requires an intensity image, it must accept the intensity image as the second argument.
Dictionary mapping property names to an array of values of that property, one value per region. This dictionary can be used as input to pandas DataFrame to map property names to columns in the frame and regions to rows. If the image has no regions, the arrays will have length 0, but the correct type.
Each column contains either a scalar property, an object property, or an element in a multidimensional array.
Properties with scalar values for each region, such as “eccentricity”, will appear as a float or int array with that property name as key.
Multidimensional properties of fixed size for a given image dimension, such as “centroid” (every centroid will have three elements in a 3D image, no matter the region size), will be split into that many columns, with the name {property_name}{separator}{element_num} (for 1D properties), {property_name}{separator}{elem_num0}{separator}{elem_num1} (for 2D properties), and so on.
For multidimensional properties that don’t have a fixed size, such as “image” (the image of a region varies in size depending on the region size), an object array will be used, with the corresponding property name as the key.
The resulting dictionary can be directly passed to pandas, if installed, to obtain a clean DataFrame:
[5 rows x 7 columns]
If we want to measure a feature that does not come as a built-in property, we can define custom functions and pass them as extra_properties. For example, we can create a custom function that measures the intensity quartiles in a region:
Measure region properties
Calculate the Shannon entropy of an image.
The Shannon entropy is defined as S = -sum(pk * log(pk)), where pk are frequency/probability of pixels of value k.
Grayscale input image.
The logarithmic base to use.
The returned value is measured in bits or shannon (Sh) for base=2, natural unit (nat) for base=np.e and hartley (Hart) for base=10.
https://en.wikipedia.org/wiki/Entropy_(information_theory)
https://en.wiktionary.org/wiki/Shannon_entropy
Subdivision of polygonal curves using B-Splines.
Note that the resulting curve is always within the convex hull of the original polygon. Circular polygons stay closed after subdivision.
Coordinate array.
Degree of B-Spline. Default is 2.
Preserve first and last coordinate of non-circular polygon. Default is False.
Subdivided coordinate array.
http://mrl.nyu.edu/publications/subdiv-course2000/coursenotes00.pdf
Bases: skimage.measure.fit.BaseModel
Total least squares estimator for 2D circles.
The functional model of the circle is:
This estimator minimizes the squared distances from all points to the circle:
A minimum number of 3 points is required to solve for the parameters.
Circle model parameters in the following order xc, yc, r.
Initialize self. See help(type(self)) for accurate signature.
Estimate circle model from data using total least squares.
N points with (x, y) coordinates, respectively.
True, if model estimation succeeds.
Predict x- and y-coordinates using the estimated model.
Angles in circle in radians. Angles start to count from positive x-axis to positive y-axis in a right-handed system.
Optional custom parameter set.
Predicted x- and y-coordinates.
Determine residuals of data to model.
For each point the shortest distance to the circle is returned.
N points with (x, y) coordinates, respectively.
Residual for each data point.
Bases: skimage.measure.fit.BaseModel
Total least squares estimator for 2D ellipses.
The functional model of the ellipse is:
where (xt, yt) is the closest point on the ellipse to (x, y). Thus d is the shortest distance from the point to the ellipse.
The estimator is based on a least squares minimization. The optimal solution is computed directly, no iterations are required. This leads to a simple, stable and robust fitting method.
The params attribute contains the parameters in the following order:
Ellipse model parameters in the following order xc, yc, a, b, theta.
Initialize self. See help(type(self)) for accurate signature.
Estimate circle model from data using total least squares.
N points with (x, y) coordinates, respectively.
True, if model estimation succeeds.
Halir, R.; Flusser, J. “Numerically stable direct least squares fitting of ellipses”. In Proc. 6th International Conference in Central Europe on Computer Graphics and Visualization. WSCG (Vol. 98, pp. 125-132).
Predict x- and y-coordinates using the estimated model.
Angles in circle in radians. Angles start to count from positive x-axis to positive y-axis in a right-handed system.
Optional custom parameter set.
Predicted x- and y-coordinates.
Determine residuals of data to model.
For each point the shortest distance to the ellipse is returned.
N points with (x, y) coordinates, respectively.
Residual for each data point.
Bases: skimage.measure.fit.BaseModel
Total least squares estimator for N-dimensional lines.
In contrast to ordinary least squares line estimation, this estimator minimizes the orthogonal distances of points to the estimated line.
Lines are defined by a point (origin) and a unit vector (direction) according to the following vector equation:
Line model parameters in the following order origin, direction.
Initialize self. See help(type(self)) for accurate signature.
Estimate line model from data.
This minimizes the sum of shortest (orthogonal) distances from the given data points to the estimated line.
N points in a space of dimensionality dim >= 2.
True, if model estimation succeeds.
Predict intersection of the estimated line model with a hyperplane orthogonal to a given axis.
Coordinates along an axis.
Axis orthogonal to the hyperplane intersecting the line.
Optional custom parameter set in the form (origin, direction).
Predicted coordinates.
If the line is parallel to the given axis.
Predict x-coordinates for 2D lines using the estimated model.
Alias for:
y-coordinates.
Optional custom parameter set in the form (origin, direction).
Predicted x-coordinates.
Predict y-coordinates for 2D lines using the estimated model.
Alias for:
x-coordinates.
Optional custom parameter set in the form (origin, direction).
Predicted y-coordinates.
Determine residuals of data to model.
For each point, the shortest (orthogonal) distance to the line is returned. It is obtained by projecting the data onto the line.
N points in a space of dimension dim.
Optional custom parameter set in the form (origin, direction).
Residual for each data point.


Approximate a polygonal chain with the specified tolerance.
It is based on the Douglas-Peucker algorithm.
Note that the approximated polygon is always within the convex hull of the original polygon.
Coordinate array.
Maximum distance from original points of polygon to approximated polygonal chain. If tolerance is 0, the original coordinate array is returned.
Approximated polygonal chain where M <= N.
https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm


Downsample image by applying function func to local blocks.
This function is useful for max and mean pooling, for example.
N-dimensional input image.
Array containing down-sampling integer factor along each axis.
Function object which is used to calculate the return value for each local block. This function must implement an axis parameter. Primary functions are numpy.sum, numpy.min, numpy.max, numpy.mean and numpy.median. See also func_kwargs.
Constant padding value if image is not perfectly divisible by the block size.
Keyword arguments passed to func. Notably useful for passing dtype argument to np.mean. Takes dictionary of inputs, e.g.: func_kwargs={'dtype': np.float16}).
Down-sampled image with same number of dimensions as input image.


Bases: skimage.measure.fit.BaseModel
Total least squares estimator for 2D circles.
The functional model of the circle is:
This estimator minimizes the squared distances from all points to the circle:
A minimum number of 3 points is required to solve for the parameters.
Circle model parameters in the following order xc, yc, r.
Initialize self. See help(type(self)) for accurate signature.
Estimate circle model from data using total least squares.
N points with (x, y) coordinates, respectively.
True, if model estimation succeeds.
Predict x- and y-coordinates using the estimated model.
Angles in circle in radians. Angles start to count from positive x-axis to positive y-axis in a right-handed system.
Optional custom parameter set.
Predicted x- and y-coordinates.
Determine residuals of data to model.
For each point the shortest distance to the circle is returned.
N points with (x, y) coordinates, respectively.
Residual for each data point.


Estimate circle model from data using total least squares.
N points with (x, y) coordinates, respectively.
True, if model estimation succeeds.


Predict x- and y-coordinates using the estimated model.
Angles in circle in radians. Angles start to count from positive x-axis to positive y-axis in a right-handed system.
Optional custom parameter set.
Predicted x- and y-coordinates.


Determine residuals of data to model.
For each point the shortest distance to the circle is returned.
N points with (x, y) coordinates, respectively.
Residual for each data point.


Initialize self. See help(type(self)) for accurate signature.


Bases: skimage.measure.fit.BaseModel
Total least squares estimator for 2D ellipses.
The functional model of the ellipse is:
where (xt, yt) is the closest point on the ellipse to (x, y). Thus d is the shortest distance from the point to the ellipse.
The estimator is based on a least squares minimization. The optimal solution is computed directly, no iterations are required. This leads to a simple, stable and robust fitting method.
The params attribute contains the parameters in the following order:
Ellipse model parameters in the following order xc, yc, a, b, theta.
Initialize self. See help(type(self)) for accurate signature.
Estimate circle model from data using total least squares.
N points with (x, y) coordinates, respectively.
True, if model estimation succeeds.
Halir, R.; Flusser, J. “Numerically stable direct least squares fitting of ellipses”. In Proc. 6th International Conference in Central Europe on Computer Graphics and Visualization. WSCG (Vol. 98, pp. 125-132).
Predict x- and y-coordinates using the estimated model.
Angles in circle in radians. Angles start to count from positive x-axis to positive y-axis in a right-handed system.
Optional custom parameter set.
Predicted x- and y-coordinates.
Determine residuals of data to model.
For each point the shortest distance to the ellipse is returned.
N points with (x, y) coordinates, respectively.
Residual for each data point.


Estimate circle model from data using total least squares.
N points with (x, y) coordinates, respectively.
True, if model estimation succeeds.
Halir, R.; Flusser, J. “Numerically stable direct least squares fitting of ellipses”. In Proc. 6th International Conference in Central Europe on Computer Graphics and Visualization. WSCG (Vol. 98, pp. 125-132).


Determine residuals of data to model.
For each point the shortest distance to the ellipse is returned.
N points with (x, y) coordinates, respectively.
Residual for each data point.


Calculate the Euler characteristic in binary image.
For 2D objects, the Euler number is the number of objects minus the number of holes. For 3D objects, the Euler number is obtained as the number of objects plus the number of holes, minus the number of tunnels, or loops.
2D or 3D images. If image is not binary, all values strictly greater than zero are considered as the object.
Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If None, a full connectivity of input.ndim is used. 4 or 8 neighborhoods are defined for 2D images (connectivity 1 and 2, respectively). 6 or 26 neighborhoods are defined for 3D images, (connectivity 1 and 3, respectively). Connectivity 2 is not defined.
Euler characteristic of the set of all objects in the image.
The Euler characteristic is an integer number that describes the topology of the set of all objects in the input image. If object is 4-connected, then background is 8-connected, and conversely.
The computation of the Euler characteristic is based on an integral geometry formula in discretized space. In practice, a neighbourhood configuration is constructed, and a LUT is applied for each configuration. The coefficients used are the ones of Ohser et al.
It can be useful to compute the Euler characteristic for several connectivities. A large relative difference between results for different connectivities suggests that the image resolution (with respect to the size of objects and holes) is too low.
S. Rivollier. Analyse d’image geometrique et morphometrique par diagrammes de forme et voisinages adaptatifs generaux. PhD thesis, 2010. Ecole Nationale Superieure des Mines de Saint-Etienne. https://tel.archives-ouvertes.fr/tel-00560838
Ohser J., Nagel W., Schladitz K. (2002) The Euler Number of Discretized Sets - On the Choice of Adjacency in Homogeneous Lattices. In: Mecke K., Stoyan D. (eds) Morphology of Condensed Matter. Lecture Notes in Physics, vol 600. Springer, Berlin, Heidelberg.


Find iso-valued contours in a 2D array for a given level value.
Uses the “marching squares” method to compute a the iso-valued contours of the input 2D array for a particular level value. Array values are linearly interpolated to provide better precision for the output contours.
Input image in which to find contours.
Value along which to find contours in the array. By default, the level is set to (max(image) + min(image)) / 2
Changed in version 0.18: This parameter is now optional.
Indicates whether array elements below the given level value are to be considered fully-connected (and hence elements above the value will only be face connected), or vice-versa. (See notes below for details.)
Indicates whether the output contours will produce positively-oriented polygons around islands of low- or high-valued elements. If ‘low’ then contours will wind counter- clockwise around elements below the iso-value. Alternately, this means that low-valued elements are always on the left of the contour. (See below for details.)
A boolean mask, True where we want to draw contours. Note that NaN values are always excluded from the considered region (mask is set to False wherever array is NaN).
Each contour is an ndarray of shape (n, 2), consisting of n (row, column) coordinates along the contour.
See also
The marching squares algorithm is a special case of the marching cubes algorithm [1]. A simple explanation is available here:
http://users.polytech.unice.fr/~lingrand/MarchingCubes/algo.html
There is a single ambiguous case in the marching squares algorithm: when a given 2 x 2-element square has two high-valued and two low-valued elements, each pair diagonally adjacent. (Where high- and low-valued is with respect to the contour value sought.) In this case, either the high-valued elements can be ‘connected together’ via a thin isthmus that separates the low-valued elements, or vice-versa. When elements are connected together across a diagonal, they are considered ‘fully connected’ (also known as ‘face+vertex-connected’ or ‘8-connected’). Only high-valued or low-valued elements can be fully-connected, the other set will be considered as ‘face-connected’ or ‘4-connected’. By default, low-valued elements are considered fully-connected; this can be altered with the ‘fully_connected’ parameter.
Output contours are not guaranteed to be closed: contours which intersect the array edge or a masked-off region (either where mask is False or where array is NaN) will be left open. All other contours will be closed. (The closed-ness of a contours can be tested by checking whether the beginning point is the same as the end point.)
Contours are oriented. By default, array values lower than the contour value are to the left of the contour and values greater than the contour value are to the right. This means that contours will wind counter-clockwise (i.e. in ‘positive orientation’) around islands of low-valued pixels. This behavior can be altered with the ‘positive_orientation’ parameter.
The order of the contours in the output list is determined by the position of the smallest x,y (in lexicographical order) coordinate in the contour. This is a side-effect of how the input array is traversed, but can be relied upon.
Warning
Array coordinates/values are assumed to refer to the center of the array element. Take a simple example input: [0, 1]. The interpolated position of 0.5 in this array is midway between the 0-element (at x=0) and the 1-element (at x=1), and thus would fall at x=0.5.
This means that to find reasonable contours, it is best to find contours midway between the expected “light” and “dark” values. In particular, given a binarized array, do not choose to find contours at the low or high value of the array. This will often yield degenerate contours, especially around structures that are a single array element wide. Instead choose a middle value, as above.
Lorensen, William and Harvey E. Cline. Marching Cubes: A High Resolution 3D Surface Construction Algorithm. Computer Graphics (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). DOI:10.1145/37401.37422


Test whether points on a specified grid are inside a polygon.
For each (r, c) coordinate on a grid, i.e. (0, 0), (0, 1) etc., test whether that point lies inside a polygon.
Shape of the grid.
Specify the V vertices of the polygon, sorted either clockwise or anti-clockwise. The first point may (but does not need to be) duplicated.
True where the grid falls inside the polygon.
See also


Compute the inertia tensor of the input image.
The input image.
The pre-computed central moments of image. The inertia tensor computation requires the central moments of the image. If an application requires both the central moments and the inertia tensor (for example, skimage.measure.regionprops), then it is more efficient to pre-compute them and pass them to the inertia tensor call.
The inertia tensor of the input image. \(T_{i, j}\) contains the covariance of image intensity along axes \(i\) and \(j\).
https://en.wikipedia.org/wiki/Moment_of_inertia#Inertia_tensor
Bernd Jähne. Spatio-Temporal Image Processing: Theory and Scientific Applications. (Chapter 8: Tensor Methods) Springer, 1993.


Compute the eigenvalues of the inertia tensor of the image.
The inertia tensor measures covariance of the image intensity along the image axes. (See inertia_tensor.) The relative magnitude of the eigenvalues of the tensor is thus a measure of the elongation of a (bright) object in the image.
The input image.
The pre-computed central moments of image.
The pre-computed inertia tensor. If T is given, mu and image are ignored.
The eigenvalues of the inertia tensor of image, in descending order.
Computing the eigenvalues requires the inertia tensor of the input image. This is much faster if the central moments (mu) are provided, or, alternatively, one can provide the inertia tensor (T) directly.


Label connected regions of an integer array.
Two pixels are connected when they are neighbors and have the same value. In 2D, they can be neighbors either in a 1- or 2-connected sense. The value refers to the maximum number of orthogonal hops to consider a pixel/voxel a neighbor:
Image to label.
Consider all pixels with this value as background pixels, and label them as 0. By default, 0-valued pixels are considered as background pixels.
Whether to return the number of assigned labels.
Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If None, a full connectivity of input.ndim is used.
Labeled array, where all connected regions are assigned the same integer value.
Number of labels, which equals the maximum label index and is only returned if return_num is True.
See also
Christophe Fiorio and Jens Gustedt, “Two linear time Union-Find strategies for image processing”, Theoretical Computer Science 154 (1996), pp. 165-181.
Kensheng Wu, Ekow Otoo and Arie Shoshani, “Optimizing connected component labeling algorithms”, Paper LBNL-56864, 2005, Lawrence Berkeley National Laboratory (University of California), http://repositories.cdlib.org/lbnl/LBNL-56864


Bases: skimage.measure.fit.BaseModel
Total least squares estimator for N-dimensional lines.
In contrast to ordinary least squares line estimation, this estimator minimizes the orthogonal distances of points to the estimated line.
Lines are defined by a point (origin) and a unit vector (direction) according to the following vector equation:
Line model parameters in the following order origin, direction.
Initialize self. See help(type(self)) for accurate signature.
Estimate line model from data.
This minimizes the sum of shortest (orthogonal) distances from the given data points to the estimated line.
N points in a space of dimensionality dim >= 2.
True, if model estimation succeeds.
Predict intersection of the estimated line model with a hyperplane orthogonal to a given axis.
Coordinates along an axis.
Axis orthogonal to the hyperplane intersecting the line.
Optional custom parameter set in the form (origin, direction).
Predicted coordinates.
If the line is parallel to the given axis.
Predict x-coordinates for 2D lines using the estimated model.
Alias for:
y-coordinates.
Optional custom parameter set in the form (origin, direction).
Predicted x-coordinates.
Predict y-coordinates for 2D lines using the estimated model.
Alias for:
x-coordinates.
Optional custom parameter set in the form (origin, direction).
Predicted y-coordinates.
Determine residuals of data to model.
For each point, the shortest (orthogonal) distance to the line is returned. It is obtained by projecting the data onto the line.
N points in a space of dimension dim.
Optional custom parameter set in the form (origin, direction).
Residual for each data point.


Estimate line model from data.
This minimizes the sum of shortest (orthogonal) distances from the given data points to the estimated line.
N points in a space of dimensionality dim >= 2.
True, if model estimation succeeds.


Predict intersection of the estimated line model with a hyperplane orthogonal to a given axis.
Coordinates along an axis.
Axis orthogonal to the hyperplane intersecting the line.
Optional custom parameter set in the form (origin, direction).
Predicted coordinates.
If the line is parallel to the given axis.


Predict x-coordinates for 2D lines using the estimated model.
Alias for:
y-coordinates.
Optional custom parameter set in the form (origin, direction).
Predicted x-coordinates.


Predict y-coordinates for 2D lines using the estimated model.
Alias for:
x-coordinates.
Optional custom parameter set in the form (origin, direction).
Predicted y-coordinates.


Determine residuals of data to model.
For each point, the shortest (orthogonal) distance to the line is returned. It is obtained by projecting the data onto the line.
N points in a space of dimension dim.
Optional custom parameter set in the form (origin, direction).
Residual for each data point.


Marching cubes algorithm to find surfaces in 3d volumetric data.
In contrast with Lorensen et al. approach [2], Lewiner et al. algorithm is faster, resolves ambiguities, and guarantees topologically correct results. Therefore, this algorithm generally a better choice.
Input data volume to find isosurfaces. Will internally be converted to float32 if necessary.
Contour value to search for isosurfaces in volume. If not given or None, the average of the min and max of vol is used.
Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in volume.
Controls if the mesh was generated from an isosurface with gradient descent toward objects of interest (the default), or the opposite, considering the left-hand rule. The two options are: * descent : Object was greater than exterior * ascent : Exterior was greater than object
Step size in voxels. Default 1. Larger steps yield faster but coarser results. The result will always be topologically correct though.
Whether to allow degenerate (i.e. zero-area) triangles in the end-result. Default True. If False, degenerate triangles are removed, at the cost of making the algorithm slower.
One of ‘lewiner’, ‘lorensen’ or ‘_lorensen’. Specify witch of Lewiner et al. or Lorensen et al. method will be used. The ‘_lorensen’ flag correspond to an old implementation that will be deprecated in version 0.19.
Boolean array. The marching cube algorithm will be computed only on True elements. This will save computational time when interfaces are located within certain region of the volume M, N, P-e.g. the top half of the cube-and also allow to compute finite surfaces-i.e. open surfaces that do not end at the border of the cube.
Spatial coordinates for V unique mesh vertices. Coordinate order matches input volume (M, N, P). If allow_degenerate is set to True, then the presence of degenerate triangles in the mesh can make this array have duplicate vertices.
Define triangular faces via referencing vertex indices from verts. This algorithm specifically outputs triangles, so each face has exactly three indices.
The normal direction at each vertex, as calculated from the data.
Gives a measure for the maximum value of the data in the local region near each vertex. This can be used by visualization tools to apply a colormap to the mesh.
See also
The algorithm [1] is an improved version of Chernyaev’s Marching Cubes 33 algorithm. It is an efficient algorithm that relies on heavy use of lookup tables to handle the many different cases, keeping the algorithm relatively easy. This implementation is written in Cython, ported from Lewiner’s C++ implementation.
To quantify the area of an isosurface generated by this algorithm, pass verts and faces to skimage.measure.mesh_surface_area.
Regarding visualization of algorithm output, to contour a volume named myvolume about the level 0.0, using the mayavi package:
Similarly using the visvis package:
To reduce the number of triangles in the mesh for better performance, see this example using the mayavi package.
Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan Tavares. Efficient implementation of Marching Cubes’ cases with topological guarantees. Journal of Graphics Tools 8(2) pp. 1-15 (december 2003). DOI:10.1080/10867651.2003.10487582
Lorensen, William and Harvey E. Cline. Marching Cubes: A High Resolution 3D Surface Construction Algorithm. Computer Graphics (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). DOI:10.1145/37401.37422


Classic marching cubes algorithm to find surfaces in 3d volumetric data.
Note that the marching_cubes() algorithm is recommended over this algorithm, because it’s faster and produces better results.
Input data volume to find isosurfaces. Will be cast to np.float64.
Contour value to search for isosurfaces in volume. If not given or None, the average of the min and max of vol is used.
Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in volume.
Controls if the mesh was generated from an isosurface with gradient descent toward objects of interest (the default), or the opposite. The two options are: * descent : Object was greater than exterior * ascent : Exterior was greater than object
Spatial coordinates for V unique mesh vertices. Coordinate order matches input volume (M, N, P). If allow_degenerate is set to True, then the presence of degenerate triangles in the mesh can make this array have duplicate vertices.
Define triangular faces via referencing vertex indices from verts. This algorithm specifically outputs triangles, so each face has exactly three indices.
See also
The marching cubes algorithm is implemented as described in [1]. A simple explanation is available here:
There are several known ambiguous cases in the marching cubes algorithm. Using point labeling as in [1], Figure 4, as shown:
Most notably, if v4, v8, v2, and v6 are all >= level (or any generalization of this case) two parallel planes are generated by this algorithm, separating v4 and v8 from v2 and v6. An equally valid interpretation would be a single connected thin surface enclosing all four points. This is the best known ambiguity, though there are others.
This algorithm does not attempt to resolve such ambiguities; it is a naive implementation of marching cubes as in [1], but may be a good beginning for work with more recent techniques (Dual Marching Cubes, Extended Marching Cubes, Cubic Marching Squares, etc.).
Because of interactions between neighboring cubes, the isosurface(s) generated by this algorithm are NOT guaranteed to be closed, particularly for complicated contours. Furthermore, this algorithm does not guarantee a single contour will be returned. Indeed, ALL isosurfaces which cross level will be found, regardless of connectivity.
The output is a triangular mesh consisting of a set of unique vertices and connecting triangles. The order of these vertices and triangles in the output list is determined by the position of the smallest x,y,z (in lexicographical order) coordinate in the contour. This is a side-effect of how the input array is traversed, but can be relied upon.
The generated mesh guarantees coherent orientation as of version 0.12.
To quantify the area of an isosurface generated by this algorithm, pass outputs directly into skimage.measure.mesh_surface_area.
Lorensen, William and Harvey E. Cline. Marching Cubes: A High Resolution 3D Surface Construction Algorithm. Computer Graphics (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). DOI:10.1145/37401.37422


Lewiner marching cubes algorithm to find surfaces in 3d volumetric data.
In contrast to marching_cubes_classic(), this algorithm is faster, resolves ambiguities, and guarantees topologically correct results. Therefore, this algorithm generally a better choice, unless there is a specific need for the classic algorithm.
Input data volume to find isosurfaces. Will internally be converted to float32 if necessary.
Contour value to search for isosurfaces in volume. If not given or None, the average of the min and max of vol is used.
Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in volume.
Controls if the mesh was generated from an isosurface with gradient descent toward objects of interest (the default), or the opposite, considering the left-hand rule. The two options are: * descent : Object was greater than exterior * ascent : Exterior was greater than object
Step size in voxels. Default 1. Larger steps yield faster but coarser results. The result will always be topologically correct though.
Whether to allow degenerate (i.e. zero-area) triangles in the end-result. Default True. If False, degenerate triangles are removed, at the cost of making the algorithm slower.
If given and True, the classic marching cubes by Lorensen (1987) is used. This option is included for reference purposes. Note that this algorithm has ambiguities and is not guaranteed to produce a topologically correct result. The results with using this option are not generally the same as the marching_cubes_classic() function.
Boolean array. The marching cube algorithm will be computed only on True elements. This will save computational time when interfaces are located within certain region of the volume M, N, P-e.g. the top half of the cube-and also allow to compute finite surfaces-i.e. open surfaces that do not end at the border of the cube.
Spatial coordinates for V unique mesh vertices. Coordinate order matches input volume (M, N, P). If allow_degenerate is set to True, then the presence of degenerate triangles in the mesh can make this array have duplicate vertices.
Define triangular faces via referencing vertex indices from verts. This algorithm specifically outputs triangles, so each face has exactly three indices.
The normal direction at each vertex, as calculated from the data.
Gives a measure for the maximum value of the data in the local region near each vertex. This can be used by visualization tools to apply a colormap to the mesh.
See also
The algorithm [1] is an improved version of Chernyaev’s Marching Cubes 33 algorithm. It is an efficient algorithm that relies on heavy use of lookup tables to handle the many different cases, keeping the algorithm relatively easy. This implementation is written in Cython, ported from Lewiner’s C++ implementation.
To quantify the area of an isosurface generated by this algorithm, pass verts and faces to skimage.measure.mesh_surface_area.
Regarding visualization of algorithm output, to contour a volume named myvolume about the level 0.0, using the mayavi package:
Similarly using the visvis package:
Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan Tavares. Efficient implementation of Marching Cubes’ cases with topological guarantees. Journal of Graphics Tools 8(2) pp. 1-15 (december 2003). DOI:10.1080/10867651.2003.10487582


Compute surface area, given vertices & triangular faces
Array containing (x, y, z) coordinates for V unique mesh vertices.
List of length-3 lists of integers, referencing vertex coordinates as provided in verts
Surface area of mesh. Units now [coordinate units] ** 2.
See also
The arguments expected by this function are the first two outputs from skimage.measure.marching_cubes. For unit correct output, ensure correct spacing was passed to skimage.measure.marching_cubes.
This algorithm works properly only if the faces provided are all triangles.


Calculate all raw image moments up to a certain order.
Note that raw moments are neither translation, scale nor rotation invariant.
Rasterized shape as image.
Maximum order of moments. Default is 3.
Raw image moments.
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
https://en.wikipedia.org/wiki/Image_moment


Calculate all central image moments up to a certain order.
The center coordinates (cr, cc) can be calculated from the raw moments as: {M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]}.
Note that central moments are translation invariant but not scale and rotation invariant.
Rasterized shape as image.
Coordinates of the image centroid. This will be computed if it is not provided.
The maximum order of moments computed.
Central image moments.
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
https://en.wikipedia.org/wiki/Image_moment


Calculate all raw image moments up to a certain order.
Note that raw moments are neither translation, scale nor rotation invariant.
Array of N points that describe an image of D dimensionality in Cartesian space.
Maximum order of moments. Default is 3.
Raw image moments. (D dimensions)
Johannes Kilian. Simple Image Analysis By Moments. Durham University, version 0.2, Durham, 2001.


Calculate all central image moments up to a certain order.
Note that raw moments are neither translation, scale nor rotation invariant.
Array of N points that describe an image of D dimensionality in Cartesian space. A tuple of coordinates as returned by np.nonzero is also accepted as input.
Coordinates of the image centroid. This will be computed if it is not provided.
Maximum order of moments. Default is 3.
Central image moments. (D dimensions)
Johannes Kilian. Simple Image Analysis By Moments. Durham University, version 0.2, Durham, 2001.
As seen above, for symmetric objects, odd-order moments (columns 1 and 3, rows 1 and 3) are zero when centered on the centroid, or center of mass, of the object (the default). If we break the symmetry by adding a new point, this no longer holds:
Image moments and central image moments are equivalent (by definition) when the center is (0, 0):


Calculate Hu’s set of image moments (2D-only).
Note that this set of moments is proofed to be translation, scale and rotation invariant.
Normalized central image moments, where M must be >= 4.
Hu’s set of image moments.
M. K. Hu, “Visual Pattern Recognition by Moment Invariants”, IRE Trans. Info. Theory, vol. IT-8, pp. 179-187, 1962
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
https://en.wikipedia.org/wiki/Image_moment


Calculate all normalized central image moments up to a certain order.
Note that normalized central moments are translation and scale invariant but not rotation invariant.
Central image moments, where M must be greater than or equal to order.
Maximum order of moments. Default is 3.
Normalized central image moments.
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
https://en.wikipedia.org/wiki/Image_moment


Calculate total perimeter of all objects in binary image.
2D binary image.
Neighborhood connectivity for border pixel determination. It is used to compute the contour. A higher neighbourhood widens the border on which the perimeter is computed.
Total perimeter of all objects in binary image.
K. Benkrid, D. Crookes. Design and FPGA Implementation of a Perimeter Estimator. The Queen’s University of Belfast. http://www.cs.qub.ac.uk/~d.crookes/webpubs/papers/perimeter.doc


Calculate total Crofton perimeter of all objects in binary image.
2D image. If image is not binary, all values strictly greater than zero are considered as the object.
Number of directions used to approximate the Crofton perimeter. By default, 4 is used: it should be more accurate than 2. Computation time is the same in both cases.
Total perimeter of all objects in binary image.
This measure is based on Crofton formula [1], which is a measure from integral geometry. It is defined for general curve length evaluation via a double integral along all directions. In a discrete space, 2 or 4 directions give a quite good approximation, 4 being more accurate than 2 for more complex shapes.
Similar to perimeter(), this function returns an approximation of the perimeter in continuous space.
https://en.wikipedia.org/wiki/Crofton_formula
S. Rivollier. Analyse d’image geometrique et morphometrique par diagrammes de forme et voisinages adaptatifs generaux. PhD thesis, 2010. Ecole Nationale Superieure des Mines de Saint-Etienne. https://tel.archives-ouvertes.fr/tel-00560838


Test whether points lie inside a polygon.
Input points, (x, y).
Vertices of the polygon, sorted either clockwise or anti-clockwise. The first point may (but does not need to be) duplicated.
True if corresponding point is inside the polygon.
See also