measure

Module: measure

skimage.measure.approximate_polygon(coords, ...) Approximate a polygonal chain with the specified tolerance.
skimage.measure.block_reduce(image, block_size) Down-sample image by applying function to local blocks.
skimage.measure.compare_mse(im1, im2) Compute the mean-squared error between two images.
skimage.measure.compare_nrmse(im_true, im_test) Compute the normalized root mean-squared error (NRMSE) between two images.
skimage.measure.compare_psnr(im_true, im_test) Compute the peak signal to noise ratio (PSNR) for an image.
skimage.measure.compare_ssim(X, Y[, ...]) Compute the mean structural similarity index between two images.
skimage.measure.correct_mesh_orientation(...) Correct orientations of mesh faces.
skimage.measure.find_contours(array, level) Find iso-valued contours in a 2D array for a given level value.
skimage.measure.grid_points_in_poly Test whether points on a specified grid are inside a polygon.
skimage.measure.label(input[, neighbors, ...]) Label connected regions of an integer array.
skimage.measure.marching_cubes(volume, level) Marching cubes algorithm to find iso-valued 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, cr, cc) Calculate all central image moments up to a certain order.
skimage.measure.moments_hu(nu) Calculate Hu’s set of image moments.
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.points_in_poly Test whether points lie inside a polygon.
skimage.measure.profile_line(img, 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.structural_similarity(*args, ...) Deprecated function. Use compare_ssim instead.
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.LineModel() Total least squares estimator for 2D lines.
skimage.measure.LineModelND() Total least squares estimator for N-dimensional lines.

approximate_polygon

skimage.measure.approximate_polygon(coords, tolerance) [source]

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.

Parameters:

coords : (N, 2) array

Coordinate array.

tolerance : float

Maximum distance from original points of polygon to approximated polygonal chain. If tolerance is 0, the original coordinate array is returned.

Returns:

coords : (M, 2) array

Approximated polygonal chain where M <= N.

References

[R258] http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm

block_reduce

skimage.measure.block_reduce(image, block_size, func=<function sum>, cval=0) [source]

Down-sample image by applying function to local blocks.

Parameters:

image : ndarray

N-dimensional input image.

block_size : array_like

Array containing down-sampling integer factor along each axis.

func : callable

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.

cval : float

Constant padding value if image is not perfectly divisible by the block size.

Returns:

image : ndarray

Down-sampled 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 
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 
array([[[11]],
       [[23]],
       [[35]]])
>>> image_max2 = block_reduce(image, block_size=(3, 1, 4), func=np.max)
>>> image_max2 
array([[[27],
        [31],
        [35]]])

compare_mse

skimage.measure.compare_mse(im1, im2) [source]

Compute the mean-squared error between two images.

Parameters:

im1, im2 : ndarray

Image. Any dimensionality.

Returns:

mse : float

The mean-squared error (MSE) metric.

compare_nrmse

skimage.measure.compare_nrmse(im_true, im_test, norm_type='Euclidean') [source]

Compute the normalized root mean-squared error (NRMSE) between two images.

Parameters:

im_true : ndarray

Ground-truth image.

im_test : ndarray

Test image.

norm_type : {‘Euclidean’, ‘min-max’, ‘mean’}

Controls the normalization method to use in the denominator of the NRMSE. There is no standard method of normalization across the literature [R259]. The methods available here are as follows:

  • ‘Euclidean’ : normalize by the Euclidean norm of im_true.
  • ‘min-max’ : normalize by the intensity range of im_true.
  • ‘mean’ : normalize by the mean of im_true.
Returns:

nrmse : float

The NRMSE metric.

References

[R259] (1, 2) https://en.wikipedia.org/wiki/Root-mean-square_deviation

compare_psnr

skimage.measure.compare_psnr(im_true, im_test, dynamic_range=None) [source]

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

Parameters:

im_true : ndarray

Ground-truth image.

im_test : ndarray

Test image.

dynamic_range : int

The dynamic range of the input image (distance between minimum and maximum possible values). By default, this is estimated from the image data-type.

Returns:

psnr : float

The PSNR metric.

References

[R260] https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio

compare_ssim

skimage.measure.compare_ssim(X, Y, win_size=None, gradient=False, dynamic_range=None, multichannel=False, gaussian_weights=False, full=False, **kwargs) [source]

Compute the mean structural similarity index between two images.

Parameters:

X, Y : ndarray

Image. Any dimensionality.

win_size : int or None

The side-length 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.

gradient : bool

If True, also return the gradient.

dynamic_range : int

The dynamic range of the input image (distance between minimum and maximum possible values). By default, this is estimated from the image data-type.

multichannel : int or None

If True, treat the last dimension of the array as channels. Similarity calculations are done independently for each channel then averaged.

gaussian_weights : bool

If True, each patch has its mean and variance spatially weighted by a normalized Gaussian kernel of width sigma=1.5.

full : bool

If True, return the full structural similarity image instead of the mean value

Returns:

mssim : float or ndarray

The mean structural similarity over the image.

grad : ndarray

The gradient of the structural similarity index between X and Y [R262]. This is only returned if gradient is set to True.

S : ndarray

The full SSIM image. This is only returned if full is set to True.

Other Parameters:

use_sample_covariance : bool

if True, normalize covariances by N-1 rather than, N where N is the number of pixels within the sliding window.

K1 : float

algorithm parameter, K1 (small constant, see [R261])

K2 : float

algorithm parameter, K2 (small constant, see [R261])

sigma : float

sigma for the Gaussian when gaussian_weights is True.

Notes

To match the implementation of Wang et. al. [R261], set gaussian_weights to True, sigma to 1.5, and use_sample_covariance to False.

References

[R261] (1, 2, 3, 4) 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, 600-612. https://ece.uwaterloo.ca/~z70wang/publications/ssim.pdf
[R262] (1, 2) Avanaki, A. N. (2009). Exact global histogram specification optimized for structural similarity. Optical Review, 16, 613-621. http://arxiv.org/abs/0901.0065

correct_mesh_orientation

skimage.measure.correct_mesh_orientation(volume, verts, faces, spacing=(1.0, 1.0, 1.0), gradient_direction='descent') [source]

Correct orientations of mesh faces.

Parameters:

volume : (M, N, P) array of doubles

Input data volume to find isosurfaces. Will be cast to np.float64.

verts : (V, 3) array of floats

Array containing (x, y, z) coordinates for V unique mesh vertices.

faces : (F, 3) array of ints

List of length-3 lists of integers, referencing vertex coordinates as provided in verts.

spacing : length-3 tuple of floats

Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in volume.

gradient_direction : string

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

Returns:

faces_corrected (F, 3) array of ints

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 by flipping the orientation of mis-oriented 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. 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.

find_contours

skimage.measure.find_contours(array, level, fully_connected='low', positive_orientation='low') [source]

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.

Parameters:

array : 2D ndarray of double

Input data in which to find contours.

level : float

Value along which to find contours in the array.

fully_connected : str, {‘low’, ‘high’}

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.)

