
    1-Ph                        d dl Z d dlZd dlmZ d dlZd dlmZ d dlm	Z	m
Z
 ddlmZ ddlmZmZmZ ddlmZ dd	lmZ d
dlmZ d
dlmZmZmZ d
dlmZ d
dlmZmZ d.dZd/dZ d0dZ!	 d1dZ"d2dZ#d Z$d Z%d Z&d Z'd3dZ(d.dZ)d4d!Z*d5d"Z+d5d#Z,d6d&Z-d7d)Z.d
ddddej/        ddfej/        ej/        d*d+Z0d5d,Z1d- Z2dS )8    N)combinations_with_replacement)ndimage)spatialstats   gaussian)_supported_float_typesafe_as_intwarn)integral_image)img_as_float   )_hessian_matrix_det)_corner_fast_corner_moravec_corner_orientations)peak_local_max)_prepare_grayscale_input_2D_prepare_grayscale_input_nDconstantc                 P      fdt           j                  D             }|S )a  Compute derivatives in axis directions using the Sobel operator.

    Parameters
    ----------
    image : ndarray
        Input image.
    mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional
        How to handle values outside the image borders.
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    Returns
    -------
    derivatives : list of ndarray
        Derivatives in each axis direction.

    c                 @    g | ]}t          j        |           S ))axismodecval)ndisobel).0ir   imager   s     V/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/skimage/feature/corner.py
<listcomp>z(_compute_derivatives.<locals>.<listcomp>'   s9       ;<	%ad666      )rangendim)r!   r   r   derivativess   ``` r"   _compute_derivativesr(      sI    (     @Eej@Q@Q  K r$   rcc                    |dk    r| j         dk    rt          d          |dvrt          d| d          t          j                  s6t	                    t                    | j         k    rt          d          t          |           } t          |           }|dk    rt          |          }fd	t          |d          D             }|S )
a  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]_).

    Parameters
    ----------
    image : ndarray
        Input image.
    sigma : float or array-like of float, optional
        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.
    mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional
        How to handle values outside the image borders.
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.
    order : {'rc', 'xy'}, optional
        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).

    Returns
    -------
    A_elems : list of ndarray
        Upper-diagonal elements of the structure tensor for each pixel in the
        input image.

    Examples
    --------
    >>> from skimage.feature import structure_tensor
    >>> square = np.zeros((5, 5))
    >>> square[2, 2] = 1
    >>> Arr, Arc, Acc = structure_tensor(square, sigma=0.1, order='rc')
    >>> Acc
    array([[0., 0., 0., 0., 0.],
           [0., 1., 0., 1., 0.],
           [0., 4., 0., 4., 0.],
           [0., 1., 0., 1., 0.],
           [0., 0., 0., 0., 0.]])

    See also
    --------
    structure_tensor_eigenvalues

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Structure_tensor
    xyr   z)Only "rc" order is supported for dim > 2.r)   r+   zorder z( is invalid. Must be either "rc" or "xy"z2sigma must have as many elements as image has axesr   r   c                 B    g | ]\  }}t          ||z             S )sigmar   r   r   )r   der0der1r   r   r0   s      r"   r#   z$structure_tensor.<locals>.<listcomp>~   sB       D$ 	E4@@@  r$   )
r&   
ValueErrornpisscalartuplelenr   r(   reversedr   )r!   r0   r   r   orderr'   A_elemss    ```   r"   structure_tensorr;   .   s	   z }}aDEEEL  Q%QQQRRR;u Veu::##TUUU'..E&u4dCCCK}}{++     7QGG  G
 Nr$   reflectc                 H    t                      t           j                  }                     |d            j        dk    r|dk    rt          d          |dvrt          d|           t          j        |          r|f j        z  }t          d |D                       rd	nd
}dt          j
        d          z  t          fd|D                       }t          ||||          }t          j        t          j        fi | j        t          fdt#                    D                        fdt#                    D             t#                    }	|dk    rt%          |	          }	fdt'          |	d          D             }
