measure
¶

Find isovalued contours in a 2D array for a given level value. 

Measure properties of labeled image regions. 

Calculate total perimeter of all objects in binary image. 

Approximate a polygonal chain with the specified tolerance. 

Subdivision of polygonal curves using BSplines. 

Fit a model to data with the RANSAC (random sample consensus) algorithm. 

Downsample image by applying function to local blocks. 

Calculate all raw image moments up to a certain order. 

Calculate all central image moments up to a certain order. 

Calculate all raw image moments up to a certain order. 
Calculate all central image moments up to a certain order. 


Calculate all normalized central image moments up to a certain order. 
Calculate Hu’s set of image moments (2Donly). 

Lewiner marching cubes algorithm to find surfaces in 3d volumetric data. 

Classic marching cubes algorithm to find surfaces in 3d volumetric data. 


Compute surface area, given vertices & triangular faces 
Correct orientations of mesh faces. 


Return the intensity profile of an image measured along a scan line. 

Label connected regions of an integer array. 

Test whether points lie inside a polygon. 

Test whether points on a specified grid are inside a polygon. 

Compute the mean structural similarity index between two images. 

Compute the meansquared error between two images. 

Compute the normalized root meansquared error (NRMSE) between two images. 

Compute the peak signal to noise ratio (PSNR) for an image. 

Calculate the Shannon entropy of an image. 
Total least squares estimator for Ndimensional lines. 

Total least squares estimator for 2D circles. 