positive_orientation : either ‘low’ or ‘high’

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.)

Returns:

contours : list of (n,2)-ndarrays

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 [R263]. 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 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 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.

References

[R263] (1, 2) 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).

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. ]])]

grid_points_in_poly

skimage.measure.grid_points_in_poly()

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.

Parameters:

shape : tuple (M, N)

Shape of the grid.

verts : (V, 2) array

Specify the V vertices of the polygon, sorted either clockwise or anti-clockwise. The first point may (but does not need to be) duplicated.

Returns:

mask : (M, N) ndarray of bool

True where the grid falls inside the polygon.

See also

points_in_poly

label

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 2-connected sense. The value refers to the maximum number of orthogonal hops to consider a pixel/voxel a neighbor:

1-connectivity      2-connectivity     diagonal connection close-up

     [ ]           [ ]  [ ]  [ ]         [ ]
      |               \  |  /             |  <- hop 2
[ ]--[x]--[ ]      [ ]--[x]--[ ]    [x]--[ ]
      |               /  |  \         hop 1
     [ ]           [ ]  [ ]  [ ]
Parameters:

input : ndarray of dtype int

Image to label.

neighbors : {4, 8}, int, optional

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.

background : int, optional

Consider all pixels with this value as background pixels, and label them as 0. By default, 0-valued pixels are considered as background pixels.