|
S )a,  Compute the Hessian via convolutions with Gaussian derivatives.

    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.

    Parameters
    ----------
    image : ndarray
        Input image.
    sigma : float or sequence of float, optional
        Standard deviation used for the Gaussian kernel, which sets the
        amount of smoothing in terms of pixel-distances. It is
        advised to not choose a sigma much less than 1.0, otherwise
        aliasing artifacts may occur.
    mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional
        How to handle values outside the image borders.
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.
    order : {'rc', 'xy'}, optional
        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)

    Returns
    -------
    H_elems : list of ndarray
        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.

    Fcopyr   r+   +order='xy' is only supported for 2D images.r,   unrecognized order: c              3   "   K   | ]
}|d k    V  dS )r   N )r   ss     r"   	<genexpr>z0_hessian_matrix_with_gaussian.<locals>.<genexpr>   s&      --!A------r$      d   r   c              3   "   K   | ]	}|z  V  
d S )NrC   )r   rD   sq1_2s     r"   rE   z0_hessian_matrix_with_gaussian.<locals>.<genexpr>   s'      22q222222r$   )r0   r   r   truncatec              3   F   K   | ]}d g|z  dgz   d g|z
  dz
  z  z   V  dS )r   r   NrC   )r   dr&   s     r"   rE   z0_hessian_matrix_with_gaussian.<locals>.<genexpr>   sC      MMAA37aS=A3$(Q,#77MMMMMMr$   c                 6    g | ]} |                    S r9   rC   )r   rL   	gaussian_r!   orderss     r"   r#   z1_hessian_matrix_with_gaussian.<locals>.<listcomp>   s,    HHHq5q	222HHHr$   c                 H    g | ]\  }} |         |                    S rN   rC   )r   ax0ax1rP   	gradientsrQ   s      r"   r#   z1_hessian_matrix_with_gaussian.<locals>.<listcomp>   sD       C 		)C.s444  r$   )r   r
   dtypeastyper&   r3   r4   r5   allmathsqrtr6   dict	functoolspartialr   gaussian_filterr%   r8   r   )r!   r0   r   r   r9   float_dtyperJ   sigma_scaledcommon_kwargsaxesH_elemsrP   rU   r&   rQ   rI   s   `          @@@@@r"   _hessian_matrix_with_gaussianrd      s   P E'44KLL5L11EzA~~%4--FGGGL  777888	{5 &5:% --u-----6qq3H	!E2222E22222L|$THUUUM!#"5GGGGI :D
 MMMMtMMMMMFHHHHHHE$KKHHHI ;;D}}~~     5dA>>  G Nr$   c                 "  
 t          |           } t          | j                  }|                     |d          } | j        dk    r|dk    rt          d          |dvrt          d|           |d}t          d	t          d
           |rt          | ||||          S t          | |||          }t          j        |          
t          | j                  }|dk    rt          |          }
fdt          |d          D             }	|	S )a
  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.

    Parameters
    ----------
    image : ndarray
        Input image.
    sigma : float
        Standard deviation used for the Gaussian kernel, which is used as
        weighting function for the auto-correlation matrix.
    mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional
        How to handle values outside the image borders.
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.
    order : {'rc', 'xy'}, optional
        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.
    use_gaussian_derivatives : boolean, optional
        Indicates whether the Hessian is computed by convolving with Gaussian
        derivatives, or by a simple finite-difference operation.

    Returns
    -------
    H_elems : list of ndarray
        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.


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

    .. math::

        \frac{\partial }{\partial x_i}(I * G) =
        I * \left( \frac{\partial }{\partial x_i} G \right)

    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.

    Examples
    --------
    >>> from skimage.feature import hessian_matrix
    >>> square = np.zeros((5, 5))
    >>> square[2, 2] = 4
    >>> Hrr, Hrc, Hcc = hessian_matrix(square, sigma=0.1, order='rc',
    ...                                use_gaussian_derivatives=False)
    >>> Hrc
    array([[ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  1.,  0., -1.,  0.],
           [ 0.,  0.,  0.,  0.,  0.],
           [ 0., -1.,  0.,  1.,  0.],
           [ 0.,  0.,  0.,  0.,  0.]])

    Fr>   r   r+   r@   r,   rA   Nzuse_gaussian_derivatives currently defaults to False, but will change to True in a future version. Please specify this argument explicitly to maintain the current behavior)category
stacklevel)r0   r   r   r9   r/   c                 N    g | ]!\  }}t          j        |         |           "S )r   )r4   gradient)r   rS   rT   rU   s      r"   r#   z"hessian_matrix.<locals>.<listcomp>N  s@       C 	IcN---  r$   )r   r
   rV   rW   r&   r3   r   FutureWarningrd   r	   r4   rj   r%   r8   r   )r!   r0   r   r   r9   use_gaussian_derivativesr_   gaussian_filteredrb   rc   rU   s             @r"   hessian_matrixrn      s]   \ E'44KLL5L11EzA~~%4--FGGGL  777888'#( C #	
 	
 	
 	
   
,TE
 
 
 	
 !e$TJJJ-..ID}}~~   5dA>>  G Nr$   Tc                 n   t          |           } t          | j                  }|                     |d          } | j        dk    r3|r1t          |           }t          j        t          ||                    S t          t          | |d                    }t          j                            |          S )a  Compute the approximate Hessian Determinant over an image.

    The 2D approximate method uses box filters over integral images to
    compute the approximate Hessian Determinant.

    Parameters
    ----------
    image : ndarray
        The image over which to compute the Hessian Determinant.
    sigma : float, optional
        Standard deviation of the Gaussian kernel used for the Hessian
        matrix.
    approximate : bool, optional
        If ``True`` and the image is 2D, use a much faster approximate
        computation. This argument has no effect on 3D and higher images.

    Returns
    -------
    out : array
        The array of the Determinant of Hessians.

    References
    ----------
    .. [1] 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

    Notes
    -----
    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.
    Fr>   r   )rl   )r   r
   rV   rW   r&   r   r4   arrayr   _symmetric_imagern   linalgdet)r!   r0   approximater_   integralhessian_mat_arrays         r"   hessian_matrix_detrw   U  s    H E'44KLL5L11EzQ;!%((x+He<<===,5%%HHH
 
 y}}.///r$   c                    t          |           dk    r{| \  }}}t          j        dg|j        R |j                  }||z   dz  |dd<   t          j        |dz  ||z
  dz  dz  z             }|dxx         |z  cc<   |dxx         |z  cc<   |S t          |           }t          j                            |          ddddf         }t          t          |j        dz
                      }t          j        ||j        dz
  f|z             S )a  Compute eigenvalues from the upper-diagonal entries of a symmetric
    matrix.

    Parameters
    ----------
    S_elems : list of ndarray
        The upper-diagonal elements of the matrix, as returned by
        `hessian_matrix` or `structure_tensor`.

    Returns
    -------
    eigs : ndarray
        The eigenvalues of the 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).
       r   Nr   r   .)r7   r4   emptyshaperV   rZ   rq   rr   eigvalshr6   r%   r&   	transpose)S_elemsM00M01M11eigshsqrtdetmatricesleading_axess           r"   _symmetric_compute_eigenvaluesr     s   $ 7||qS#xSY339/QQQ736cCi1_$::;;Q8Q8#G,,y!!(++C2I6U49q=1122|D49q="2\"ABBBr$   c                 (   | d         }t          j        |j        |j        |j        fz   | d         j                  }t          t          t          |j                  d                    D ]$\  }\  }}| |         |d||f<   | |         |d||f<   %|S )a  Convert the upper-diagonal elements of a matrix to the full
    symmetric matrix.

    Parameters
    ----------
    S_elems : list of array
        The upper-diagonal elements of the matrix, as returned by
        `hessian_matrix` or `structure_tensor`.

    Returns
    -------
    image : array
        An array of shape ``(M, N[, ...], image.ndim, image.ndim)``,
        containing the matrix corresponding to each coordinate.
    r   rV   r   .)r4   zerosr|   r&   rV   	enumerater   r%   )r   r!   symmetric_imageidxrowcols         r"   rq   rq     s      AJEhuz5:..gaj6F  O %%eEJ&7&7;;  6 6Zc3 *1S#&)0S#&&r$   c                      t          |           S )a  Compute eigenvalues of structure tensor.

    Parameters
    ----------
    A_elems : list of ndarray
        The upper-diagonal elements of the structure tensor, as returned
        by `structure_tensor`.

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

    Examples
    --------
    >>> from skimage.feature import structure_tensor
    >>> from skimage.feature import structure_tensor_eigenvalues
    >>> square = np.zeros((5, 5))
    >>> square[2, 2] = 1
    >>> A_elems = structure_tensor(square, sigma=0.1, order='rc')
    >>> structure_tensor_eigenvalues(A_elems)[0]
    array([[0., 0., 0., 0., 0.],
           [0., 2., 4., 2., 0.],
           [0., 4., 0., 4., 0.],
           [0., 2., 4., 2., 0.],
           [0., 0., 0., 0., 0.]])

    See also
    --------
    structure_tensor
    r   )r:   s    r"   structure_tensor_eigenvaluesr     s    D *'222r$   c                      t          |           S )a  Compute eigenvalues of Hessian matrix.

    Parameters
    ----------
    H_elems : list of ndarray
        The upper-diagonal elements of the Hessian matrix, as returned
        by `hessian_matrix`.

    Returns
    -------
    eigs : ndarray
        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).

    Examples
    --------
    >>> from skimage.feature import hessian_matrix, hessian_matrix_eigvals
    >>> square = np.zeros((5, 5))
    >>> square[2, 2] = 4
    >>> H_elems = hessian_matrix(square, sigma=0.1, order='rc',
    ...                          use_gaussian_derivatives=False)
    >>> hessian_matrix_eigvals(H_elems)[0]
    array([[ 0.,  0.,  2.,  0.,  0.],
           [ 0.,  1.,  0.,  1.,  0.],
           [ 2.,  0., -2.,  0.,  2.],
           [ 0.,  1.,  0.,  1.,  0.],
           [ 0.,  0.,  2.,  0.,  0.]])
    r   )rc   s    r"   hessian_matrix_eigvalsr     s    < *'222r$   c                 
   t          | |||dd          }t          |          \  }}t          j        dd          5  dt          j        z  t          j        ||z   ||z
  z            z  cddd           S # 1 swxY w Y   dS )a~  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:

    .. table:: Ranges of the shape index and corresponding 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)         Saddle ridge
      [+3/8, +5/8)         Ridge
      [+5/8, +7/8)         Dome
      [+7/8,   +1]         Spherical cap
      ===================  =============

    Parameters
    ----------
    image : (M, N) ndarray
        Input image.
    sigma : float, optional
        Standard deviation used for the Gaussian kernel, which is used for
        smoothing the input data before Hessian eigen value calculation.
    mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional
        How to handle values outside the image borders
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    Returns
    -------
    s : ndarray
        Shape index

    References
    ----------
    .. [1] 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`

    Examples
    --------
    >>> from skimage.feature import shape_index
    >>> square = np.zeros((5, 5))
    >>> square[2, 2] = 4
    >>> s = shape_index(square, sigma=0.1)
    >>> s
    array([[ nan,  nan, -0.5,  nan,  nan],
           [ nan, -0. ,  nan, -0. ,  nan],
           [-0.5,  nan, -1. ,  nan, -0.5],
           [ nan, -0. ,  nan, -0. ,  nan],
           [ nan,  nan, -0.5,  nan,  nan]])
    r)   F)r0   r   r   r9   rl   ignore)divideinvalidg       @N)rn   r   r4   errstatepiarctan)r!   r0   r   r   Hl1l2s          r"   shape_indexr   
  s    D 	!&	 	 	A $A&&FB 