Total least squares estimator for 2D ellipses. 
skimage.measure.
find_contours
(array, level, fully_connected='low', positive_orientation='low')[source]¶Find isovalued contours in a 2D array for a given level value.
Uses the “marching squares” method to compute a the isovalued 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 data in which to find contours.
Value along which to find contours in the array.
Indicates whether array elements below the given level value are to be considered fullyconnected (and hence elements above the value will only be face connected), or viceversa. (See notes below for details.)
Indicates whether the output contours will produce positivelyoriented polygons around islands of low or highvalued elements. If ‘low’ then contours will wind counter clockwise around elements below the isovalue. Alternately, this means that lowvalued elements are always on the left of the contour. (See below for details.)
Each contour is an ndarray of shape (n, 2)
,
consisting of n (row, column)
coordinates along the contour.
Notes
The marching squares algorithm is a special case of the marching cubes algorithm [1]. A simple explanation is available here:
http://www.essi.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 highvalued and two lowvalued
elements, each pair diagonally adjacent. (Where high and lowvalued is
with respect to the contour value sought.) In this case, either the
highvalued elements can be ‘connected together’ via a thin isthmus that
separates the lowvalued elements, or viceversa. When elements are
connected together across a diagonal, they are considered ‘fully
connected’ (also known as ‘face+vertexconnected’ or ‘8connected’). Only
highvalued or lowvalued elements can be fullyconnected, the other set
will be considered as ‘faceconnected’ or ‘4connected’. By default,
lowvalued elements are considered fullyconnected; this can be altered
with the ‘fully_connected’ parameter.
Output contours are not guaranteed to be closed: contours which intersect the array edge will be left open. All other contours will be closed. (The closedness 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 counterclockwise (i.e. in ‘positive orientation’) around islands of lowvalued 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 sideeffect 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 0element (at
x=0
) and the 1element (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.
References
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. 163170).
Examples
>>> a = np.zeros((3, 3))
>>> a[0, 0] = 1
>>> a
array([[ 1., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
>>> find_contours(a, 0.5)
[array([[ 0. , 0.5],
[ 0.5, 0. ]])]
skimage.measure.
regionprops
(label_image, intensity_image=None, cache=True, coordinates=None)[source]¶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. Default is None.
Determine whether to cache calculated properties. The computation is much faster for cached properties, whereas the memory consumption increases.
Coordinate conventions for 2D images. (Only ‘rc’ coordinates are supported for 3D images.)
Each item describes one labeled region, and can be accessed using the attributes listed below.
See also
Notes
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 halfopen 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 secondmoments 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 region. Computed as number of objects (= 1) subtracted by number of holes (8connectivity).
Ratio of pixels in the region to pixels in the total bounding box.
Computed as area / (rows * cols)
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 two eigen values 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:
m_ji = sum{ array(x, y) * x^j * y^i }
where the sum is over the x, y coordinates of the region.
Central moments (translation invariant) up to 3rd order:
mu_ji = sum{ array(x, y) * (x  x_c)^j * (y  y_c)^i }
where the sum is over the x, y coordinates of the region, and x_c and y_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:
nu_ji = mu_ji / m_00^[(i+j)/2 + 1]
where m_00 is the zeroth spatial moment.
In ‘rc’ coordinates, 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 counterclockwise.
In xy coordinates, as above but the angle is now measured from the “x” or horizontal axis.
Perimeter of object which approximates the contour as a line through the centers of border pixels using a 4connectivity.
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:
wm_ji = sum{ array(x, y) * x^j * y^i }
where the sum is over the x, y coordinates of the region.
Central moments (translation invariant) of intensity image up to 3rd order:
wmu_ji = sum{ array(x, y) * (x  x_c)^j * (y  y_c)^i }
where the sum is over the x, y coordinates of the region, and x_c and y_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:
wnu_ji = wmu_ji / wm_00^[(i+j)/2 + 1]
where wm_00
is the zeroth spatial moment (intensityweighted area).
Each region also supports iteration, so that you can do:
for prop in region:
print(prop, region[prop])
References
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. SpringerVerlag, London, 2009.
B. Jähne. Digital Image Processing. SpringerVerlag, BerlinHeidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
Examples
>>> from skimage import data, util
>>> from skimage.measure import label
>>> img = util.img_as_ubyte(data.coins()) > 110
>>> label_img = label(img, connectivity=img.ndim)
>>> props = regionprops(label_img)
>>> # centroid of first labeled object
>>> props[0].centroid
(22.729879860483141, 81.912285234465827)
>>> # centroid of first labeled object
>>> props[0]['centroid']
(22.729879860483141, 81.912285234465827)
skimage.measure.
perimeter
(image, neighbourhood=4)[source]¶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.
References
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
Examples
>>> from skimage import data, util
>>> from skimage.measure import label
>>> # coins image (binary)
>>> img_coins = data.coins() > 110
>>> # total perimeter of all objects in the image
>>> perimeter(img_coins, neighbourhood=4) # doctest: +ELLIPSIS
7796.867...
>>> perimeter(img_coins, neighbourhood=8) # doctest: +ELLIPSIS
8806.268...
skimage.measure.
approximate_polygon
(coords, tolerance)[source]¶Approximate a polygonal chain with the specified tolerance.
It is based on the DouglasPeucker 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.
References
skimage.measure.approximate_polygon
¶skimage.measure.
subdivide_polygon
(coords, degree=2, preserve_ends=False)[source]¶Subdivision of polygonal curves using BSplines.
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 BSpline. Default is 2.
Preserve first and last coordinate of noncircular polygon. Default is False.
Subdivided coordinate array.
References
skimage.measure.subdivide_polygon
¶skimage.measure.
ransac
(data, model_class, min_samples, residual_threshold, is_data_valid=None, is_model_valid=None, max_trials=100, stop_sample_num=inf, stop_residuals_sum=0, stop_probability=1, random_state=None)[source]¶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:
Select min_samples random samples from the original data and check whether the set of data is valid (see is_data_valid).
Estimate a model to the random subset (model_cls.estimate(*data[random_subset]) and check whether the estimated model is valid (see is_model_valid).
Classify all data as inliers or outliers by calculating the residuals to the estimated model (model_cls.residuals(*data))  all data samples with residuals smaller than the residual_threshold are considered as inliers.
Save estimated model as best model if number of inlier samples is maximal. In case the current estimated model has the same number of inliers, it is only considered as the best model if it has less sum of residuals.
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 D the dimensionality of the data.
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:
success = estimate(*data)
residuals(*data)
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 outlierfree 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, and e is the current fraction of inliers w.r.t. the total number of samples.
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.
Best model with largest consensus set.
Boolean mask of inliers classified as True
.
References
“RANSAC”, Wikipedia, https://en.wikipedia.org/wiki/RANSAC
Examples
Generate ellipse data without tilt and add noise:
>>> t = np.linspace(0, 2 * np.pi, 50)
>>> xc, yc = 20, 30
>>> a, b = 5, 10
>>> x = xc + a * np.cos(t)
>>> y = yc + b * np.sin(t)
>>> data = np.column_stack([x, y])
>>> np.random.seed(seed=1234)
>>> data += np.random.normal(size=data.shape)
Add some faulty data:
>>> data[0] = (100, 100)
>>> data[1] = (110, 120)
>>> data[2] = (120, 130)
>>> data[3] = (140, 130)
Estimate ellipse model using all available data:
>>> model = EllipseModel()
>>> model.estimate(data)
True
>>> np.round(model.params) # doctest: +SKIP
array([ 72., 75., 77., 14., 1.])
Estimate ellipse model using RANSAC:
>>> ransac_model, inliers = ransac(data, EllipseModel, 20, 3, max_trials=50)
>>> abs(np.round(ransac_model.params))
array([ 20., 30., 5., 10., 0.])
>>> inliers # doctest: +SKIP
array([False, False, False, False, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True], dtype=bool)
>>> sum(inliers) > 40
True
Robustly estimate geometric transformation:
>>> from skimage.transform import SimilarityTransform
>>> np.random.seed(0)
>>> src = 100 * np.random.rand(50, 2)
>>> model0 = SimilarityTransform(scale=0.5, rotation=1,
... translation=(10, 20))
>>> dst = model0(src)
>>> dst[0] = (10000, 10000)
>>> dst[1] = (100, 100)
>>> dst[2] = (50, 50)
>>> model, inliers = ransac((src, dst), SimilarityTransform, 2, 10)
>>> inliers
array([False, False, False, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True], dtype=bool)
skimage.measure.
block_reduce
(image, block_size, func=<function sum>, cval=0)[source]¶Downsample image by applying function to local blocks.
Ndimensional input image.
Array containing downsampling 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 such
as numpy.sum
or numpy.min
.
Constant padding value if image is not perfectly divisible by the block size.
Downsampled image with same number of dimensions as input image.
Examples
>>> from skimage.measure import block_reduce
>>> image = np.arange(3*3*4).reshape(3, 3, 4)
>>> image # doctest: +NORMALIZE_WHITESPACE
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]],
[[24, 25, 26, 27],
[28, 29, 30, 31],
[32, 33, 34, 35]]])
>>> block_reduce(image, block_size=(3, 3, 1), func=np.mean)
array([[[ 16., 17., 18., 19.]]])
>>> image_max1 = block_reduce(image, block_size=(1, 3, 4), func=np.max)
>>> image_max1 # doctest: +NORMALIZE_WHITESPACE
array([[[11]],
[[23]],
[[35]]])
>>> image_max2 = block_reduce(image, block_size=(3, 1, 4), func=np.max)
>>> image_max2 # doctest: +NORMALIZE_WHITESPACE
array([[[27],
[31],
[35]]])
skimage.measure.
moments
(image, order=3)[source]¶Calculate all raw image moments up to a certain order.
Area as: M[0, 0]
.
Centroid as: {M[1, 0] / M[0, 0]
, M[0, 1] / M[0, 0]
}.
Note that raw moments are neither translation, scale nor rotation invariant.
Rasterized shape as image.
Maximum order of moments. Default is 3.
order + 1
, order + 1
) arrayRaw image moments.
References
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. SpringerVerlag, London, 2009.
B. Jähne. Digital Image Processing. SpringerVerlag, BerlinHeidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
Examples
>>> image = np.zeros((20, 20), dtype=np.double)
>>> image[13:17, 13:17] = 1
>>> M = moments(image)
>>> cr = M[1, 0] / M[0, 0]
>>> cc = M[0, 1] / M[0, 0]
>>> cr, cc
(14.5, 14.5)
skimage.measure.
moments_central
(image, center=None, cc=None, order=3, **kwargs)[source]¶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.
order + 1
, order + 1
) arrayCentral image moments.
DEPRECATED: Center row coordinate for 2D image.
DEPRECATED: Center column coordinate for 2D image.
References
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. SpringerVerlag, London, 2009.
B. Jähne. Digital Image Processing. SpringerVerlag, BerlinHeidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
Examples
>>> image = np.zeros((20, 20), dtype=np.double)
>>> image[13:17, 13:17] = 1
>>> M = moments(image)
>>> cr = M[1, 0] / M[0, 0]
>>> cc = M[0, 1] / M[0, 0]
>>> moments_central(image, (cr, cc))
array([[ 16., 0., 20., 0.],
[ 0., 0., 0., 0.],
[ 20., 0., 25., 0.],
[ 0., 0., 0., 0.]])
skimage.measure.
moments_coords
(coords, order=3)[source]¶Calculate all raw image moments up to a certain order.
Area as: M[0, 0]
.
Centroid as: {M[1, 0] / M[0, 0]
, M[0, 1] / M[0, 0]
}.
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.
order + 1
, order + 1
, …) arrayRaw image moments. (D dimensions)
References
Johannes Kilian. Simple Image Analysis By Moments. Durham University, version 0.2, Durham, 2001.
Examples
>>> coords = np.array([[row, col]
... for row in range(13, 17)
... for col in range(14, 18)], dtype=np.double)
>>> M = moments_coords(coords)
>>> centroid_row = M[1, 0] / M[0, 0]
>>> centroid_col = M[0, 1] / M[0, 0]
>>> centroid_row, centroid_col
(14.5, 15.5)
skimage.measure.
moments_coords_central
(coords, center=None, order=3)[source]¶Calculate all central image moments up to a certain order.
Area as: M[0, 0]
.
Centroid as: {M[1, 0] / M[0, 0]
, M[0, 1] / M[0, 0]
}.
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.
order + 1
, order + 1
, …) arrayCentral image moments. (D dimensions)
References
Johannes Kilian. Simple Image Analysis By Moments. Durham University, version 0.2, Durham, 2001.
Examples
>>> coords = np.array([[row, col]
... for row in range(13, 17)
... for col in range(14, 18)])
>>> moments_coords_central(coords)
array([[ 16., 0., 20., 0.],
[ 0., 0., 0., 0.],
[ 20., 0., 25., 0.],
[ 0., 0., 0., 0.]])
As seen above, for symmetric objects, oddorder 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:
>>> coords2 = np.concatenate((coords, [[17, 17]]), axis=0)
>>> np.round(moments_coords_central(coords2), 2)
array([[ 17. , 0. , 22.12, 2.49],
[ 0. , 3.53, 1.73, 7.4 ],
[ 25.88, 6.02, 36.63, 8.83],
[ 4.15, 19.17, 14.8 , 39.6 ]])
Image moments and central image moments are equivalent (by definition) when the center is (0, 0):
>>> np.allclose(moments_coords(coords),
... moments_coords_central(coords, (0, 0)))
True
skimage.measure.
moments_normalized
(mu, order=3)[source]¶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.
order + 1
,[ …,] order + 1
) arrayNormalized central image moments.
References
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. SpringerVerlag, London, 2009.
B. Jähne. Digital Image Processing. SpringerVerlag, BerlinHeidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
Examples
>>> image = np.zeros((20, 20), dtype=np.double)
>>> image[13:17, 13:17] = 1
>>> m = moments(image)
>>> cr = m[0, 1] / m[0, 0]
>>> cc = m[1, 0] / m[0, 0]
>>> mu = moments_central(image, cr, cc)
>>> moments_normalized(mu)
array([[ nan, nan, 0.078125 , 0. ],
[ nan, 0. , 0. , 0. ],
[ 0.078125 , 0. , 0.00610352, 0. ],
[ 0. , 0. , 0. , 0. ]])
skimage.measure.
moments_hu
(nu)[source]¶Calculate Hu’s set of image moments (2Donly).
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.
References
M. K. Hu, “Visual Pattern Recognition by Moment Invariants”, IRE Trans. Info. Theory, vol. IT8, pp. 179187, 1962
Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. SpringerVerlag, London, 2009.
B. Jähne. Digital Image Processing. SpringerVerlag, BerlinHeidelberg, 6. edition, 2005.
T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
skimage.measure.
marching_cubes_lewiner
(volume, level=None, spacing=(1.0, 1.0, 1.0), gradient_direction='descent', step_size=1, allow_degenerate=True, use_classic=False)[source]¶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 lefthand 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. zeroarea) triangles in the endresult. 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.
Spatial coordinates for V unique mesh vertices. Coordinate order matches input volume (M, N, P).
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.
Notes
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:
>>> from mayavi import mlab
>>> verts, faces, normals, values = marching_cubes_lewiner(myvolume, 0.0)
>>> mlab.triangular_mesh([vert[0] for vert in verts],
... [vert[1] for vert in verts],
... [vert[2] for vert in verts],
... faces)
>>> mlab.show()
Similarly using the visvis
package:
>>> import visvis as vv
>>> verts, faces, normals, values = marching_cubes_lewiner(myvolume, 0.0)
>>> vv.mesh(np.fliplr(verts), faces, normals, values)
>>> vv.use().Run()
References
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. 115 (december 2003). DOI:10.1080/10867651.2003.10487582
skimage.measure.marching_cubes_lewiner
¶skimage.measure.
marching_cubes_classic
(volume, level=None, spacing=(1.0, 1.0, 1.0), gradient_direction='descent')[source]¶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).
Define triangular faces via referencing vertex indices from verts
.
This algorithm specifically outputs triangles, so each face has
exactly three indices.
See also
skimage.measure.marching_cubes
, skimage.measure.mesh_surface_area
Notes
The marching cubes algorithm is implemented as described in [1]. A simple explanation is available here:
http://www.essi.fr/~lingrand/MarchingCubes/algo.html
There are several known ambiguous cases in the marching cubes algorithm. Using point labeling as in [1], Figure 4, as shown:
v8  v7
/  /  y
/  /  ^ z
v4  v3   /
 v5  v6 / (note: NOT right handed!)
 /  / > x
 /  /