return_num : bool, optional

Whether to return the number of assigned labels.

connectivity : int, optional

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.

Returns:

labels : ndarray of dtype int

Labeled array, where all connected regions are assigned the same integer value.

num : int, optional

Number of labels, which equals the maximum label index and is only returned if return_num is True.

Examples

>>> import numpy as np
>>> x = np.eye(3).astype(int)
>>> print(x)
[[1 0 0]
 [0 1 0]
 [0 0 1]]
>>> from skimage.measure import label
>>> 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]]

marching_cubes

skimage.measure.marching_cubes(volume, level, spacing=(1.0, 1.0, 1.0), gradient_direction='descent') [source]

Marching cubes algorithm to find iso-valued surfaces in 3d volumetric data

Parameters:

volume : (M, N, P) array of doubles

Input data volume to find isosurfaces. Will be cast to np.float64.

level : float

Contour value to search for isosurfaces in volume.

spacing : length-3 tuple of floats

Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in volume.

gradient_direction : string

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

Returns:

verts : (V, 3) array

Spatial coordinates for V unique mesh vertices. Coordinate order matches input volume (M, N, P).

faces : (F, 3) array

Define triangular faces via referencing vertex indices from verts. This algorithm specifically outputs triangles, so each face has exactly three indices.

Notes

The marching cubes algorithm is implemented as described in [R264]. 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 [R264], 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 [R264], 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.

Regarding visualization of algorithm output, the mayavi package is recommended. To contour a volume named myvolume about the level 0.0:

>>> from mayavi import mlab 
>>> verts, faces = marching_cubes(myvolume, 0.0, (1., 1., 2.)) 
>>> mlab.triangular_mesh([vert[0] for vert in verts],
...                      [vert[1] for vert in verts],
...                      [vert[2] for vert in verts],
...                      faces) 
>>> mlab.show() 

References

[R264] (1, 2, 3, 4) 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).

mesh_surface_area

skimage.measure.mesh_surface_area(verts, faces) [source]

Compute surface area, given vertices & triangular faces

Parameters:

verts : (V, 3) array of floats

Array containing (x, y, z) coordinates for V unique mesh vertices.

faces : (F, 3) array of ints

List of length-3 lists of integers, referencing vertex coordinates as provided in verts

Returns:

area : float

Surface area of mesh. Units now [coordinate units] ** 2.

Notes

The arguments expected by this function are the exact 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.

moments

skimage.measure.moments(image, order=3) [source]

Calculate all raw image moments up to a certain order.

The following properties can be calculated from raw image moments:
  • Area as: m[0, 0].
  • Centroid as: {m[0, 1] / m[0, 0], m[1, 0] / m[0, 0]}.

Note that raw moments are neither translation, scale nor rotation invariant.

Parameters:

image : 2D double or uint8 array

Rasterized shape as image.

order : int, optional

Maximum order of moments. Default is 3.

Returns:

m : (order + 1, order + 1) array

Raw image moments.

References

[R265] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
[R266] B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
[R267] T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
[R268] http://en.wikipedia.org/wiki/Image_moment

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]
>>> cr, cc
(14.5, 14.5)

moments_central

skimage.measure.moments_central(image, cr, cc, order=3) [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[0, 1] / m[0, 0], m[1, 0] / m[0, 0]}.