Hh	7	7	7 @ @bery"r'b2g)>???@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @s   -A88A<?A<c                    t          | j                  }|                     |d          } t          | ||          \  }}t          |||          \  }}t          |||          \  }}	||dz  z  ||dz  z  z   d|z  |z  |z  z
  }
|dz  |dz  z   }t	          j        | |          }|dk    }|
|         ||         z  ||<   |S )a  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.

    Parameters
    ----------
    image : (M, N) ndarray
        Input image.
    mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional
        How to handle values outside the image borders.
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.

    Returns
    -------
    response : ndarray
        Kitchen and Rosenfeld response image.

    References
    ----------
    .. [1] Kitchen, L., & Rosenfeld, A. (1982). Gray-level corner detection.
           Pattern recognition letters, 1(2), 95-102.
           :DOI:`10.1016/0167-8655(82)90020-4`
    Fr>   r-   r   r   r   )r
   rV   rW   r(   r4   
zeros_like)r!   r   r   r_   imyimximxyimxximyyimyx	numeratordenominatorresponsemasks                 r"   corner_kitchen_rosenfeldr   [  s    B (44KLL5L11E#E4@@@HC%c4@@@JD$%c4@@@JD$sAvsAv-D30DDIq&36/K}U+666H!Dt_{4'88HTNOr$   k皙?ư>c                     t          | |d          \  }}}||z  |dz  z
  }||z   }	|dk    r|||	dz  z  z
  }