v1  v2
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 sideeffect
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.
References
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. 163170). DOI:10.1145/37401.37422
skimage.measure.
mesh_surface_area
(verts, faces)[source]¶Compute surface area, given vertices & triangular faces
Array containing (x, y, z) coordinates for V unique mesh vertices.
List of length3 lists of integers, referencing vertex coordinates as provided in verts
Surface area of mesh. Units now [coordinate units] ** 2.
See also
skimage.measure.marching_cubes
, skimage.measure.marching_cubes_classic
, skimage.measure.correct_mesh_orientation
Notes
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.
skimage.measure.
correct_mesh_orientation
(volume, verts, faces, spacing=(1.0, 1.0, 1.0), gradient_direction='descent')[source]¶Correct orientations of mesh faces.
Input data volume to find isosurfaces. Will be cast to np.float64.
Array containing (x, y, z) coordinates for V unique mesh vertices.
List of length3 lists of integers, referencing vertex coordinates as provided in verts.
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
Corrected list of faces referencing vertex coordinates in verts.
Notes
Certain applications and mesh processing algorithms require all faces to be oriented in a consistent way. Generally, this means a normal vector points “out” of the meshed shapes. This algorithm corrects the output from skimage.measure.marching_cubes_classic by flipping the orientation of misoriented faces.
Because marching cubes could be used to find isosurfaces either on
gradient descent (where the desired object has greater values than the
exterior) or ascent (where the desired object has lower values than the
exterior), the gradient_direction
kwarg allows the user to inform this
algorithm which is correct. If the resulting mesh appears to be oriented
completely incorrectly, try changing this option.
The arguments expected by this function are the exact outputs from skimage.measure.marching_cubes_classic. Only faces is corrected and returned, as the vertices do not change; only the order in which they are referenced.
This algorithm assumes faces
provided are all triangles.
skimage.measure.
profile_line
(image, src, dst, linewidth=1, order=1, mode='constant', cval=0.0)[source]¶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 start point of the scan line.
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 to compute image values at noninteger coordinates. 0 means nearestneighbor interpolation.
How to compute any values falling outside of the image.
If mode is ‘constant’, what constant value to use outside the image.
The intensity profile along the scan line. The length of the profile is the ceil of the computed length of the scan line.
Examples
>>> x = np.array([[1, 1, 1, 2, 2, 2]])
>>> img = np.vstack([np.zeros_like(x), x, x, x, np.zeros_like(x)])
>>> img
array([[0, 0, 0, 0, 0, 0],
[1, 1, 1, 2, 2, 2],
[1, 1, 1, 2, 2, 2],
[1, 1, 1, 2, 2, 2],
[0, 0, 0, 0, 0, 0]])
>>> profile_line(img, (2, 1), (2, 4))
array([ 1., 1., 2., 2.])
>>> profile_line(img, (1, 0), (1, 6), cval=4)
array([ 1., 1., 1., 2., 2., 2., 4.])
The destination point is included in the profile, in contrast to standard numpy indexing. For example:
>>> profile_line(img, (1, 0), (1, 6)) # The final point is out of bounds
array([ 1., 1., 1., 2., 2., 2., 0.])
>>> profile_line(img, (1, 0), (1, 5)) # This accesses the full first row
array([ 1., 1., 1., 2., 2., 2.])
skimage.measure.
label
(input, neighbors=None, background=None, return_num=False, connectivity=None)[source]¶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 2connected sense. The value refers to the maximum number of orthogonal hops to consider a pixel/voxel a neighbor:
1connectivity 2connectivity diagonal connection closeup
[ ] [ ] [ ] [ ] [ ]
 \  /  < hop 2