Note that central moments are translation invariant but not scale and rotation invariant.

Parameters:

image : 2D double or uint8 array

Rasterized shape as image.

cr : double

Center row coordinate.

cc : double

Center column coordinate.

order : int, optional

Maximum order of moments. Default is 3.

Returns:

mu : (order + 1, order + 1) array

Central image moments.

References

[R269] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
[R270] B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
[R271] T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
[R272] http://en.wikipedia.org/wiki/Image_moment

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]
>>> moments_central(image, cr, cc)
array([[ 16.,   0.,  20.,   0.],
       [  0.,   0.,   0.,   0.],
       [ 20.,   0.,  25.,   0.],
       [  0.,   0.,   0.,   0.]])

moments_hu

skimage.measure.moments_hu(nu) [source]

Calculate Hu’s set of image moments.

Note that this set of moments is proofed to be translation, scale and rotation invariant.

Parameters:

nu : (M, M) array

Normalized central image moments, where M must be > 4.

Returns:

nu : (7, 1) array

Hu’s set of image moments.

References

[R273] M. K. Hu, “Visual Pattern Recognition by Moment Invariants”, IRE Trans. Info. Theory, vol. IT-8, pp. 179-187, 1962
[R274] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
[R275] B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
[R276] T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
[R277] http://en.wikipedia.org/wiki/Image_moment

moments_normalized

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.

Parameters:

mu : (M, M) array

Central image moments, where M must be > order.

order : int, optional

Maximum order of moments. Default is 3.

Returns:

nu : (order + 1, order + 1) array

Normalized central image moments.

References

[R278] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
[R279] B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
[R280] T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
[R281] http://en.wikipedia.org/wiki/Image_moment

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.        ]])

perimeter

skimage.measure.perimeter(image, neighbourhood=4) [source]

Calculate total perimeter of all objects in binary image.

Parameters:

image : array

Binary image.

neighbourhood : 4 or 8, optional

Neighborhood connectivity for border pixel determination.

Returns:

perimeter : float

Total perimeter of all objects in binary image.

References

[R282] 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

points_in_poly

skimage.measure.points_in_poly()

Test whether points lie inside a polygon.

Parameters:

points : (N, 2) array

Input points, (x, y).

verts : (M, 2) array

Vertices of the polygon, sorted either clockwise or anti-clockwise. The first point may (but does not need to be) duplicated.

Returns:

mask : (N,) array of bool

True if corresponding point is inside the polygon.

profile_line

skimage.measure.profile_line(img, src, dst, linewidth=1, order=1, mode='constant', cval=0.0) [source]

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

Parameters:

img : numeric array, shape (M, N[, C])

The image, either grayscale (2D array) or multichannel (3D array, where the final axis contains the channel information).

src : 2-tuple of numeric scalar (float or int)

The start point of the scan line.

dst : 2-tuple of numeric scalar (float or int)

The end point of the scan line. The destination point is included in the profile, in constrast to standard numpy indexing.

linewidth : int, optional

Width of the scan, perpendicular to the line

order : int in {0, 1, 2, 3, 4, 5}, optional

The order of the spline interpolation to compute image values at non-integer coordinates. 0 means nearest-neighbor interpolation.

mode : {‘constant’, ‘nearest’, ‘reflect’, ‘mirror’, ‘wrap’}, optional

How to compute any values falling outside of the image.

cval : float, optional

If mode is ‘constant’, what constant value to use outside the image.

Returns:

return_value : array

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.])

ransac

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) [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:

  1. Select min_samples random samples from the original data and check whether the set of data is valid (see is_data_valid).
  2. 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).
  3. 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.
  4. 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.

Parameters:

data : [list, tuple of] (N, D) array

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.

model_class : object

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).

min_samples : int

The minimum number of data points to fit a model to.

residual_threshold : float

Maximum distance for a data point to be classified as an inlier.

is_data_valid : function, optional