nd|z  |	|z   z  }
|
S )a  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)

    Parameters
    ----------
    image : (M, N) ndarray
        Input image.
    method : {'k', 'eps'}, optional
        Method to compute the response image from the auto-correlation matrix.
    k : float, optional
        Sensitivity factor to separate corners from edges, typically in range
        `[0, 0.2]`. Small values of k result in detection of sharp corners.
    eps : float, optional
        Normalisation factor (Noble's corner measure).
    sigma : float, optional
        Standard deviation used for the Gaussian kernel, which is used as
        weighting function for the auto-correlation matrix.

    Returns
    -------
    response : ndarray
        Harris response image.

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Corner_detection

    Examples
    --------
    >>> from skimage.feature import corner_harris, corner_peaks
    >>> square = np.zeros([10, 10])
    >>> square[2:8, 2:8] = 1
    >>> square.astype(int)
    array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
    >>> corner_peaks(corner_harris(square), min_distance=1)
    array([[2, 2],
           [2, 7],
           [7, 2],
           [7, 7]])

    r)   rO   r   r   )r;   )r!   methodr   epsr0   ArrArcAccdetAtraceAr   s              r"   corner_harrisr     sp    B %UE>>>MCc 9sAvD3YF}}!fai-'t8v|,Or$   c                     t          | |d          \  }}}||z   t          j        ||z
  dz  d|dz  z  z             z
  dz  }|S )a`  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

    Parameters
    ----------
    image : (M, N) ndarray
        Input image.
    sigma : float, optional
        Standard deviation used for the Gaussian kernel, which is used as
        weighting function for the auto-correlation matrix.

    Returns
    -------
    response : ndarray
        Shi-Tomasi response image.

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Corner_detection

    Examples
    --------
    >>> from skimage.feature import corner_shi_tomasi, corner_peaks
    >>> square = np.zeros([10, 10])
    >>> square[2:8, 2:8] = 1
    >>> square.astype(int)
    array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
    >>> corner_peaks(corner_shi_tomasi(square), min_distance=1)
    array([[2, 2],
           [2, 7],
           [7, 2],
           [7, 7]])

    r)   rO   r      )r;   r4   rZ   )r!   r0   r   r   r   r   s         r"   corner_shi_tomasir     sY    l %UE>>>MCc sbgsSyQ&6S!V&CDDDIHOr$   c                    t          | |d          \  }}}||z  |dz  z
  }||z   }t          j        | |j                  }t          j        |          }|dk    }	||	         ||	         z  ||	<   d||	         z  ||	         dz  z  ||	<   ||fS )u  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)

    Parameters
    ----------
    image : (M, N) ndarray
        Input image.
    sigma : float, optional
        Standard deviation used for the Gaussian kernel, which is used as
        weighting function for the auto-correlation matrix.

    Returns
    -------
    w : ndarray
        Error ellipse sizes.
    q : ndarray
        Roundness of error ellipse.

    References
    ----------
    .. [1] 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
    .. [2] https://en.wikipedia.org/wiki/Corner_detection

    Examples
    --------
    >>> from skimage.feature import corner_foerstner, corner_peaks
    >>> square = np.zeros([10, 10])
    >>> square[2:8, 2:8] = 1
    >>> square.astype(int)
    array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
    >>> w, q = corner_foerstner(square)
    >>> accuracy_thresh = 0.5
    >>> roundness_thresh = 0.3
    >>> foerstner = (q > roundness_thresh) * (w > accuracy_thresh) * w
    >>> corner_peaks(foerstner, min_distance=1)
    array([[2, 2],
           [2, 7],
           [7, 2],
           [7, 7]])

    r)   rO   r   r   r   r   )r;   r4   r   rV   )
r!   r0   r   r   r   r   r   wqr   s
             r"   corner_foerstnerr     s    D %UE>>>MCc 9sAvD3YF
e4:...A
aAQ;D4j6$<'AdG$t*nvd|q00AdGa4Kr$      333333?c                 n    t          |           } t          j        |           } t          | ||          }|S )a  Extract FAST corners for a given image.

    Parameters
    ----------
    image : (M, N) ndarray
        Input image.
    n : int, optional
        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 : float, optional
        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.

    Returns
    -------
    response : ndarray
        FAST corner response image.

    References
    ----------
    .. [1] 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
    .. [2] Wikipedia, "Features from accelerated segment test",
           https://en.wikipedia.org/wiki/Features_from_accelerated_segment_test

    Examples
    --------
    >>> from skimage.feature import corner_fast, corner_peaks
    >>> square = np.zeros((12, 12))
    >>> square[3:9, 3:9] = 1
    >>> square.astype(int)
    array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
    >>> corner_peaks(corner_fast(square, 9), min_distance=1)
    array([[3, 3],
           [3, 8],
           [8, 3],
           [8, 8]])

    )r   r4   ascontiguousarrayr   )r!   n	thresholdr   s       r"   corner_fastr   p  s8    t (..E ''EE1i00HOr$      Gz?c                 	   |dz
  dz  }t          | j                  }|                     |d          } t          j        | |dd          } t          ||z             }t          j        d|	          }t          j        d|	          }t          j        d
|	          }t          j        d
|	          }	|dz  dz
  }
t          j        	                    d|z
  |
|
          }t          j        	                    ||
|
          }t          j
        | |dz   | |dz   f         \  }}t          j        ||	          }t          |          D ]\  }\  }}||z
  dz
  }||z   dz   }||z
  dz
  }||z   dz   }| ||||f         }t          |dd          \  }}||z  ddddf         }||z  ddddf         }||z  ddddf         }t          j        |          }t          j        |          }t          j        |          }t          j        ||z            } t          j        ||z            }!t          j        ||z            }"t          j        ||z            }#t          j        ||z            }$t          j        ||z            }%||d<   | x|d<   |d<   ||d<   ||d<   |x|d<   |d<   ||d<   |!|"z
  |$|#z
  f|dd<   |%|"z   | |#z   f|	dd<   	 t          j                            ||          }&t          j                            ||	          }'n:# t          j        j        $ r# t          j        t          j        f||ddf<   Y w xY w||&d         z
  }(||&d         z
  })||'d         z
  }*||'d         z
  }+|)|)z  },|)|(z  }-|(|(z  }.|+|+z  }/|+|*z  }0|*|*z  }1t          j        ||.z  d|z  |-z  z
  ||,z  z             }2t          j        ||1z  d|z  |0z  z   ||/z  z             }3|2t          j        d          k     r%|3t          j        d          k     rt          j        }4n|2dk    rt          j        }4n|3|2z  }4t+          |4|k               t+          |4|k              z
  }5|5dk    r||&d         z   ||&d         z   f||ddf<   ?|5dk    r!t          j        t          j        f||ddf<   f|5dk    r||'d         z   ||'d         z   f||ddf<   ||z  }|S )u  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.

    Parameters
    ----------
    image : (M, N) ndarray
        Input image.
    corners : (K, 2) ndarray
        Corner coordinates `(row, col)`.
    window_size : int, optional
        Search window size for subpixel estimation.
    alpha : float, optional
        Significance level for corner classification.

    Returns
    -------
    positions : (K, 2) ndarray
        Subpixel corner positions. NaN for "not classified" corners.

    References
    ----------
    .. [1] 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
    .. [2] https://en.wikipedia.org/wiki/Corner_detection

    Examples
    --------
    >>> from skimage.feature import corner_harris, corner_peaks, corner_subpix
    >>> img = np.zeros((10, 10))
    >>> img[:5, :5] = 1
    >>> img[5:, 5:] = 1
    >>> img.astype(int)
    array([[1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
           [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
           [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
           [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
           [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
           [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
           [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
           [0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
           [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]])
    >>> coords = corner_peaks(corner_harris(img), min_distance=2)
    >>> coords_subpix = corner_subpix(img, coords, window_size=7)
    >>> coords_subpix
    array([[4.5, 4.5]])

    r   r   Fr>   r   r   )	pad_widthr   constant_values)r   r   r   )r   r-   rz   )r   r   )r   r   )r   r   )r   r   N)r
   rV   rW   r4   padr   r   r   fisfmgridr   r   r(   sumrr   solveLinAlgErrornanspacinginfint)6r!   cornerswindow_sizealphawextr_   N_dotN_edgeb_dotb_edge
redundancy
t_crit_dott_crit_edgeyxcorners_subpixr    y0x0minymaxyminxmaxxwindowwinywinx	winx_winx	winx_winy	winy_winyAxxAxyAyybxx_xbxx_ybxy_xbxy_ybyy_xbyy_yest_dotest_edgery_dotrx_dotry_edgerx_edgerxx_dotrxy_dotryy_dotrxx_edgerxy_edgeryy_edgevar_dotvar_edgetcorner_classs6                                                         r"   corner_subpixr
    s   x !O!D'44KLL5L11EF5Dz1MMME 'D.))G HV;///EXfK000FHT---EXd+...F a!#JQY
J??J'++eZ<<K 8TED1H$tedQh&667DAq]7+>>>N )) XF XF8BDy1}Dy1}Dy1}Dy1}tDy$t)+,)&zJJJ
d D[!B$"*-	D[!B$"*-	D[!B$"*-	 fYfYfY y1}%%y1}%%y1}%%y1}%%y1}%%y1}%% d%(D(deDkdt&))tvd|t5=%%-/aaaEM55=0qqq		iooeU33Gyvv66HHy$ 	 	 	#%626>N1aaa4 H	 WQZWQZhqk/hqk/6/6/6/W$W$W$ &!i-'"99I<OO
 
 6 1y=8#;;i(>RR
 

 RZ]]""x"*Q--'?'?AA\\AA7"A 1{?++c!j..A.AA2#%
?BO#CN1aaa4  Q#%626>N1aaa4  Q#%#3R(1+5E#EN1aaa4  dNs   A L3MM)num_peaks_per_labelp_normc	                R   t          j        |          rd}t          | ||||t           j        |||		  	        }t	          |          rt          j        |          }t                      }t          |          D ]K\  }}||vrB|	                    |||
          }|
                    |           |                    |           Lt          j        |t          |          d          d|         }|r|S t          j        | t                    }d|t          |j                  <   |S )a  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.

    Parameters
    ----------
    image : (M, N) ndarray
        Input image.
    min_distance : int, optional
        The minimal allowed distance separating peaks.
    * : *
        See :py:meth:`skimage.feature.peak_local_max`.
    p_norm : float
        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.

    Returns
    -------
    output : ndarray or ndarray of bools

        * If `indices = True`  : (row, column, ...) coordinates of peaks.
        * If `indices = False` : Boolean array shaped like `image`, with peaks
          represented by True values.

    See also
    --------
    skimage.feature.peak_local_max

    Notes
    -----
    .. versionchanged:: 0.18
        The default value of `threshold_rel` has changed to None, which
        corresponds to letting `skimage.feature.peak_local_max` decide on the
        default. This is equivalent to `threshold_rel=0`.

    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.

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

    N)min_distancethreshold_absthreshold_relexclude_border	num_peaks	footprintlabelsr  )rpr   ri   r   T)r4   isinfr   r   r7   r   cKDTreesetr   query_ball_pointremoveupdatedeleter6   r   boolT)r!   r  r  r  r  indicesr  r  r  r  r  coordstreerejected_peaks_indicesr   point
candidatespeakss                     r"   corner_peaksr'  f  sE   X 
x	 	 !##%&/
 
 
F 6{{ Vv&&!$#F++ 	: 	:JC000!225LF2SS
!!#&&&&--j999 65)?#@#@qIII*9*U M%t,,,E!E%//Lr$   c                     t          |           } t          | j                  }|                     |d          } t	          t          j        |           |          S )a  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).

    Parameters
    ----------
    image : (M, N) ndarray
        Input image.
    window_size : int, optional
        Window size.

    Returns
    -------
    response : ndarray
        Moravec response image.

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Corner_detection

    Examples
    --------
    >>> 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],
           [0, 0, 0, 0, 0, 0, 0],
           [0, 0, 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, 0]])
    >>> corner_moravec(square).astype(int)
    array([[0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0],
           [0, 0, 1, 1, 1, 0, 0],
           [0, 0, 1, 2, 1, 0, 0],
           [0, 0, 1, 1, 1, 0, 0],
           [0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0]])
    Fr>   )r   r
   rV   rW   r   r4   r   )r!   r   r_   s      r"   corner_moravecr)    sQ    X E'44KLL5L11E2/66DDDr$   c                 B    t          |           } t          | ||          S )a	  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.

    Parameters
    ----------
    image : (M, N) array
        Input grayscale image.
    corners : (K, 2) array
        Corner coordinates as ``(row, col)``.
    mask : 2D array
        Mask defining the local neighborhood of the corner used for the
        calculation of the central moment.

    Returns
    -------
    orientations : (K, 1) array
        Orientations of corners in the range [-pi, pi].

    References
    ----------
    .. [1] 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
    .. [2] Paul L. Rosin, "Measuring Corner Properties"
          http://users.cs.cf.ac.uk/Paul.Rosin/corner2.pdf

    Examples
    --------
    >>> from skimage.morphology import octagon
    >>> from skimage.feature import (corner_fast, corner_peaks,
    ...                              corner_orientations)
    >>> square = np.zeros((12, 12))
    >>> square[3:9, 3:9] = 1
    >>> square.astype(int)
    array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
    >>> corners = corner_peaks(corner_fast(square, 9), min_distance=1)
    >>> corners
    array([[3, 3],
           [3, 8],
           [8, 3],
           [8, 8]])
    >>> orientations = corner_orientations(square, corners, octagon(3, 2))
    >>> np.rad2deg(orientations)
    array([  45.,  135.,  -45., -135.])

    )r   r   )r!   r   r   s      r"   corner_orientationsr+    s$    ~ (..Ew555r$   )r   r   )r   r   r   r)   )r   r<   r   r)   )r   r   r   r)   N)r   T)r   r   r   )r   r   r   r   )r   )r   r   )r   r   )3r\   rY   	itertoolsr   numpyr4   scipyr   r   r   r   _shared.filtersr	   _shared.utilsr
   r   r   	transformr   utilr   _hessian_det_appxr   	corner_cyr   r   r   peakr   r   r   r(   r;   rd   rn   rw   r   rq   r   r   r   r   r   r   r   r   r
  r   r'  r)  r+  rC   r$   r"   <module>r6     s        3 3 3 3 3 3                                 & & & & & & D D D D D D D D D D & & & & & &       2 2 2 2 2 2 J J J J J J J J J J             J J J J J J J J   6U U U UpX X X Xx SWq q q qh.0 .0 .0 .0bC C CD  8"3 "3 "3J3 3 3BN@ N@ N@ N@b0 0 0 0fM M M M`; ; ; ;|Q Q Q Qh> > > >Br r r rn fp 6p p p p pf/E /E /E /Ed@6 @6 @6 @6 @6r$   