[ ][x][ ] [ ][x][ ] [x][ ]
 /  \ hop 1
[ ] [ ] [ ] [ ]
Image to label.
Whether to use 4 or 8“connectivity”. In 3D, 4“connectivity” means connected pixels have to share face, whereas with 8“connectivity”, they have to share only edge or vertex. Deprecated, use ``connectivity`` instead.
Consider all pixels with this value as background pixels, and label them as 0. By default, 0valued 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
References
Christophe Fiorio and Jens Gustedt, “Two linear time UnionFind strategies for image processing”, Theoretical Computer Science 154 (1996), pp. 165181.
Kensheng Wu, Ekow Otoo and Arie Shoshani, “Optimizing connected component labeling algorithms”, Paper LBNL56864, 2005, Lawrence Berkeley National Laboratory (University of California), http://repositories.cdlib.org/lbnl/LBNL56864
Examples
>>> import numpy as np
>>> x = np.eye(3).astype(int)
>>> print(x)
[[1 0 0]
[0 1 0]
[0 0 1]]
>>> print(label(x, connectivity=1))
[[1 0 0]
[0 2 0]
[0 0 3]]
>>> print(label(x, connectivity=2))
[[1 0 0]
[0 1 0]
[0 0 1]]
>>> print(label(x, background=1))
[[1 2 2]
[2 1 2]
[2 2 1]]
>>> x = np.array([[1, 0, 0],
... [1, 1, 5],
... [0, 0, 0]])
>>> print(label(x))
[[1 0 0]
[1 1 2]
[0 0 0]]
skimage.measure.
points_in_poly
(points, verts)[source]¶Test whether points lie inside a polygon.
Input points, (x, y)
.
Vertices of the polygon, sorted either clockwise or anticlockwise. The first point may (but does not need to be) duplicated.
True if corresponding point is inside the polygon.
See also
skimage.measure.
grid_points_in_poly
(shape, verts)[source]¶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 anticlockwise. The first point may (but does not need to be) duplicated.
True where the grid falls inside the polygon.
See also
skimage.measure.
compare_ssim
(X, Y, win_size=None, gradient=False, data_range=None, multichannel=False, gaussian_weights=False, full=False, **kwargs)[source]¶Compute the mean structural similarity index between two images.
Image. Any dimensionality.
The sidelength of the sliding window used in comparison. Must be an odd value. If gaussian_weights is True, this is ignored and the window size will depend on sigma.
If True, also return the gradient with respect to Y.
The data range of the input image (distance between minimum and maximum possible values). By default, this is estimated from the image datatype.
If True, treat the last dimension of the array as channels. Similarity calculations are done independently for each channel then averaged.
If True, each patch has its mean and variance spatially weighted by a normalized Gaussian kernel of width sigma=1.5.
If True, return the full structural similarity image instead of the mean value.
The mean structural similarity over the image.
The gradient of the structural similarity index between X and Y [2]. This is only returned if gradient is set to True.
The full SSIM image. This is only returned if full is set to True.
If True, normalize covariances by N1 rather than, N where N is the number of pixels within the sliding window.
Algorithm parameter, K1 (small constant, see [1]).
Algorithm parameter, K2 (small constant, see [1]).
Standard deviation for the Gaussian when gaussian_weights is True.
Notes
To match the implementation of Wang et. al. [1], set gaussian_weights to True, sigma to 1.5, and use_sample_covariance to False.
References
Wang, Z., Bovik, A. C., Sheikh, H. R., & Simoncelli, E. P. (2004). Image quality assessment: From error visibility to structural similarity. IEEE Transactions on Image Processing, 13, 600612. https://ece.uwaterloo.ca/~z70wang/publications/ssim.pdf, DOI:10.1109/TIP.2003.819861
Avanaki, A. N. (2009). Exact global histogram specification optimized for structural similarity. Optical Review, 16, 613621. arXiv:0901.0065 DOI:10.1007/s100430090119z
skimage.measure.compare_ssim
¶skimage.measure.
compare_nrmse
(im_true, im_test, norm_type='Euclidean')[source]¶Compute the normalized root meansquared error (NRMSE) between two images.
Groundtruth image.
Test image.
Controls the normalization method to use in the denominator of the NRMSE. There is no standard method of normalization across the literature [1]. The methods available here are as follows:
‘Euclidean’ : normalize by the averaged Euclidean norm of
im_true
:
NRMSE = RMSE * sqrt(N) /  im_true 
where  .  denotes the Frobenius norm and N = im_true.size
.
This result is equivalent to:
NRMSE =  im_true  im_test  /  im_true .
‘minmax’ : normalize by the intensity range of im_true
.
‘mean’ : normalize by the mean of im_true
The NRMSE metric.
References
skimage.measure.
compare_psnr
(im_true, im_test, data_range=None)[source]¶Compute the peak signal to noise ratio (PSNR) for an image.
Groundtruth image.
Test image.
The data range of the input image (distance between minimum and maximum possible values). By default, this is estimated from the image datatype.
The PSNR metric.
References
skimage.measure.
shannon_entropy
(image, base=2)[source]¶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.
Notes
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.
References
Examples
>>> from skimage import data
>>> shannon_entropy(data.camera())
7.0479552324230861
LineModelND
¶skimage.measure.
LineModelND
[source]¶Bases: skimage.measure.fit.BaseModel
Total least squares estimator for Ndimensional 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:
X = origin + lambda * direction
Examples
>>> x = np.linspace(1, 2, 25)
>>> y = 1.5 * x + 3
>>> lm = LineModelND()
>>> lm.estimate(np.array([x, y]).T)
True
>>> tuple(np.round(lm.params, 5))
(array([ 1.5 , 5.25]), array([ 0.5547 , 0.83205]))
>>> res = lm.residuals(np.array([x, y]).T)
>>> np.abs(np.round(res, 9))
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> np.round(lm.predict_y(x[:5]), 3)
array([ 4.5 , 4.562, 4.625, 4.688, 4.75 ])
>>> np.round(lm.predict_x(y[:5]), 3)
array([ 1. , 1.042, 1.083, 1.125, 1.167])
Line model parameters in the following order origin, direction.
estimate
(data)[source]¶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
(x, axis=0, params=None)[source]¶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
(y, params=None)[source]¶Predict xcoordinates for 2D lines using the estimated model.
Alias for:
predict(y, axis=1)[:, 0]
ycoordinates.
Optional custom parameter set in the form (origin, direction).
Predicted xcoordinates.
predict_y
(x, params=None)[source]¶Predict ycoordinates for 2D lines using the estimated model.
Alias for:
predict(x, axis=0)[:, 1]
xcoordinates.
Optional custom parameter set in the form (origin, direction).
Predicted ycoordinates.
residuals
(data, params=None)[source]¶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.
CircleModel
¶skimage.measure.
CircleModel
[source]¶Bases: skimage.measure.fit.BaseModel
Total least squares estimator for 2D circles.
The functional model of the circle is:
r**2 = (x  xc)**2 + (y  yc)**2
This estimator minimizes the squared distances from all points to the circle:
min{ sum((r  sqrt((x_i  xc)**2 + (y_i  yc)**2))**2) }
A minimum number of 3 points is required to solve for the parameters.
Examples
>>> t = np.linspace(0, 2 * np.pi, 25)
>>> xy = CircleModel().predict_xy(t, params=(2, 3, 4))
>>> model = CircleModel()
>>> model.estimate(xy)
True
>>> tuple(np.round(model.params, 5))
(2.0, 3.0, 4.0)
>>> res = model.residuals(xy)
>>> np.abs(np.round(res, 9))
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
Circle model parameters in the following order xc, yc, r.
estimate
(data)[source]¶Estimate circle model from data using total least squares.
N points with (x, y)
coordinates, respectively.
True, if model estimation succeeds.
predict_xy
(t, params=None)[source]¶Predict x and ycoordinates using the estimated model.
Angles in circle in radians. Angles start to count from positive xaxis to positive yaxis in a righthanded system.
Optional custom parameter set.
Predicted x and ycoordinates.
EllipseModel
¶skimage.measure.
EllipseModel
[source]¶Bases: skimage.measure.fit.BaseModel
Total least squares estimator for 2D ellipses.
The functional model of the ellipse is:
xt = xc + a*cos(theta)*cos(t)  b*sin(theta)*sin(t)
yt = yc + a*sin(theta)*cos(t) + b*cos(theta)*sin(t)
d = sqrt((x  xt)**2 + (y  yt)**2)
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:
xc, yc, a, b, theta
Examples
>>> xy = EllipseModel().predict_xy(np.linspace(0, 2 * np.pi, 25),
... params=(10, 15, 4, 8, np.deg2rad(30)))
>>> ellipse = EllipseModel()
>>> ellipse.estimate(xy)
True
>>> np.round(ellipse.params, 2)
array([ 10. , 15. , 4. , 8. , 0.52])
>>> np.round(abs(ellipse.residuals(xy)), 5)
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
Ellipse model parameters in the following order xc, yc, a, b, theta.
estimate
(data)[source]¶Estimate circle model from data using total least squares.
N points with (x, y)
coordinates, respectively.
True, if model estimation succeeds.
References
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. 125132).
predict_xy
(t, params=None)[source]¶Predict x and ycoordinates using the estimated model.
Angles in circle in radians. Angles start to count from positive xaxis to positive yaxis in a righthanded system.
Optional custom parameter set.
Predicted x and ycoordinates.