This function is called with the randomly selected data before the model is fitted to it: is_data_valid(*random_data).

is_model_valid : function, optional

This function is called with the estimated model and the randomly selected data: is_model_valid(model, *random_data), .

max_trials : int, optional

Maximum number of iterations for random sample selection.

stop_sample_num : int, optional

Stop iteration if at least this number of inliers are found.

stop_residuals_sum : float, optional

Stop iteration if sum of residuals is less than or equal to this threshold.

stop_probability : float in range [0, 1], optional

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, and e is the current fraction of inliers w.r.t. the total number of samples.

Returns:

model : object

Best model with largest consensus set.

inliers : (N, ) array

Boolean mask of inliers classified as True.

References

[R283] “RANSAC”, Wikipedia, http://en.wikipedia.org/wiki/RANSAC

Examples

Generate ellipse data without tilt and add noise:

>>> t = np.linspace(0, 2 * np.pi, 50)
>>> a = 5
>>> b = 10
>>> xc = 20
>>> yc = 30
>>> 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
>>> model.params 
array([ -3.30354146e+03,  -2.87791160e+03,   5.59062118e+03,
         7.84365066e+00,   7.19203152e-01])

Estimate ellipse model using RANSAC:

>>> ransac_model, inliers = ransac(data, EllipseModel, 5, 3, max_trials=50)
>>> ransac_model.params
array([ 20.12762373,  29.73563063,   4.81499637,  10.4743584 ,   0.05217117])
>>> inliers
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)

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)

regionprops

skimage.measure.regionprops(label_image, intensity_image=None, cache=True) [source]

Measure properties of labeled image regions.

Parameters:

label_image : (N, M) ndarray

Labeled input image. Labels with value 0 are ignored.

intensity_image : (N, M) ndarray, optional

Intensity (i.e., input) image with same size as labeled image. Default is None.

cache : bool, optional

Determine whether to cache calculated properties. The computation is much faster for cached properties, whereas the memory consumption increases.

Returns:

properties : list of RegionProperties

Each item describes one labeled region, and can be accessed using the attributes listed below.

Notes

The following properties can be accessed as attributes or keys:

area : int
Number of pixels of region.
bbox : tuple
Bounding box (min_row, min_col, max_row, max_col)
centroid : array
Centroid coordinate tuple (row, col).
convex_area : int
Number of pixels of convex hull image.
convex_image : (H, J) ndarray
Binary convex hull image which has the same size as bounding box.
coords : (N, 2) ndarray
Coordinate list (row, col) of the region.
eccentricity : float
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.
equivalent_diameter : float
The diameter of a circle with the same area as the region.
euler_number : int
Euler characteristic of region. Computed as number of objects (= 1) subtracted by number of holes (8-connectivity).
extent : float
Ratio of pixels in the region to pixels in the total bounding box. Computed as area / (rows * cols)
filled_area : int
Number of pixels of filled region.
filled_image : (H, J) ndarray
Binary region image with filled holes which has the same size as bounding box.
image : (H, J) ndarray
Sliced binary region image which has the same size as bounding box.
inertia_tensor : (2, 2) ndarray
Inertia tensor of the region for the rotation around its mass.
inertia_tensor_eigvals : tuple
The two eigen values of the inertia tensor in decreasing order.
intensity_image : ndarray
Image inside region bounding box.
label : int
The label in the labeled input image.
local_centroid : array
Centroid coordinate tuple (row, col), relative to region bounding box.
major_axis_length : float
The length of the major axis of the ellipse that has the same normalized second central moments as the region.
max_intensity : float
Value with the greatest intensity in the region.
mean_intensity : float
Value with the mean intensity in the region.
min_intensity : float
Value with the least intensity in the region.
minor_axis_length : float
The length of the minor axis of the ellipse that has the same normalized second central moments as the region.
moments : (3, 3) ndarray

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.

moments_central : (3, 3) ndarray

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.

