Загрузка
Finds blobs in the given grayscale image. |
Edge filter an image using the Canny algorithm. |
Extract FAST corners for a given image. |
Compute Foerstner corner measure response image. |
Compute Harris corner measure response image. |
Compute Kitchen and Rosenfeld corner measure response image. |
Compute Moravec corner measure response image. |
Compute the orientation of corners. |
Find peaks in corner measure response image. |
Compute Shi-Tomasi (Kanade-Tomasi) corner measure response image. |
Determine subpixel position of corners. |
Extract DAISY feature descriptors densely for the given image. |
Visualization of Haar-like features. |
Multi-block local binary pattern visualization. |
Compute the Fisher vector given some descriptors/vectors, and an associated estimated GMM. |
Calculate the gray-level co-occurrence matrix. |
Calculate texture properties of a GLCM. |
Compute the Haar-like features for a region of interest (ROI) of an integral image. |
Compute the coordinates of Haar-like features. |
Compute the Hessian matrix. |
Compute the approximate Hessian Determinant over an image. |
Compute eigenvalues of Hessian matrix. |
Extract Histogram of Oriented Gradients (HOG) for a given image. |
Estimate a Gaussian mixture model (GMM) given a set of descriptors and number of modes (i.e. Gaussians). |
Compute the local binary patterns (LBP) of an image. |
Brute-force matching of descriptors. |
Match a template to a 2-D or 3-D image using normalized correlation. |
Multi-block local binary pattern (MB-LBP). |
Local features for a single- or multi-channel nd image. |
Find peaks in an image as coordinate list. |
Plot matched features between two images. |
Compute the shape index. |
Compute structure tensor using sum of squared differences. |
Compute eigenvalues of structure tensor. |
BRIEF binary descriptor extractor. |
CENSURE keypoint detector. |
Class for cascade of classifiers that is used for object detection. |
Oriented FAST and rotated BRIEF feature detector and binary descriptor extractor. |
SIFT feature detection and descriptor extraction. |
Finds blobs in the given grayscale image.
Blobs are found using the Difference of Gaussian (DoG) method [1], [2]. For each blob found, the method returns its coordinates and the standard deviation of the Gaussian kernel that detected the blob.
Input grayscale image, blobs are assumed to be light on dark background (white on black).
Minimum standard deviation for Gaussian kernel. Keep this value low to detect smaller blobs. The standard deviation of the Gaussian kernel is given either as a sequence for each axis, or as a single number, in which case it is equal for all axes.
The maximum standard deviation for Gaussian kernel. Keep this high to detect larger blobs. The standard deviation of the Gaussian kernel is given either as a sequence for each axis, or as a single number, in which case it is equal for all axes.
The ratio between the standard deviation of Gaussian Kernels used for computing the Difference of Gaussians
The absolute lower bound for scale space maxima. Local maxima smaller than are ignored. Reduce this to detect blobs with lower intensities. If is also specified, whichever threshold is larger will be used. If None, is used instead.
The radius of each blob is approximately for a 2-D image and for a 3-D image.
Lowe, D. G. “Distinctive Image Features from Scale-Invariant Keypoints.” International Journal of Computer Vision 60, 91–110 (2004). https://www.cs.ubc.ca/~lowe/papers/ijcv04.pdf DOI:10.1023/B:VISI.0000029664.99615.94
>>> from skimage import data, feature
>>> coins = data.coins()
>>> feature.blob_dog(coins, threshold=.05, min_sigma=10, max_sigma=40)
array([[128., 155., 10.],
[198., 155., 10.],
Finds blobs in the given grayscale image.
Blobs are found using the Determinant of Hessian method [1]. For each blob found, the method returns its coordinates and the standard deviation of the Gaussian Kernel used for the Hessian matrix whose determinant detected the blob. Determinant of Hessians is approximated using [2].
Input grayscale image. Blobs can either be light on dark or vice versa.
The minimum standard deviation for Gaussian Kernel used to compute Hessian matrix. Keep this value low to detect smaller blobs. The standard deviation of the Gaussian kernel is given either as a sequence for each axis, or as a single number, in which case it is equal for all axes.
The maximum standard deviation for Gaussian Kernel used to compute Hessian matrix. Keep this value high to detect larger blobs. The standard deviation of the Gaussian kernel is given either as a sequence for each axis, or as a single number, in which case it is equal for all axes.
The number of evenly spaced values for standard deviation of the
Gaussian kernel to consider on the closed interval
[min_sigma, max_sigma].
The radius of each blob is approximately sigma.
Computation of Determinant of Hessians is independent of the standard
deviation. Therefore detecting larger blobs won’t take more time. In
methods line blob_dog() and blob_log() the computation
of Gaussians for larger sigma takes more time. The downside is that
this method can’t be used for detecting blobs of radius less than 3px
due to the box filters used in the approximation of Hessian Determinant.
Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool, “SURF: Speeded Up Robust Features” ftp://ftp.vision.ee.ethz.ch/publications/articles/eth_biwi_00517.pdf
>>> from skimage import data, feature
>>> img = data.coins()
>>> feature.blob_doh(img)
array([[197. , 153. , 20.33333333],
[124. , 336. , 20.33333333],
[126. , 153. , 20.33333333],
[195. , 100. , 23.55555556],
[192. , 212. , 23.55555556],
[121. , 271. , 30. ],
[126. , 101. , 20.33333333],
[193. , 275. , 23.55555556],
[123. , 205. , 20.33333333],
Finds blobs in the given grayscale image.
Blobs are found using the Laplacian of Gaussian (LoG) method [1]. For each blob found, the method returns its coordinates and the standard deviation of the Gaussian kernel that detected the blob.
Input grayscale image, blobs are assumed to be light on dark background (white on black).
Minimum standard deviation for Gaussian kernel. Keep this value low to detect smaller blobs. The standard deviation of the Gaussian kernel is given either as a sequence for each axis, or as a single number, in which case it is equal for all axes.
The maximum standard deviation for Gaussian kernel. Keep this high to detect larger blobs. The standard deviation of the Gaussian kernel is given either as a sequence for each axis, or as a single number, in which case it is equal for all axes.
The number of evenly spaced values for standard deviation of the Gaussian kernel to consider on the closed interval .
Edge filter an image using the Canny algorithm.
Grayscale input image to detect edges on; can be of any dtype.
Standard deviation of the Gaussian filter.
Lower bound for hysteresis thresholding (linking edges). If None, low_threshold is set to 10% of dtype’s max.
Upper bound for hysteresis thresholding (linking edges). If None, high_threshold is set to 20% of dtype’s max.
Mask to limit the application of Canny to a certain area.
If then treat low_threshold and high_threshold as
quantiles of the edge magnitude image, rather than absolute
edge magnitude values. If then the thresholds must be
in the range [0, 1].
The binary edge map.
The steps of the algorithm are as follows:
Smooth the image using a Gaussian with sigma width.
Apply the horizontal and vertical Sobel operators to get the gradients within the image. The edge strength is the norm of the gradient.
Thin potential edges to 1-pixel wide curves. First, find the normal to the edge at each point. This is done by looking at the signs and the relative magnitude of the X-Sobel and Y-Sobel to sort the points into 4 categories: horizontal, vertical, diagonal and antidiagonal. Then look in the normal and reverse directions to see if the values in either of those directions are greater than the point in question. Use interpolation to get a mix of points instead of picking the one that’s the closest to the normal.
Perform a hysteresis thresholding: first label all points above the high threshold as edges. Then recursively label any point above the low threshold that is 8-connected to a labeled point as an edge.
Canny, J., A Computational Approach To Edge Detection, IEEE Trans. Pattern Analysis and Machine Intelligence, 8:679-714, 1986 DOI:10.1109/TPAMI.1986.4767851
William Green’s Canny tutorial https://en.wikipedia.org/wiki/Canny_edge_detector
>>> from skimage import feature
>>> rng = np.random.default_rng()
>>> # Generate noisy image of a square
>>> im = np.zeros((256, 256))
>>> im[64:-64
Comparing edge-based and region-based segmentation
Extract FAST corners for a given image.
Input image.
Minimum number of consecutive pixels out of 16 pixels on the circle
that should all be either brighter or darker w.r.t testpixel.
A point c on the circle is darker w.r.t test pixel p if
Ic < Ip - threshold and brighter if Ic > Ip + threshold. Also
stands for the n in FAST-n corner detector.
Threshold used in deciding whether the pixels on the circle are brighter, darker or similar w.r.t. the test pixel. Decrease the threshold when more corners are desired and vice-versa.
FAST corner response image.
Rosten, E., & Drummond, T. (2006, May). Machine learning for high-speed corner detection. In European conference on computer vision (pp. 430-443). Springer, Berlin, Heidelberg. DOI:10.1007/11744023_34 http://www.edwardrosten.com/work/rosten_2006_machine.pdf
Wikipedia, “Features from accelerated segment test”, https://en.wikipedia.org/wiki/Features_from_accelerated_segment_test
>>> from skimage.feature import corner_fast, corner_peaks
>>> square = np.zeros((12, 12))
>>> square[3:9, 3:9] = 1
>>> square.astype
Compute Foerstner corner measure response image.
This corner detector uses information from the auto-correlation matrix A:
A = [(imx**2) (imx*imy)] = [Axx Axy]
[(imx*imy) (imy**2)] [Axy Ayy]
Where imx and imy are first derivatives, averaged with a gaussian filter. The corner measure is then defined as:
w = det(A) / trace(A) (size of error ellipse)
q = 4 * det(A) / trace(A)**2 (roundness of error ellipse)
Input image.
Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix.
Error ellipse sizes.
Roundness of error ellipse.
Förstner, W., & Gülch, E. (1987, June). A fast operator for detection and precise location of distinct points, corners and centres of circular features. In Proc. ISPRS intercommission conference on fast processing of photogrammetric data (pp. 281-305). https://cseweb.ucsd.edu/classes/sp02/cse252/foerstner/foerstner.pdf
>>> from skimage.feature import corner_foerstner, corner_peaks
>>> square = np.zeros([10, 10])
>>> square[2:8, 2:8] = 1
>>> square.astype
Compute Harris corner measure response image.
This corner detector uses information from the auto-correlation matrix A:
A = [(imx**2) (imx*imy)] = [Axx Axy]
[(imx*imy) (imy**2)] [Axy Ayy]
Where imx and imy are first derivatives, averaged with a gaussian filter. The corner measure is then defined as:
det(A) - k * trace(A)**2
or:
2 * det(A) / (trace(A) + eps)
Input image.
Method to compute the response image from the auto-correlation matrix.
Sensitivity factor to separate corners from edges, typically in range
[0, 0.2]. Small values of k result in detection of sharp corners.
Normalisation factor (Noble’s corner measure).
Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix.
>>> from skimage.feature import corner_harris, corner_peaks
>>> square = np.zeros([10, 10])
>>> square[2:8, 2:8] = 1
>>> square.astype
Compute Kitchen and Rosenfeld corner measure response image.
The corner measure is calculated as follows:
(imxx * imy**2 + imyy * imx**2 - 2 * imxy * imx * imy)
/ (imx**2 + imy**2)
Where imx and imy are the first and imxx, imxy, imyy the second derivatives.
Input image.
How to handle values outside the image borders.
Used in conjunction with mode ‘constant’, the value outside the image boundaries.
Kitchen and Rosenfeld response image.
Kitchen, L., & Rosenfeld, A. (1982). Gray-level corner detection. Pattern recognition letters, 1(2), 95-102. DOI:10.1016/0167-8655(82)90020-4
Compute Moravec corner measure response image.
This is one of the simplest corner detectors and is comparatively fast but has several limitations (e.g. not rotation invariant).
Input image.
Window size.
Moravec response image.
>>> from skimage.feature import corner_moravec
>>> square = np.zeros([7, 7])
>>> square[3, 3] = 1
>>> square.astype(int)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
Compute the orientation of corners.
The orientation of corners is computed using the first order central moment i.e. the center of mass approach. The corner orientation is the angle of the vector from the corner coordinate to the intensity centroid in the local neighborhood around the corner calculated using first order central moment.
Input grayscale image.
Corner coordinates as (row, col).
Mask defining the local neighborhood of the corner used for the calculation of the central moment.
Orientations of corners in the range [-pi, pi].
Ethan Rublee, Vincent Rabaud, Kurt Konolige and Gary Bradski “ORB : An efficient alternative to SIFT and SURF” http://www.vision.cs.chubu.ac.jp/CV-R/pdf/Rublee_iccv2011.pdf
Paul L. Rosin, “Measuring Corner Properties” http://users.cs.cf.ac.uk/Paul.Rosin/corner2.pdf
>>> from skimage.morphology import octagon
>>> from skimage.feature import (corner_fast, corner_peaks,
... corner_orientations)
>>> square = np.zeros((12, 12))
>>> square[3
Find peaks in corner measure response image.
This differs from skimage.feature.peak_local_max in that it suppresses
multiple connected peaks with the same accumulator value.
Input image.
The minimal allowed distance separating peaks.
Compute Shi-Tomasi (Kanade-Tomasi) corner measure response image.
This corner detector uses information from the auto-correlation matrix A:
A = [(imx**2) (imx*imy)] = [Axx Axy]
[(imx*imy) (imy**2)] [Axy Ayy]
Where imx and imy are first derivatives, averaged with a gaussian filter. The corner measure is then defined as the smaller eigenvalue of A:
((Axx + Ayy) - sqrt((Axx - Ayy)**2 + 4 * Axy**2)) / 2
Input image.
Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix.
Shi-Tomasi response image.
>>> from skimage.feature import corner_shi_tomasi, corner_peaks
>>> square = np.zeros([10, 10])
>>> square[2:8, 2:8] = 1
>>> square.astype
Determine subpixel position of corners.
A statistical test decides whether the corner is defined as the intersection of two edges or a single peak. Depending on the classification result, the subpixel corner location is determined based on the local covariance of the grey-values. If the significance level for either statistical test is not sufficient, the corner cannot be classified, and the output subpixel position is set to NaN.
Input image.
Corner coordinates (row, col).
Search window size for subpixel estimation.
Significance level for corner classification.
Subpixel corner positions. NaN for “not classified” corners.
Förstner, W., & Gülch, E. (1987, June). A fast operator for detection and precise location of distinct points, corners and centres of circular features. In Proc. ISPRS intercommission conference on fast processing of photogrammetric data (pp. 281-305). https://cseweb.ucsd.edu/classes/sp02/cse252/foerstner/foerstner.pdf
>>> from skimage.feature import corner_harris, corner_peaks, corner_subpix
>>> img = np.zeros((10, 10))
>>> img[:5, :5] = 1
>>> img[5:,
Extract DAISY feature descriptors densely for the given image.
DAISY is a feature descriptor similar to SIFT formulated in a way that allows for fast dense extraction. Typically, this is practical for bag-of-features image representations.
The implementation follows Tola et al. [1] but deviate on the following points:
Histogram bin contribution are smoothed with a circular Gaussian window over the tonal range (the angular range).
The sigma values of the spatial Gaussian smoothing in this code do not match the sigma values in the original code by Tola et al. [2]. In their code, spatial smoothing is applied to both the input image and the center histogram. However, this smoothing is not documented in [1] and, therefore, it is omitted.
Input image (grayscale).
Distance between descriptor sampling points.
Visualization of Haar-like features.
The region of an integral image for which the features need to be computed.
Row-coordinate of top left corner of the detection window.
Column-coordinate of top left corner of the detection window.
Width of the detection window.
Height of the detection window.
The array of coordinates to be extracted. This is useful when you want
to recompute only a subset of features. In this case feature_type
needs to be an array containing the type of each feature, as returned
by . By default, all coordinates are
computed.
An image in which the different features will be added.
>>> import numpy as np
>>> from skimage.feature import haar_like_feature_coord
>>> from skimage.feature import draw_haar_like_feature
>>> feature_coord, _ = haar_like_feature_coord(2, 2, 'type-4')
>>> image =
Face classification using Haar-like feature descriptor
Multi-block local binary pattern visualization.
Blocks with higher sums are colored with alpha-blended white rectangles,
whereas blocks with lower sums are colored alpha-blended cyan. Colors
and the alpha parameter can be changed.
Image on which to visualize the pattern.
Row-coordinate of top left corner of a rectangle containing feature.
Column-coordinate of top left corner of a rectangle containing feature.
Width of one of 9 equal rectangles that will be used to compute a feature.
Height of one of 9 equal rectangles that will be used to compute a feature.
The descriptor of feature to visualize. If not provided, the descriptor with 0 value will be used.
L. Zhang, R. Chu, S. Xiang, S. Liao, S.Z. Li. “Face Detection Based on Multi-Block LBP Representation”, In Proceedings: Advances in Biometrics, International Conference, ICB 2007, Seoul, Korea. http://www.cbsr.ia.ac.cn/users/scliao/papers/Zhang-ICB07-MBLBP.pdf DOI:10.1007/978-3-540-74549-5_2
Multi-Block Local Binary Pattern for texture classification
Compute the Fisher vector given some descriptors/vectors, and an associated estimated GMM.
NumPy array of the descriptors for which the Fisher vector representation is to be computed.
sklearn.mixture.GaussianMixtureAn estimated GMM object, which contains the necessary parameters needed to compute the Fisher vector.
Flag denoting whether to compute improved Fisher vectors or not. Improved Fisher vectors are L2 and power normalized. Power normalization is simply f(z) = sign(z) pow(abs(z), alpha) for some 0 <= alpha <= 1.
The parameter for the power normalization step. Ignored if improved=False.
The computation Fisher vector, which is given by a concatenation of the gradients of a GMM with respect to its parameters (mixture weights, means, and covariance matrices). For D-dimensional input descriptors or vectors, and a K-mode GMM, the Fisher vector dimensionality will be 2KD + K. Thus, its dimensionality is invariant to the number of descriptors/vectors.
Perronnin, F. and Dance, C. Fisher kernels on Visual Vocabularies for Image Categorization, IEEE Conference on Computer Vision and Pattern Recognition, 2007
Perronnin, F. and Sanchez, J. and Mensink T. Improving the Fisher Kernel for Large-Scale Image Classification, ECCV, 2010
>>> from skimage.feature import fisher_vector, learn_gmm
>>> sift_for_images = [np.random.random((10, 128)) for _ in range(10)]
>>> num_modes = 16
>>> # Estimate 16-mode GMM with these synthetic SIFT vectors
Calculate the gray-level co-occurrence matrix.
A gray level co-occurrence matrix is a histogram of co-occurring grayscale values at a given offset over an image.
Integer typed input image. Only positive valued images are supported.
If type is other than uint8, the argument levels needs to be set.
List of pixel pair distance offsets.
List of pixel pair angles in radians.
The input image should contain integers in [0, levels-1],
where levels indicate the number of gray-levels counted
(typically 256 for an 8-bit image). This argument is required for
16-bit images or higher and is typically the maximum of the image.
As the output matrix is at least x , it might
be preferable to use binning of the input image rather than
large values for .
M. Hall-Beyer, 2007. GLCM Texture: A Tutorial
https://prism.ucalgary.ca/handle/1880/51900
DOI:10.11575/PRISM/33280
R.M. Haralick, K. Shanmugam, and I. Dinstein, “Textural features for image classification”, IEEE Transactions on Systems, Man, and Cybernetics, vol. SMC-3, no. 6, pp. 610-621, Nov. 1973. DOI:10.1109/TSMC.1973.4309314
M. Nadler and E.P. Smith, Pattern Recognition Engineering, Wiley-Interscience, 1993.
Wikipedia, https://en.wikipedia.org/wiki/Co-occurrence_matrix
Compute 4 GLCMs using 1-pixel distance and 4 different angles. For example, an angle of 0 radians refers to the neighboring pixel to the right; pi/4 radians to the top-right diagonal neighbor; pi/2 radians to the pixel above, and so forth.
>>> image = np.array([[0, 0, 1, 1],
... [0, 0, 1, 1],
... [0, 2, 2, 2],
...
Calculate texture properties of a GLCM.
Compute a feature of a gray level co-occurrence matrix to serve as a compact summary of the matrix. The properties are computed as follows:
‘contrast’:
‘dissimilarity’:
‘homogeneity’:
‘ASM’:
‘energy’:
‘mean’:
‘variance’:
‘std’:
‘entropy’:
Each GLCM is normalized to have a sum of 1 before the computation of texture properties.
Input array. P is the gray-level co-occurrence histogram
for which to compute the specified property. The value
P[i,j,d,theta] is the number of times that gray-level j
occurs at a distance d and at an angle theta from
gray-level i.
The property of the GLCM to compute. The default is ‘contrast’.
2-dimensional array. results[d, is the property ‘prop’ for
the d’th distance and the a’th angle.
M. Hall-Beyer, 2007. GLCM Texture: A Tutorial v. 1.0 through 3.0.
The GLCM Tutorial Home Page,
https://prism.ucalgary.ca/handle/1880/51900
DOI:10.11575/PRISM/33280
Compute the contrast for GLCMs with distances [1, 2] and angles [0 degrees, 90 degrees]
>>> image = np.array([[0, 0, 1, 1],
... [0, 0, 1, 1],
... [0, 2, 2, 2],
...
Compute the Haar-like features for a region of interest (ROI) of an integral image.
Haar-like features have been successfully used for image classification and object detection [1]. It has been used for real-time face detection algorithm proposed in [2].
Integral image for which the features need to be computed.
Row-coordinate of top left corner of the detection window.
Column-coordinate of top left corner of the detection window.
Width of the detection window.
Height of the detection window.
The type of feature to consider:
‘type-2-x’: 2 rectangles varying along the x axis;
‘type-2-y’: 2 rectangles varying along the y axis;
‘type-3-x’: 3 rectangles varying along the x axis;
‘type-3-y’: 3 rectangles varying along the y axis;
‘type-4’: 4 rectangles varying along x and y axis.
By default all features are extracted.
If using with feature_coord, it should correspond to the feature
type of each associated coordinate feature.
The array of coordinates to be extracted. This is useful when you want
to recompute only a subset of features. In this case feature_type
needs to be an array containing the type of each feature, as returned
by haar_like_feature_coord(). By default, all coordinates are
computed.
Resulting Haar-like features. Each value is equal to the subtraction of
sums of the positive and negative rectangles. The data type depends of
the data type of int_image: int when the data type of int_image
is uint or int and float when the data type of int_image is
.
When extracting those features in parallel, be aware that the choice of the backend (i.e. multiprocessing vs threading) will have an impact on the performance. The rule of thumb is as follows: use multiprocessing when extracting features for all possible ROI in an image; use threading when extracting the feature at specific location for a limited number of ROIs. Refer to the example Face classification using Haar-like feature descriptor for more insights.
Oren, M., Papageorgiou, C., Sinha, P., Osuna, E., & Poggio, T. (1997, June). Pedestrian detection using wavelet templates. In Computer Vision and Pattern Recognition, 1997. Proceedings., 1997 IEEE Computer Society Conference on (pp. 193-199). IEEE. http://tinyurl.com/y6ulxfta DOI:10.1109/CVPR.1997.609319
Viola, Paul, and Michael J. Jones. “Robust real-time face detection.” International journal of computer vision 57.2 (2004): 137-154. https://www.merl.com/publications/docs/TR2004-043.pdf DOI:10.1109/CVPR.2001.990517
>>> import numpy as np
>>> from skimage.transform import integral_image
>>> from skimage.feature import haar_like_feature
>>> img = np.ones((5, 5), dtype=np.uint8
You can compute the feature for some pre-computed coordinates.
>>> from skimage.feature import haar_like_feature_coord
>>> feature_coord, feature_type = zip(
... *[haar_like_feature_coord(5, 5, feat_t)
... for feat_t in ('type-2-x', 'type-3-x')])
>>>
Face classification using Haar-like feature descriptor
Compute the coordinates of Haar-like features.
Width of the detection window.
Height of the detection window.
The type of feature to consider:
‘type-2-x’: 2 rectangles varying along the x axis;
‘type-2-y’: 2 rectangles varying along the y axis;
‘type-3-x’: 3 rectangles varying along the x axis;
‘type-3-y’: 3 rectangles varying along the y axis;
‘type-4’: 4 rectangles varying along x and y axis.
By default all features are extracted.
Coordinates of the rectangles for each feature.
The corresponding type for each feature.
>>> import numpy as np
>>> from skimage.transform import integral_image
>>> from skimage.feature import haar_like_feature_coord
>>> feat_coord, feat_type = haar_like_feature_coord(2, 2, 'type-4')
>>> feat_coord
array([ list([[(0, 0), (0, 0)], [(0, 1), (0, 1)],
Face classification using Haar-like feature descriptor
Compute the Hessian matrix.
In 2D, the Hessian matrix is defined as:
H = [Hrr Hrc]
[Hrc Hcc]
which is computed by convolving the image with the second derivatives of the Gaussian kernel in the respective r- and c-directions.
The implementation here also supports n-dimensional data.
Input image.
Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix.
How to handle values outside the image borders.
Used in conjunction with mode ‘constant’, the value outside the image boundaries.
For 2D images, this parameter allows for the use of reverse or forward order of the image axes in gradient computation. ‘rc’ indicates the use of the first axis initially (Hrr, Hrc, Hcc), whilst ‘xy’ indicates the usage of the last axis initially (Hxx, Hxy, Hyy). Images with higher dimension must always use ‘rc’ order.
The distributive property of derivatives and convolutions allows us to restate the derivative of an image, I, smoothed with a Gaussian kernel, G, as the convolution of the image with the derivative of G.
When use_gaussian_derivatives is True, this property is used to
compute the second order derivatives that make up the Hessian matrix.
When use_gaussian_derivatives is False, simple finite differences
on a Gaussian-smoothed image are used instead.
>>> from skimage.feature import hessian_matrix
>>> square = np.zeros((5, 5))
>>> square[2, 2] = 4
>>> Hrr, Hrc, Hcc = hessian_matrix(square
Compute the approximate Hessian Determinant over an image.
The 2D approximate method uses box filters over integral images to compute the approximate Hessian Determinant.
The image over which to compute the Hessian Determinant.
Standard deviation of the Gaussian kernel used for the Hessian matrix.
If True and the image is 2D, use a much faster approximate
computation. This argument has no effect on 3D and higher images.
The array of the Determinant of Hessians.
For 2D images when approximate=True, the running time of this method
only depends on size of the image. It is independent of sigma as one
would expect. The downside is that the result for sigma less than 3
is not accurate, i.e., not similar to the result obtained if someone
computed the Hessian and took its determinant.
Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool, “SURF: Speeded Up Robust Features” ftp://ftp.vision.ee.ethz.ch/publications/articles/eth_biwi_00517.pdf
Compute eigenvalues of Hessian matrix.
The upper-diagonal elements of the Hessian matrix, as returned
by hessian_matrix.
The eigenvalues of the Hessian matrix, in decreasing order. The
eigenvalues are the leading dimension. That is, eigs[i, j, k]
contains the ith-largest eigenvalue at position (j, k).
>>> from skimage.feature import hessian_matrix, hessian_matrix_eigvals
>>> square = np.zeros((5, 5))
>>> square[2, 2] = 4
>>> H_elems = hessian_matrix(square,
Extract Histogram of Oriented Gradients (HOG) for a given image.
Compute a Histogram of Oriented Gradients (HOG) by
(optional) global image normalization
computing the gradient image in
rowandcolcomputing gradient histograms
normalizing across blocks
flattening into a feature vector
Input image.
Number of orientation bins.
Estimate a Gaussian mixture model (GMM) given a set of descriptors and
number of modes (i.e. Gaussians). This function is essentially a wrapper
around the scikit-learn implementation of GMM, namely the
sklearn.mixture.GaussianMixture class.
Due to the nature of the Fisher vector, the only enforced parameter of the underlying scikit-learn class is the covariance_type, which must be ‘diag’.
There is no simple way to know what value to use for n_modes a-priori.
Typically, the value is usually one of {16, 32, 64, 128}. One may train
a few GMMs and choose the one that maximises the log probability of the
GMM, or choose n_modes such that the downstream classifier trained on
the resultant Fisher vectors has maximal performance.
List of NumPy arrays, or a single NumPy array, of the descriptors used to estimate the GMM. The reason a list of NumPy arrays is permissible is because often when using a Fisher vector encoding, descriptors/vectors are computed separately for each sample/image in the dataset, such as SIFT vectors for each image. If a list if passed in, then each element must be a NumPy array in which the number of rows may differ (e.g. different number of SIFT vector for each image), but the number of columns for each must be the same (i.e. the dimensionality must be the same).
The number of modes/Gaussians to estimate during the GMM estimate.
Keyword arguments that can be passed into the underlying scikit-learn
sklearn.mixture.GaussianMixture class.
>>> from skimage.feature import fisher_vector
>>> rng = np.random.Generator(np.random.PCG64())
>>> sift_for_images = [rng.standard_normal((10, 128)) for _
Compute the local binary patterns (LBP) of an image.
LBP is a visual descriptor often used in texture classification.
2D grayscale image.
Number of circularly symmetric neighbor set points (quantization of the angular space).
Radius of circle (spatial resolution of the operator).
Method to determine the pattern:
defaultOriginal local binary pattern which is grayscale invariant but not rotation invariant.
rorExtension of default pattern which is grayscale invariant and rotation invariant.
uniformUniform pattern which is grayscale invariant and rotation invariant, offering finer quantization of the angular space. For details, see [1].
nri_uniformVariant of uniform pattern which is grayscale invariant but not rotation invariant. For details, see [2] and [3].
LBP image.
T. Ojala, M. Pietikainen, T. Maenpaa, “Multiresolution gray-scale and rotation invariant texture classification with local binary patterns”, IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 24, no. 7, pp. 971-987, July 2002 DOI:10.1109/TPAMI.2002.1017623
T. Ahonen, A. Hadid and M. Pietikainen. “Face recognition with local binary patterns”, in Proc. Eighth European Conf. Computer Vision, Prague, Czech Republic, May 11-14, 2004, pp. 469-481, 2004. http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.214.6851 DOI:10.1007/978-3-540-24670-1_36
T. Ahonen, A. Hadid and M. Pietikainen, “Face Description with Local Binary Patterns: Application to Face Recognition”, IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 28, no. 12, pp. 2037-2041, Dec. 2006 DOI:10.1109/TPAMI.2006.244
Brute-force matching of descriptors.
For each descriptor in the first set this matcher finds the closest descriptor in the second set (and vice-versa in the case of enabled cross-checking).
Descriptors of size P about M keypoints in the first image.
Descriptors of size P about N keypoints in the second image.
The metric to compute the distance between two descriptors. See
scipy.spatial.distance.cdist for all possible types. The hamming
distance should be used for binary descriptors. By default the L2-norm
is used for all descriptors of dtype float or double and the Hamming
distance is used for binary descriptors automatically.
The p-norm to apply for metric='minkowski'.
Maximum allowed distance between descriptors of two keypoints in separate images to be regarded as a match.
If True, the matched keypoints are returned after cross checking i.e. a matched pair (keypoint1, keypoint2) is returned if keypoint2 is the best match for keypoint1 in second image and keypoint1 is the best match for keypoint2 in first image.
Maximum ratio of distances between first and second closest descriptor in the second set of descriptors. This threshold is useful to filter ambiguous matches between the two descriptor sets. The choice of this value depends on the statistics of the chosen descriptor, e.g., for SIFT descriptors a value of 0.8 is usually chosen, see D.G. Lowe, “Distinctive Image Features from Scale-Invariant Keypoints”, International Journal of Computer Vision, 2004.
Indices of corresponding matches in first and second set of
descriptors, where matches[:, 0] denote the indices in the first
and matches[:, 1] the indices in the second set of descriptors.
Match a template to a 2-D or 3-D image using normalized correlation.
The output is an array with values between -1.0 and 1.0. The value at a given position corresponds to the correlation coefficient between the image and the template.
For pad_input=True matches correspond to the center and otherwise to the
top-left corner of the template. To find the best match you must search for
peaks in the response (output) image.
2-D or 3-D input image.
Template to locate. It must be (m <= M, n <= N[, p <= P]).
If True, pad image so that output is the same size as the image, and
output values correspond to the template center. Otherwise, the output
is an array with shape (M - m + 1, N - n + 1) for an (M, N) image
and an (m, n) template, and matches correspond to origin
(top-left corner) of the template.
numpy.pad, optionalPadding mode.
numpy.pad, optionalConstant values used in conjunction with mode='constant'.
Response image with correlation coefficients.
Details on the cross-correlation are presented in [1]. This implementation uses FFT convolutions of the image and the template. Reference [2] presents similar derivations but the approximation presented in this reference is not used in our implementation.
J. P. Lewis, “Fast Normalized Cross-Correlation”, Industrial Light and Magic.
Briechle and Hanebeck, “Template Matching using Fast Normalized Cross Correlation”, Proceedings of the SPIE (2001). DOI:10.1117/12.421129
>>> template = np.zeros((3, 3))
>>> template[1, 1] = 1
>>> template
array([[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]])
>>> image = np.zeros((6, 6
Multi-block local binary pattern (MB-LBP).
The features are calculated similarly to local binary patterns (LBPs),
(See local_binary_pattern()) except that summed blocks are
used instead of individual pixel values.
MB-LBP is an extension of LBP that can be computed on multiple scales in constant time using the integral image. Nine equally-sized rectangles are used to compute a feature. For each rectangle, the sum of the pixel intensities is computed. Comparisons of these sums to that of the central rectangle determine the feature, similarly to LBP.
Integral image.
Row-coordinate of top left corner of a rectangle containing feature.
Column-coordinate of top left corner of a rectangle containing feature.
Width of one of the 9 equal rectangles that will be used to compute a feature.
Height of one of the 9 equal rectangles that will be used to compute a feature.
8-bit MB-LBP feature descriptor.
L. Zhang, R. Chu, S. Xiang, S. Liao, S.Z. Li. “Face Detection Based on Multi-Block LBP Representation”, In Proceedings: Advances in Biometrics, International Conference, ICB 2007, Seoul, Korea. http://www.cbsr.ia.ac.cn/users/scliao/papers/Zhang-ICB07-MBLBP.pdf DOI:10.1007/978-3-540-74549-5_2
Multi-Block Local Binary Pattern for texture classification
Local features for a single- or multi-channel nd image.
Intensity, gradient intensity and local structure are computed at different scales thanks to Gaussian blurring.
Input image, which can be grayscale or multichannel.
If True, pixel intensities averaged over the different scales are added to the feature set.
If True, intensities of local gradients averaged over the different scales are added to the feature set.
If True, eigenvalues of the Hessian matrix after Gaussian blurring at different scales are added to the feature set.
Smallest value of the Gaussian kernel used to average local neighborhoods before extracting features.
Find peaks in an image as coordinate list.
Peaks are the local maxima in a region of 2 * min_distance + 1
(i.e. peaks are separated by at least min_distance).
If both threshold_abs and threshold_rel are provided, the maximum
of the two is chosen as the minimum intensity threshold of peaks.
Plot matched features between two images.
First image.
Second image.
First keypoint coordinates as (row, col).
Second keypoint coordinates as (row, col).
Indices of corresponding matches in first and second sets of descriptors, where (resp. ) contains the indices in the first (resp. second) set of descriptors.
To make a sequence of colors passed to matches_color work for any number of
matches, you can wrap that sequence in itertools.cycle().
Compute the shape index.
The shape index, as defined by Koenderink & van Doorn [1], is a single valued measure of local curvature, assuming the image as a 3D plane with intensities representing heights.
It is derived from the eigenvalues of the Hessian, and its value ranges from -1 to 1 (and is undefined (=NaN) in flat regions), with following ranges representing following shapes:
Interval (s in …) | Shape |
|---|---|
[ -1, -7/8) | Spherical cup |
[-7/8, -5/8) | Through |
[-5/8, -3/8) | Rut |
[-3/8, -1/8) | Saddle rut |
[-1/8, +1/8) | Saddle |
[+1/8, +3/8) |
Input image.
Standard deviation used for the Gaussian kernel, which is used for smoothing the input data before Hessian eigen value calculation.
How to handle values outside the image borders
Used in conjunction with mode ‘constant’, the value outside the image boundaries.
Shape index
Koenderink, J. J. & van Doorn, A. J., “Surface shape and curvature scales”, Image and Vision Computing, 1992, 10, 557-564. DOI:10.1016/0262-8856(92)90076-F
>>> from skimage.feature import shape_index
>>> square = np.zeros((5, 5))
>>> square[2, 2] = 4
>>> s = shape_index(square, sigma=
Compute structure tensor using sum of squared differences.
The (2-dimensional) structure tensor A is defined as:
A = [Arr Arc]
[Arc Acc]
which is approximated by the weighted sum of squared differences in a local window around each pixel in the image. This formula can be extended to a larger number of dimensions (see [1]).
Input image.
Standard deviation used for the Gaussian kernel, which is used as a
weighting function for the local summation of squared differences.
If sigma is an iterable, its length must be equal to image.ndim and
each element is used for the Gaussian kernel applied along its
respective axis.
How to handle values outside the image borders.
Used in conjunction with mode ‘constant’, the value outside the image boundaries.
>>> from skimage.feature import structure_tensor
>>> square = np.zeros((5, 5))
>>> square[2, 2] = 1
>>> Arr, Arc, Acc = structure_tensor(
Compute eigenvalues of structure tensor.
The upper-diagonal elements of the structure tensor, as returned
by structure_tensor.
The eigenvalues of the structure tensor, in decreasing order. The eigenvalues are the leading dimension. That is, the coordinate [i, j, k] corresponds to the ith-largest eigenvalue at position (j, k).
>>> from skimage.feature import structure_tensor
>>> from skimage.feature import structure_tensor_eigenvalues
>>> square = np.zeros((5, 5))
>>> square[2, 2] = 1
>>> A_elems =
Bases: DescriptorExtractor
BRIEF binary descriptor extractor.
BRIEF (Binary Robust Independent Elementary Features) is an efficient feature point descriptor. It is highly discriminative even when using relatively few bits and is computed using simple intensity difference tests.
For each keypoint, intensity comparisons are carried out for a specifically distributed number N of pixel-pairs resulting in a binary descriptor of length N. For binary descriptors the Hamming distance can be used for feature matching, which leads to lower computational cost in comparison to the L2 norm.
Size of BRIEF descriptor for each keypoint. Sizes 128, 256 and 512 recommended by the authors. Default is 256.
Length of the two dimensional square patch sampling region around the keypoints. Default is 49.
Probability distribution for sampling location of decision pixel-pairs around keypoints.
numpy.random.Generator, int}, optionalPseudo-random number generator (RNG). By default, a PCG64 generator is used (see ). If is an int, it is used to seed the generator.
>>> from skimage.feature import (corner_harris, corner_peaks, BRIEF,
... match_descriptors)
>>> import numpy as np
>>> square1 = np.zeros((8, 8), dtype=
Extract BRIEF binary descriptors for given keypoints in image.
Input image.
Keypoint coordinates as (row, col).
Bases: FeatureDetector
CENSURE keypoint detector.
Minimum scale to extract keypoints from.
Maximum scale to extract keypoints from. The keypoints will be extracted from all the scales except the first and the last i.e. from the scales in the range [min_scale + 1, max_scale - 1]. The filter sizes for different scales is such that the two adjacent scales comprise of an octave.
Type of bi-level filter used to get the scales of the input image. Possible values are ‘DoB’, ‘Octagon’ and ‘STAR’. The three modes represent the shape of the bi-level filters i.e. box(square), octagon and star respectively. For instance, a bi-level octagon filter consists of a smaller inner octagon and a larger outer octagon with the filter weights being uniformly negative in both the inner octagon while uniformly positive in the difference region. Use STAR and Octagon for better features and DoB for better performance.
Threshold value used to suppress maximas and minimas with a weak magnitude response obtained after Non-Maximal Suppression.
Threshold for rejecting interest points which have ratio of principal curvatures greater than this value.
Keypoint coordinates as (row, col).
Corresponding scales.
Motilal Agrawal, Kurt Konolige and Morten Rufus Blas “CENSURE: Center Surround Extremas for Realtime Feature Detection and Matching”, https://link.springer.com/chapter/10.1007/978-3-540-88693-8_8 DOI:10.1007/978-3-540-88693-8_8
Adam Schmidt, Marek Kraft, Michal Fularz and Zuzanna Domagala “Comparative Assessment of Point Feature Detectors and Descriptors in the Context of Robot Navigation” http://yadda.icm.edu.pl/yadda/element/bwmeta1.element.baztech-268aaf28-0faf-4872-a4df-7e2e61cb364c/c/Schmidt_comparative.pdf DOI:10.1.1.465.1117
>>> from skimage.data import astronaut
>>> from skimage.color import rgb2gray
>>> from skimage.feature import CENSURE
>>> img = rgb2gray(astronaut()[100:300, 100:300])
>>>
Detect CENSURE keypoints along with the corresponding scale.
Input image.
Bases: object
Class for cascade of classifiers that is used for object detection.
The main idea behind cascade of classifiers is to create classifiers of medium accuracy and ensemble them into one strong classifier instead of just creating a strong one. The second advantage of cascade classifier is that easy examples can be classified only by evaluating some of the classifiers in the cascade, making the process much faster than the process of evaluating a one strong classifier.
Accuracy parameter. Increasing it, makes the classifier detect less false positives but at the same time the false negative score increases.
Amount of stages in a cascade. Each cascade consists of stumps i.e. trained features.
The overall amount of stumps in all the stages of cascade.
The overall amount of different features used by cascade. Two stumps can use the same features but has different trained values.
The width of a detection window that is used. Objects smaller than this window can’t be detected.
The height of a detection window.
A pointer to the C array that stores stages information using a Stage struct.
A pointer to the C array that stores MBLBP features using an MBLBP struct.
A pointer to the C array with look-up tables that are used by trained MBLBP features (MBLBPStumps) to evaluate a particular region.
The cascade approach was first described by Viola and Jones [1], [2], although these initial publications used a set of Haar-like features. This implementation instead uses multi-scale block local binary pattern (MB-LBP) features [3].
Viola, P. and Jones, M. “Rapid object detection using a boosted cascade of simple features,” In: Proceedings of the 2001 IEEE Computer Society Conference on Computer Vision and Pattern Recognition. CVPR 2001, pp. I-I. DOI:10.1109/CVPR.2001.990517
Viola, P. and Jones, M.J, “Robust Real-Time Face Detection”, International Journal of Computer Vision 57, 137–154 (2004). DOI:10.1023/B:VISI.0000013087.49260.fb
Liao, S. et al. Learning Multi-scale Block Local Binary Patterns for Face Recognition. International Conference on Biometrics (ICB), 2007, pp. 828-837. In: Lecture Notes in Computer Science, vol 4642. Springer, Berlin, Heidelberg. DOI:10.1007/978-3-540-74549-5_87
Initialize cascade classifier.
A file in a OpenCv format from which all the cascade classifier’s parameters are loaded.
Accuracy parameter. Increasing it, makes the classifier detect less false positives but at the same time the false negative score increases.
Search for the object on multiple scales of input image.
The function takes the input image, the scale factor by which the searching window is multiplied on each step, minimum window size and maximum window size that specify the interval for the search windows that are applied to the input image to detect objects.
Bases: FeatureDetector, DescriptorExtractor
Oriented FAST and rotated BRIEF feature detector and binary descriptor extractor.
Number of keypoints to be returned. The function will return the best
n_keypoints according to the Harris corner response if more than
n_keypoints are detected. If not, then all the detected keypoints
are returned.
The n parameter in skimage.feature.corner_fast. Minimum number of
consecutive pixels out of 16 pixels on the circle that should all be
either brighter or darker w.r.t test-pixel. A point c on the circle is
darker w.r.t test pixel p if Ic < Ip and brighter if
. Also stands for the n in corner
detector.
Ethan Rublee, Vincent Rabaud, Kurt Konolige and Gary Bradski “ORB: An efficient alternative to SIFT and SURF” http://www.vision.cs.chubu.ac.jp/CV-R/pdf/Rublee_iccv2011.pdf
>>> from skimage.feature import ORB, match_descriptors
>>> img1 = np.zeros((100, 100))
>>> img2 = np.zeros_like(img1)
>>> rng = np.random.
Detect oriented FAST keypoints along with the corresponding scale.
Input image.
Detect oriented FAST keypoints and extract rBRIEF descriptors.
Note that this is faster than first calling detect and then
extract.
Input image.
Extract rBRIEF binary descriptors for given keypoints in image.
Note that the keypoints must be extracted using the same downscale
and n_scales parameters. Additionally, if you want to extract both
keypoints and descriptors you should use the faster
detect_and_extract.
Bases: FeatureDetector, DescriptorExtractor
SIFT feature detection and descriptor extraction.
Prior to the feature detection the image is upscaled by a factor of 1 (no upscaling), 2 or 4. Method: Bi-cubic interpolation.
Maximum number of octaves. With every octave the image size is halved and the sigma doubled. The number of octaves will be reduced as needed to keep at least 12 pixels along each dimension at the smallest scale.
Maximum number of scales in every octave.
The blur level of the seed image. If upsampling is enabled sigma_min is scaled by factor 1/upsampling
thresholdthreshold_relthreshold_relA value between 0 and 1. If the area of two blobs overlaps by a
fraction greater than threshold, the smaller blob is eliminated.
Minimum intensity of peaks, calculated as
max(dog_space) * threshold_rel, where dog_space refers to the
stack of Difference-of-Gaussian (DoG) images computed internally. This
should have a value between 0 and 1. If None, threshold is used
instead.
If tuple of ints, the length of the tuple must match the input array’s
dimensionality. Each element of the tuple will exclude peaks from
within exclude_border-pixels of the border of the image along that
dimension.
If nonzero int, exclude_border excludes peaks from within
exclude_border-pixels of the border of the image.
If zero or False, peaks are identified regardless of their
distance from the border.
A 2d array with each row representing 2 coordinate values for a 2D
image, or 3 coordinate values for a 3D image, plus the sigma(s) used.
When a single sigma is passed, outputs are:
(r, c, sigma) or (p, r, c, sigma) where (r, c) or
(p, r, c) are coordinates of the blob and sigma is the standard
deviation of the Gaussian kernel which detected the blob. When an
anisotropic gaussian is used (sigmas per dimension), the detected sigma
is returned for each dimension.
The absolute lower bound for scale space maxima. Local maxima smaller
than threshold are ignored. Reduce this to detect blobs with lower
intensities. If threshold_rel is also specified, whichever threshold
is larger will be used. If None, threshold_rel is used instead.
A value between 0 and 1. If the area of two blobs overlaps by a
fraction greater than threshold, the smaller blob is eliminated.
If set intermediate values of standard deviations are interpolated
using a logarithmic scale to the base 10. If not, linear
interpolation is used.
Minimum intensity of peaks, calculated as
max(doh_space) * threshold_rel, where doh_space refers to the
stack of Determinant-of-Hessian (DoH) images computed internally. This
should have a value between 0 and 1. If None, threshold is used
instead.
A 2d array with each row representing 3 values, (y,x,sigma)
where (y,x) are coordinates of the blob and sigma is the
standard deviation of the Gaussian kernel of the Hessian Matrix whose
determinant detected the blob.
[min_sigma, max_sigma]The absolute lower bound for scale space maxima. Local maxima smaller
than threshold are ignored. Reduce this to detect blobs with lower
intensities. If threshold_rel is also specified, whichever threshold
is larger will be used. If None, threshold_rel is used instead.
A value between 0 and 1. If the area of two blobs overlaps by a
fraction greater than threshold, the smaller blob is eliminated.
If set intermediate values of standard deviations are interpolated
using a logarithmic scale to the base 10. If not, linear
interpolation is used.
Minimum intensity of peaks, calculated as
max(log_space) * threshold_rel, where log_space refers to the
stack of Laplacian-of-Gaussian (LoG) images computed internally. This
should have a value between 0 and 1. If None, threshold is used
instead.
If tuple of ints, the length of the tuple must match the input array’s
dimensionality. Each element of the tuple will exclude peaks from
within exclude_border-pixels of the border of the image along that
dimension.
If nonzero int, exclude_border excludes peaks from within
exclude_border-pixels of the border of the image.
If zero or False, peaks are identified regardless of their
distance from the border.
A 2d array with each row representing 2 coordinate values for a 2D
image, or 3 coordinate values for a 3D image, plus the sigma(s) used.
When a single sigma is passed, outputs are:
(r, c, sigma) or (p, r, c, sigma) where (r, c) or
(p, r, c) are coordinates of the blob and sigma is the standard
deviation of the Gaussian kernel which detected the blob. When an
anisotropic gaussian is used (sigmas per dimension), the detected sigma
is returned for each dimension.
The radius of each blob is approximately for a 2-D image and for a 3-D image.
>>> from skimage import data, feature, exposure
>>> img = data.coins()
>>> img = exposure.equalize_hist(img) # improves detection
>>> feature.blob_log(img, threshold = .3)
array([[124. , 336. , 11.88888889],
[198. , 155. , 11.88888889],
[194. , 213. , 17.33333333],
[121. , 272. , 17.33333333],
[263. , 244. , 17.33333333],
[194. , 276. , 17.33333333],
[266. , 115. , 11.88888889],
[128. , 154. , 11.88888889],
[260. , 174. , 17.33333333],
[198. , 103. , 11.88888889],
[126. , 208. , 11.88888889],
[127. , 102. , 11.88888889],
[263. , 302. , 17.33333333],
[197. , 44. , 11.88888889],
[185. , 344. , 17.33333333],
[126. , 46. , 11.88888889],
[113. , 323. , 1. ]])
TrueThe mode parameter determines how the array borders are
handled during Gaussian filtering, where cval is the value when
mode is equal to ‘constant’.
Value to fill past edges of input if mode is ‘constant’.
Harris response image.
Which Minkowski p-norm to use. Should be in the range [1, inf].
A finite large p may cause a ValueError if overflow can occur.
inf corresponds to the Chebyshev distance and 2 to the
Euclidean distance.
If indices = True : (row, column, …) coordinates of peaks.
If indices = False : Boolean array shaped like image, with peaks
represented by True values.
The num_peaks limit is applied before suppression of connected peaks.
To limit the number of peaks after suppression, set num_peaks=np.inf and
post-process the output of this function.
>>> from skimage.feature import peak_local_max
>>> response = np.zeros((5, 5))
>>> response[2:4, 2:4] = 1
>>> response
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 1., 1., 0.],
[0., 0., 1., 1., 0.],
[0., 0., 0., 0., 0.]])
>>> peak_local_max(response)
array([[2, 2],
[2, 3],
[3, 2],
[3, 3]])
>>> corner_peaks(response)
array([[2, 2]])
Radius (in pixels) of the outermost ring.
Number of rings.
Number of histograms sampled per ring.
Number of orientations (bins) per histogram.
How to normalize the descriptors
‘l1’: L1-normalization of each descriptor.
‘l2’: L2-normalization of each descriptor.
‘daisy’: L2-normalization of individual histograms.
‘off’: Disable normalization.
Standard deviation of spatial Gaussian smoothing for the center histogram and for each ring of histograms. The array of sigmas should be sorted from the center and out. I.e. the first sigma value defines the spatial smoothing of the center histogram and the last sigma value defines the spatial smoothing of the outermost ring. Specifying sigmas overrides the following parameter.
rings = len(sigmas) - 1
Radius (in pixels) for each ring. Specifying ring_radii overrides the following two parameters.
rings = len(ring_radii)radius = ring_radii[-1]
If both sigmas and ring_radii are given, they must satisfy the following predicate since no radius is needed for the center histogram.
len(ring_radii) == len(sigmas) + 1
Generate a visualization of the DAISY descriptors
Grid of DAISY descriptors for the given image as an array dimensionality (P, Q, R) where
P = ceil((M - radius*2) / step)Q = ceil((N - radius*2) / step)R = (rings * histograms + 1) * orientations
Visualization of the DAISY descriptors.
Floats specifying the color for the positive block. Corresponding values define (R, G, B) values. Default value is red (1, 0, 0).
Floats specifying the color for the negative block Corresponding values define (R, G, B) values. Default value is blue (0, 1, 0).
Value in the range [0, 1] that specifies opacity of visualization. 1 - fully transparent, 0 - opaque.
The maximum number of features to be returned. By default, all features are returned.
numpy.random.Generator, int}, optionalPseudo-random number generator.
By default, a PCG64 generator is used (see numpy.random.default_rng()).
If rng is an int, it is used to seed the generator.
The rng is used when generating a set of features smaller than the total number of available features.
Floats specifying the color for the block that has greater intensity value. They should be in the range [0, 1]. Corresponding values define (R, G, B) values. Default value is white (1, 1, 1).
Floats specifying the color for the block that has greater intensity value. They should be in the range [0, 1]. Corresponding values define (R, G, B) values. Default value is cyan (0, 0.69, 0.96).
Value in the range [0, 1] that specifies opacity of visualization. 1 - fully transparent, 0 - opaque.
Image with MB-LBP visualization.
levelslevelsIf True, the output matrix P[:, :, d, theta] is symmetric. This
is accomplished by ignoring the order of value pairs, so both
(i, j) and (j, i) are accumulated when (i, j) is encountered
for a given offset. The default is False.
If True, normalize each matrix P[:, :, d, theta] by dividing
by the total number of accumulated co-occurrences for the given
offset. The elements of the resulting matrix sum to 1. The
default is False.
The gray-level co-occurrence histogram. The value
P[i,j,d,theta] is the number of times that gray-level j
occurs at a distance d and at an angle theta from
gray-level i. If normed is False, the output is of
type uint32, otherwise it is float64. The dimensions are:
levels x levels x number of distances x number of angles.
Indicates whether the Hessian is computed by convolving with Gaussian derivatives, or by a simple finite-difference operation.
Upper-diagonal elements of the hessian matrix for each pixel in the
input image. In 2D, this will be a three element list containing [Hrr,
Hrc, Hcc]. In nD, the list will contain (n**2 + n) / 2 arrays.
Size (in pixels) of a cell.
Number of cells in each block.
Block normalization method:
L1Normalization using L1-norm.
L1-sqrtNormalization using L1-norm, followed by square root.
L2Normalization using L2-norm.
L2-HysNormalization using L2-norm, followed by limiting the
maximum values to 0.2 (Hys stands for hysteresis) and
renormalization using L2-norm. (default)
For details, see [3], [4].
Also return an image of the HOG. For each cell and orientation bin, the image contains a line segment that is centered at the cell center, is perpendicular to the midpoint of the range of angles spanned by the orientation bin, and has intensity proportional to the corresponding histogram value.
Apply power law compression to normalize the image before
processing. DO NOT use this if the image contains negative
values. Also see notes section below.
Return the data as a feature vector by calling .ravel() on the result just before returning.
If None, the image is assumed to be a grayscale (single channel) image. Otherwise, this parameter indicates which axis of the array corresponds to channels.
HOG descriptor for the image. If feature_vector is True, a 1D
(flattened) array is returned.
A visualisation of the HOG image. Only provided if visualize is True.
If the image is too small given the values of pixels_per_cell and cells_per_block.
The presented code implements the HOG extraction method from [2] with the following changes: (I) blocks of (3, 3) cells are used ((2, 2) in the paper); (II) no smoothing within cells (Gaussian spatial window with sigma=8pix in the paper); (III) L1 block normalization is used (L2-Hys in the paper).
Power law compression, also known as Gamma correction, is used to reduce
the effects of shadowing and illumination variations. The compression makes
the dark regions lighter. When the kwarg transform_sqrt is set to
True, the function computes the square root of each color channel
and then applies the hog algorithm to the image.
Dalal, N and Triggs, B, Histograms of Oriented Gradients for Human Detection, IEEE Computer Society Conference on Computer Vision and Pattern Recognition 2005 San Diego, CA, USA, https://lear.inrialpes.fr/people/triggs/pubs/Dalal-cvpr05.pdf, DOI:10.1109/CVPR.2005.177
Lowe, D.G., Distinctive image features from scale-invatiant keypoints, International Journal of Computer Vision (2004) 60: 91, http://www.cs.ubc.ca/~lowe/papers/ijcv04.pdf, DOI:10.1023/B:VISI.0000029664.99615.94
Dalal, N, Finding People in Images and Videos, Human-Computer Interaction [cs.HC], Institut National Polytechnique de Grenoble - INPG, 2006, https://tel.archives-ouvertes.fr/tel-00390303/file/NavneetDalalThesis.pdf
sklearn.mixture.GaussianMixtureThe estimated GMM object, which contains the necessary parameters needed to compute the Fisher vector.
Variance of local image texture (related to contrast) which is rotation invariant but not grayscale invariant.
Largest value of the Gaussian kernel used to average local neighborhoods before extracting features.
Number of values of the Gaussian kernel between sigma_min and sigma_max. If None, sigma_min multiplied by powers of 2 are used.
The number of parallel threads to use. If set to None, the full
set of available cores are used.
If None, the image is assumed to be a grayscale (single channel) image. Otherwise, this parameter indicates which axis of the array corresponds to channels.
Array of shape image.shape + (n_features,). When channel_axis is
not None, all channels are concatenated along the features dimension.
(i.e. n_features == n_features_singlechannel * n_channels)
Trainable segmentation using local features and random forests
Input image.
The minimal allowed distance separating peaks. To find the
maximum number of peaks, use min_distance=1.
Minimum intensity of peaks. By default, the absolute threshold is the minimum intensity of the image.
Minimum intensity of peaks, calculated as
max(image) * threshold_rel.
If positive integer, exclude_border excludes peaks from within
exclude_border-pixels of the border of the image.
If tuple of non-negative ints, the length of the tuple must match the
input array’s dimensionality. Each element of the tuple will exclude
peaks from within exclude_border-pixels of the border of the image
along that dimension.
If True, takes the min_distance parameter as value.
If zero or False, peaks are identified regardless of their distance
from the border.
Maximum number of peaks. When the number of peaks exceeds num_peaks,
return num_peaks peaks based on highest peak intensity.
If provided, footprint == 1 represents the local region within which
to search for peaks at every point in image.
If provided, each unique region labels == value represents a unique
region to search for peaks. Zero is reserved for background.
Maximum number of peaks for each label.
Which Minkowski p-norm to use. Should be in the range [1, inf].
A finite large p may cause a ValueError if overflow can occur.
inf corresponds to the Chebyshev distance and 2 to the
Euclidean distance.
The coordinates of the peaks.
The peak local maximum function returns the coordinates of local peaks (maxima) in an image. Internally, a maximum filter is used for finding local maxima. This operation dilates the original image. After comparison of the dilated and original images, this function returns the coordinates of the peaks where the dilated image equals the original image.
>>> img1 = np.zeros((7, 7))
>>> img1[3, 4] = 1
>>> img1[3, 2] = 1.5
>>> img1
array([[0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 1.5, 0. , 1. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. , 0. , 0. ]])
>>> peak_local_max(img1, min_distance=1)
array([[3, 2],
[3, 4]])
>>> peak_local_max(img1, min_distance=2)
array([[3, 2]])
>>> img2 = np.zeros((20, 20, 20))
>>> img2[10, 10, 10] = 1
>>> img2[15, 15, 15] = 1
>>> peak_idx = peak_local_max(img2, exclude_border=0)
>>> peak_idx
array([[10, 10, 10],
[15, 15, 15]])
>>> peak_mask = np.zeros_like(img2, dtype=bool)
>>> peak_mask[tuple(peak_idx.T)] = True
>>> np.argwhere(peak_mask)
array([[10, 10, 10],
[15, 15, 15]])
matches[:, 0]matches[:, 1]The Axes object where the images and their matched features are drawn.
Color for keypoint locations.
Single color or sequence of colors for each line defined by matches,
which connect keypoint matches. See [1] for an overview of supported
color formats. By default, colors are picked randomly.
Set to True to plot matches only and not the keypoint locations.
Whether to show the two images side by side ('horizontal'), or one above
the other ('vertical').
Saddle ridge
[+3/8, +5/8) | Ridge |
[+5/8, +7/8) | Dome |
[+7/8, +1] | Spherical cap |
NOTE: ‘xy’ is only an option for 2D images, higher dimensions must always use ‘rc’ order. This parameter allows for the use of reverse or forward order of the image axes in gradient computation. ‘rc’ indicates the use of the first axis initially (Arr, Arc, Acc), whilst ‘xy’ indicates the usage of the last axis initially (Axx, Axy, Ayy).
Upper-diagonal elements of the structure tensor for each pixel in the input image.
numpy.random.default_rng()rngThe PRNG is used for the random sampling of the decision
pixel-pairs. From a square window with length patch_size,
pixel pairs are sampled using the mode parameter to build
the descriptors using intensity comparison.
For matching across images, the same rng should be used to construct
descriptors. To facilitate this:
rng defaults to 1
Subsequent calls of the extract method will use the same rng/seed.
Standard deviation of the Gaussian low-pass filter applied to the image to alleviate noise sensitivity, which is strongly recommended to obtain discriminative and good descriptors.
descriptor_size) array of dtype bool2D ndarray of binary descriptors of size descriptor_size for Q
keypoints after filtering out border keypoints with value at an
index (i, j) either being True or False representing
the outcome of the intensity comparison for i-th keypoint on j-th
decision pixel-pair. It is Q == np.sum(mask).
Mask indicating whether a keypoint has been filtered out
(False) or is described in the descriptors array (True).
Ndarray that represents the input image.
The scale by which searching window is multiplied on each step.
The ratio by which the search step in multiplied on each scale of the image. 1 represents the exaustive search and usually is slow. By setting this parameter to higher values the results will be worse but the computation will be much faster. Usually, values in the interval [1, 1.5] give good results.
Minimum size of the search window.
Maximum size of the search window.
Minimum amount of intersecting detections in order for detection to be approved by the function.
The minimum value of value of ratio (intersection area) / (small rectangle ratio) in order to merge two detections into one.
Dict have form {‘r’: int, ‘c’: int, ‘width’: int, ‘height’: int}, where ‘r’ represents row position of top left corner of detected window, ‘c’ - col position, ‘width’ - width of detected window, ‘height’ - height of detected window.
Ic > Ip + thresholdFAST-nThe threshold parameter in feature.corner_fast. Threshold used
to decide whether the pixels on the circle are brighter, darker or
similar w.r.t. the test pixel. Decrease the threshold when more
corners are desired and vice-versa.
The k parameter in skimage.feature.corner_harris. Sensitivity
factor to separate corners from edges, typically in range [0, 0.2].
Small values of k result in detection of sharp corners.
Downscale factor for the image pyramid. Default value 1.2 is chosen so that there are more dense scales which enable robust scale invariance for a subsequent feature description.
Maximum number of scales from the bottom of the image pyramid to extract the features from.
Keypoint coordinates as (row, col).
Corresponding scales.
Corresponding orientations in radians.
Corresponding Harris corner responses.
descriptor_size) array of dtype bool2D array of binary descriptors of size descriptor_size for Q
keypoints after filtering out border keypoints with value at an
index (i, j) either being True or False representing
the outcome of the intensity comparison for i-th keypoint on j-th
decision pixel-pair. It is Q == np.sum(mask).
Input image.
Keypoint coordinates as (row, col).
Corresponding scales.
Corresponding orientations in radians.
The assumed blur level of the input image.
Threshold to discard low contrast extrema in the DoG. It’s final value is dependent on n_scales by the relation: final_c_dog = (2^(1/n_scales)-1) / (2^(1/3)-1) * c_dog
Threshold to discard extrema that lie in edges. If H is the Hessian of an extremum, its “edgeness” is described by tr(H)²/det(H). If the edgeness is higher than (c_edge + 1)²/c_edge, the extremum is discarded.
Number of bins in the histogram that describes the gradient orientations around keypoint.
The window used to find the reference orientation of a keypoint has a width of 6 * lambda_ori * sigma and is weighted by a standard deviation of 2 * lambda_ori * sigma.
The threshold at which a secondary peak in the orientation histogram is accepted as orientation
The window used to define the descriptor of a keypoint has a width of 2 * lambda_descr * sigma * (n_hist+1)/n_hist and is weighted by a standard deviation of lambda_descr * sigma.
The window used to define the descriptor of a keypoint consists of n_hist * n_hist histograms.
The number of bins in the histograms of the descriptor patch.
The sampling distance of the first octave. It’s final value is 1/upsampling.
The datatype of the image.
The sigma value of all scales in all octaves.
Keypoint coordinates as (row, col).
Subpixel-precision keypoint coordinates as (row, col).
The corresponding sigma (blur) value of a keypoint.
The corresponding scale of a keypoint.
The orientations of the gradient around every keypoint.
The corresponding octave of a keypoint.
The descriptors of a keypoint.
The SIFT algorithm was developed by David Lowe [1], [2] and later patented by the University of British Columbia. Since the patent expired in 2020 it’s free to use. The implementation here closely follows the detailed description in [3], including use of the same default parameters.
D.G. Lowe. “Object recognition from local scale-invariant features”, Proceedings of the Seventh IEEE International Conference on Computer Vision, 1999, vol.2, pp. 1150-1157. DOI:10.1109/ICCV.1999.790410
D.G. Lowe. “Distinctive Image Features from Scale-Invariant Keypoints”, International Journal of Computer Vision, 2004, vol. 60, pp. 91–110. DOI:10.1023/B:VISI.0000029664.99615.94
I. R. Otero and M. Delbracio. “Anatomy of the SIFT Method”, Image Processing On Line, 4 (2014), pp. 370–396. DOI:10.5201/ipol.2014.82
>>> from skimage.feature import SIFT, match_descriptors
>>> from skimage.data import camera
>>> from skimage.transform import rotate
>>> img1 = camera()
>>> img2 = rotate(camera(), 90)
>>> detector_extractor1 = SIFT()
>>> detector_extractor2 = SIFT()
>>> detector_extractor1.detect_and_extract(img1)
>>> detector_extractor2.detect_and_extract(img2)
>>> matches = match_descriptors(detector_extractor1.descriptors,
... detector_extractor2.descriptors,
... max_ratio=0.6)
>>> matches[10:15]
array([[ 10, 412],
[ 11, 417],
[ 12, 407],
[ 13, 411],
[ 14, 406]])
>>> detector_extractor1.keypoints[matches[10:15, 0]]
array([[ 95, 214],
[ 97, 211],
[ 97, 218],
[102, 215],
[104, 218]])
>>> detector_extractor2.keypoints[matches[10:15, 1]]
array([[297, 95],
[301, 97],
[294, 97],
[297, 102],
[293, 104]])
The sampling distances of all octaves
Detect the keypoints.
Input image.
Detect the keypoints and extract their descriptors.
Input image.
Extract the descriptors for all keypoints in the image.
Input image.