moments_hu : tuple
Hu moments (translation, scale and rotation invariant).
moments_normalized : (3, 3) ndarray

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.

orientation : float
Angle between the X-axis and the major axis of the ellipse that has the same second-moments as the region. Ranging from -pi/2 to pi/2 in counter-clockwise direction.
perimeter : float
Perimeter of object which approximates the contour as a line through the centers of border pixels using a 4-connectivity.
solidity : float
Ratio of pixels in the region to pixels of the convex hull image.
weighted_centroid : array
Centroid coordinate tuple (row, col) weighted with intensity image.
weighted_local_centroid : array
Centroid coordinate tuple (row, col), relative to region bounding box, weighted with intensity image.
weighted_moments : (3, 3) ndarray

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.

weighted_moments_central : (3, 3) ndarray

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.

weighted_moments_hu : tuple
Hu moments (translation, scale and rotation invariant) of intensity image.
weighted_moments_normalized : (3, 3) ndarray

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 (intensity-weighted area).

Each region also supports iteration, so that you can do:

for prop in region:
    print(prop, region[prop])

References

[R284] Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009.
[R285] B. Jähne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005.
[R286] T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993.
[R287] http://en.wikipedia.org/wiki/Image_moment

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)

structural_similarity

skimage.measure.structural_similarity(*args, **kwargs) [source]

Deprecated function. Use compare_ssim instead.

subdivide_polygon

skimage.measure.subdivide_polygon(coords, degree=2, preserve_ends=False) [source]

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.

Parameters:

coords : (N, 2) array

Coordinate array.

degree : {1, 2, 3, 4, 5, 6, 7}, optional

Degree of B-Spline. Default is 2.

preserve_ends : bool, optional

Preserve first and last coordinate of non-circular polygon. Default is False.

Returns:

coords : (M, 2) array

Subdivided coordinate array.

References

[R288] http://mrl.nyu.edu/publications/subdiv-course2000/coursenotes00.pdf

CircleModel

class 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.

Attributes

params (tuple) Circle model parameters in the following order xc, yc, r.
__init__() [source]
estimate(data) [source]

Estimate circle model from data using total least squares.

Parameters:

data : (N, 2) array

N points with (x, y) coordinates, respectively.

Returns:

success : bool

True, if model estimation succeeds.

predict_xy(t, params=None) [source]

Predict x- and y-coordinates using the estimated model.

Parameters:

t : array

Angles in circle in radians. Angles start to count from positive x-axis to positive y-axis in a right-handed system.

params : (3, ) array, optional

Optional custom parameter set.

Returns:

xy : (..., 2) array

Predicted x- and y-coordinates.

residuals(data) [source]

Determine residuals of data to model.

For each point the shortest distance to the circle is returned.

Parameters:

data : (N, 2) array

N points with (x, y) coordinates, respectively.

Returns:

residuals : (N, ) array

Residual for each data point.

EllipseModel

class 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.

This estimator minimizes the squared distances from all points to the ellipse:

min{ sum(d_i**2) } = min{ sum((x_i - xt)**2 + (y_i - yt)**2) }

Thus you have 2 * N equations (x_i, y_i) for N + 5 unknowns (t_i, xc, yc, a, b, theta), which gives you an effective redundancy of N - 5.

The params attribute contains the parameters in the following order:

xc, yc, a, b, theta

A minimum number of 5 points is required to solve for the parameters.

Attributes

params (tuple) Ellipse model parameters in the following order xc, yc, a, b, theta.
__init__() [source]
estimate(data) [source]

Estimate circle model from data using total least squares.

Parameters:

data : (N, 2) array

N points with (x, y) coordinates, respectively.

Returns:

success : bool

True, if model estimation succeeds.

predict_xy(t, params=None) [source]

Predict x- and y-coordinates using the estimated model.

Parameters:

t : array

Angles in circle in radians. Angles start to count from positive x-axis to positive y-axis in a right-handed system.

params : (5, ) array, optional

Optional custom parameter set.

Returns:

xy : (..., 2) array

Predicted x- and y-coordinates.

residuals(data) [source]

Determine residuals of data to model.

For each point the shortest distance to the ellipse is returned.

Parameters:

data : (N, 2) array

N points with (x, y) coordinates, respectively.

Returns:

residuals : (N, ) array

Residual for each data point.

LineModel

class skimage.measure.LineModel [source]

Bases: skimage.measure.fit.BaseModel

Total least squares estimator for 2D lines.

Lines are parameterized using polar coordinates as functional model:

dist = x * cos(theta) + y * sin(theta)

This parameterization is able to model vertical lines in contrast to the standard line model y = a*x + b.

This estimator minimizes the squared distances from all points to the line:

min{ sum((dist - x_i * cos(theta) + y_i * sin(theta))**2) }

A minimum number of 2 points is required to solve for the parameters.

Deprecated class. Use LineModelND instead.

Attributes

params (tuple) Line model parameters in the following order dist, theta.
__init__() [source]
estimate(data) [source]

Estimate line model from data using total least squares.

Parameters:

data : (N, 2) array

N points with (x, y) coordinates, respectively.

Returns:

success : bool

True, if model estimation succeeds.

predict_x(y, params=None) [source]

Predict x-coordinates using the estimated model.

Parameters:

y : array

y-coordinates.

params : (2, ) array, optional

Optional custom parameter set.

Returns:

x : array

Predicted x-coordinates.

predict_y(x, params=None) [source]

Predict y-coordinates using the estimated model.

Parameters:

x : array

x-coordinates.

params : (2, ) array, optional

Optional custom parameter set.

Returns:

y : array

Predicted y-coordinates.

residuals(data) [source]

Determine residuals of data to model.

For each point the shortest distance to the line is returned.

Parameters:

data : (N, 2) array

N points with (x, y) coordinates, respectively.

Returns:

residuals : (N, ) array

Residual for each data point.

LineModelND

class skimage.measure.LineModelND [source]

Bases: skimage.measure.fit.BaseModel

Total least squares estimator for N-dimensional lines.

Lines are defined by a point (origin) and a unit vector (direction) according to the following vector equation:

X = origin + lambda * direction

Attributes

params (tuple) Line model parameters in the following order origin, direction.
__init__() [source]
estimate(data) [source]

Estimate line model from data.

Parameters:

data : (N, dim) array

N points in a space of dimensionality dim >= 2.

Returns:

success : bool

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.

Parameters:

x : array

coordinates along an axis.

axis : int

axis orthogonal to the hyperplane intersecting the line.

params : (2, ) array, optional

Optional custom parameter set in the form (origin, direction).

Returns:

y : array

Predicted coordinates.

If the line is parallel to the given axis, a ValueError is raised.

predict_x(y, params=None) [source]

Predict x-coordinates for 2D lines using the estimated model.

Alias for:

predict(y, axis=1)[:, 0]
Parameters:

y : array

y-coordinates.

params : (2, ) array, optional

Optional custom parameter set in the form (origin, direction).

Returns:

x : array

Predicted x-coordinates.

predict_y(x, params=None) [source]

Predict y-coordinates for 2D lines using the estimated model.

Alias for:

predict(x, axis=0)[:, 1]
Parameters:

x : array

x-coordinates.

params : (2, ) array, optional

Optional custom parameter set in the form (origin, direction).

Returns:

y : array

Predicted y-coordinates.

residuals(data) [source]

Determine residuals of data to model.

For each point the shortest distance to the line is returned. It is obtained by projecting the data onto the line.

Parameters:

data : (N, dim) array

N points in a space of dimension dim.

Returns:

residuals : (N, ) array

Residual for each data point.

© 2011 the scikit-image team
Licensed under the BSD 3-clause License.
http://scikit-image.org/docs/0.12.x/api/skimage.measure.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部