o
    :ήc?K                  	   @   s   d Z ddlmZ ddlZddlmZmZ ddlm	Z	m
Z
 ddlmZmZ d!d	d
Zd"ddZdd Z		d#ddZedddddddfddZeddddddfddZedddddddddddf	ddZedddddddddddf	dd ZdS )$ab  
Ridge filters.

Ridge filters can be used to detect continuous edges, such as vessels,
neurites, wrinkles, rivers, and other tube-like structures. The present
class of ridge filters relies on the eigenvalues of the Hessian matrix of
image intensities to detect tube-like structures where the intensity changes
perpendicular but not along the structure.
    )warnN   )_supported_float_typecheck_nD)hessian_matrixhessian_matrix_eigvals)img_as_floatinvert绽|=c                 C   s"   t |}|||dk< t | |S )a  
    Divides two arrays.

    Denominator is set to small value where zero to avoid ZeroDivisionError and
    return finite float array.

    Parameters
    ----------
    array1 : (N, ..., M) ndarray
        Array 1 in the enumerator.
    array2 : (N, ..., M) ndarray
        Array 2 in the denominator.
    cval : float, optional
        Value used to replace zero entries in the denominator.

    Returns
    -------
    array : (N, ..., M) ndarray
        Quotient of the array division.
    r   )npcopydivide)array1array2cvaldenominator r   =/tmp/pip-target-vg8gfxp4/lib/python/skimage/filters/ridges.py_divide_nonzero   s   
r   c                 C   s:   t tjdd | jD  }t| |||< | t| S )a  
    Sort array along a given axis by absolute values.

    Parameters
    ----------
    array : (N, ..., M) ndarray
        Array with input image data.
    axis : int
        Axis along which to sort.

    Returns
    -------
    array : (N, ..., M) ndarray
        Array sorted along a given axis by absolute values.

    Notes
    -----
    Modified from: http://stackoverflow.com/a/11253931/4067734
    c                 S   s   g | ]}t |qS r   )r   arange).0ir   r   r   
<listcomp>K   s    z_sortbyabs.<locals>.<listcomp>)listr   ix_shapeabsargsorttuple)arrayaxisindexr   r   r   
_sortbyabs5   s   r"   c                 C   s(   t |  } t | dk rtd| S )a0  Check sigma values for ridges filters.

    Parameters
    ----------
    sigmas : iterable of floats
        Sigmas argument to be checked

    Returns
    -------
    sigmas : ndarray
        input iterable converted to ndarray

    Raises
    ------
    ValueError if any input value is negative

    g        z5Sigma values should be equal to or greater than zero.)r   asarrayravelany
ValueError)sigmasr   r   r   _check_sigmasT   s   r(   noneconstantc                    s~   t | j}t| } | j|dd} t|  d||d} fdd|D }t|}|dkr2t|dd	}|S |d
kr=tj|dd	}|S )a  
    Compute Hessian eigenvalues of nD images.

    For 2D images, the computation uses a more efficient, skimage-based
    algorithm.

    Parameters
    ----------
    image : (N, ..., M) ndarray
        Array with input image data.
    sigma : float
        Smoothing factor of image for detection of structures at different
        (sigma) scales.
    sorting : {'val', 'abs', 'none'}, optional
        Sorting of eigenvalues by values ('val') or absolute values ('abs'),
        or without sorting ('none'). Default is 'none'.
    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
    -------
    eigenvalues : (D, N, ..., M) ndarray
        Array with (sorted) eigenvalues of Hessian eigenvalues for each pixel
        of the input image.
    Fr   rc)sigmaordermoder   c                    s   g | ]} d  | qS r   r   )r   er-   r   r   r      s    z/compute_hessian_eigenvalues.<locals>.<listcomp>r   r   r    val)	r   dtyper   astyper   r   r"   r   sort)imager-   sortingr/   r   float_dtypehessian_elementshessian_eigenvaluesr   r2   r   compute_hessian_eigenvaluesm   s   
 r=      
   Treflectc                    s   t |}| j|du rd }t| j}| j|dd} |r!t| } t|j| j |}t	|D ]@\}}	t
| |	d||ddkro|g  d d<  fd	d
tD }
|
d }
t|
t|
}t|
dk |d}|||< q/tj|ddS )al  
    Filter an image with the Meijering neuriteness filter.

    This filter can be used to detect continuous ridges, e.g. neurites,
    wrinkles, rivers. It can be used to calculate the fraction of the
    whole image containing such objects.

    Calculates the eigenvectors of the Hessian to compute the similarity of
    an image region to neurites, according to the method described in [1]_.

    Parameters
    ----------
    image : (N, M[, ..., P]) ndarray
        Array with input image data.
    sigmas : iterable of floats, optional
        Sigmas used as scales of filter
    alpha : float, optional
        Frangi correction constant that adjusts the filter's
        sensitivity to deviation from a plate-like structure.
    black_ridges : boolean, optional
        When True (the default), the filter detects black ridges; when
        False, it detects white ridges.
    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
    -------
    out : (N, M[, ..., P]) ndarray
        Filtered image (maximum of pixels across all scales).

    See also
    --------
    sato
    frangi
    hessian

    References
    ----------
    .. [1] Meijering, E., Jacob, M., Sarria, J. C., Steiner, P., Hirling, H.,
        Unser, M. (2004). Design and validation of a tool for neurite tracing
        and analysis in fluorescence microscopy images. Cytometry Part A,
        58(2), 167-176.
        :DOI:`10.1002/cyto.a.20022`
    Ng      ?Fr+   r   r9   r/   r   r>   r   c                    s0   g | ] t j fd dtD ddqS )c                    s$   g | ]} t  |  qS r   )r   roll)r   j)coefficientseigenvaluesr   r   r   r      s    z(meijering.<locals>.<listcomp>.<listcomp>r   r3   )r   sumrange)r   rD   rE   ndim)r   r   r      s    
zmeijering.<locals>.<listcomp>r3   )r(   rI   r   r5   r6   r	   r   zerosr   	enumerater=   rG   r   minwheremax)r8   r'   alphablack_ridgesr/   r   r:   filtered_arrayr   r-   	auxiliaryfilteredr   rH   r   	meijering   s2   3

rU   c                 C   s   t | ddg t|}|st| } t| j}tj|j| j |d}t|D ]+\}}t	| |d||d^}	}
t
tj|
dt|
  }t|
d dk|d||< q%tj|dd	S )
a  
    Filter an image with the Sato tubeness filter.

    This filter can be used to detect continuous ridges, e.g. tubes,
    wrinkles, rivers. It can be used to calculate the fraction of the
    whole image containing such objects.

    Defined only for 2-D and 3-D images. Calculates the eigenvectors of the
    Hessian to compute the similarity of an image region to tubes, according to
    the method described in [1]_.

    Parameters
    ----------
    image : (N, M[, P]) ndarray
        Array with input image data.
    sigmas : iterable of floats, optional
        Sigmas used as scales of filter.
    black_ridges : boolean, optional
        When True (the default), the filter detects black ridges; when
        False, it detects white ridges.
    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
    -------
    out : (N, M[, P]) ndarray
        Filtered image (maximum of pixels across all scales).

    See also
    --------
    meijering
    frangi
    hessian

    References
    ----------
    .. [1] Sato, Y., Nakajima, S., Shiraga, N., Atsumi, H., Yoshida, S.,
        Koller, T., ..., Kikinis, R. (1998). Three-dimensional multi-scale line
        filter for segmentation and visualization of curvilinear structures in
        medical images. Medical image analysis, 2(2), 143-168.
        :DOI:`10.1016/S1361-8415(98)80009-1`
    r      r5   r4   rA   r>   rJ   r   r3   )r   r(   r	   r   r5   r   rK   r   rL   r=   r   multiplyreducelenrN   rO   )r8   r'   rQ   r/   r   r:   rR   r   r-   lamba1lambdasrT   r   r   r   sato  s   1

r]   g      ?   c
                 C   s  |dur|durt ddd t|d |d |}t| ddg t|}d|d  }
d|d  }d|d  }| j}|r?t| } t| j}tj	|j
| j
 |d}tj||d}t|D ]g\}}t| |d	||	d
^}}|dkrptjnt| d }ttj|dt|  }t||d }t|d gdd |D  }dt| |
  t| |  dt| |   ||< tj|dd||< qZd||dk< tj|ddS )a
  
    Filter an image with the Frangi vesselness filter.

    This filter can be used to detect continuous ridges, e.g. vessels,
    wrinkles, rivers. It can be used to calculate the fraction of the
    whole image containing such objects.

    Defined only for 2-D and 3-D images. Calculates the eigenvectors of the
    Hessian to compute the similarity of an image region to vessels, according
    to the method described in [1]_.

    Parameters
    ----------
    image : (N, M[, P]) ndarray
        Array with input image data.
    sigmas : iterable of floats, optional
        Sigmas used as scales of filter, i.e.,
        np.arange(scale_range[0], scale_range[1], scale_step)
    scale_range : 2-tuple of floats, optional
        The range of sigmas used.
    scale_step : float, optional
        Step size between sigmas.
    alpha : float, optional
        Frangi correction constant that adjusts the filter's
        sensitivity to deviation from a plate-like structure.
    beta : float, optional
        Frangi correction constant that adjusts the filter's
        sensitivity to deviation from a blob-like structure.
    gamma : float, optional
        Frangi correction constant that adjusts the filter's
        sensitivity to areas of high variance/texture/structure.
    black_ridges : boolean, optional
        When True (the default), the filter detects black ridges; when
        False, it detects white ridges.
    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
    -------
    out : (N, M[, P]) ndarray
        Filtered image (maximum of pixels across all scales).

    Notes
    -----
    Written by Marc Schrijver, November 2001
    Re-Written by D. J. Kroon, University of Twente, May 2009, [2]_
    Adoption of 3D version from D. G. Ellis, Januar 20017, [3]_

    See also
    --------
    meijering
    sato
    hessian

    References
    ----------
    .. [1] Frangi, A. F., Niessen, W. J., Vincken, K. L., & Viergever, M. A.
        (1998,). Multiscale vessel enhancement filtering. In International
        Conference on Medical Image Computing and Computer-Assisted
        Intervention (pp. 130-137). Springer Berlin Heidelberg.
        :DOI:`10.1007/BFb0056195`
    .. [2] Kroon, D. J.: Hessian based Frangi vesselness filter.
    .. [3] Ellis, D. G.: https://github.com/ellisdg/frangi3d/tree/master/frangi
    NzpUse keyword parameter `sigmas` instead of `scale_range` and `scale_range` which will be removed in version 0.17.r   )
stacklevelr   r>   rV   rW   r   rA   c                 S   s   g | ]}|d  qS r0   r   )r   lambdair   r   r   r     s    zfrangi.<locals>.<listcomp>r3   )r   r   r   r   r(   rI   r	   r   r5   rK   r   
zeros_likerL   r=   infr   r   rX   rY   rZ   rF   exprO   )r8   r'   scale_range
scale_steprP   betagammarQ   r/   r   alpha_sqbeta_sqgamma_sqrI   r:   rR   lambdas_arrayr   r-   lambda1r\   r_afiltered_rawr_br_gr   r   r   frangif  sB   F

rq   c
                 C   s,   t | |||||||||	d
}
d|
|
dk< |
S )a  Filter an image with the Hybrid Hessian filter.

    This filter can be used to detect continuous edges, e.g. vessels,
    wrinkles, rivers. It can be used to calculate the fraction of the whole
    image containing such objects.

    Defined only for 2-D and 3-D images. Almost equal to Frangi filter, but
    uses alternative method of smoothing. Refer to [1]_ to find the differences
    between Frangi and Hessian filters.

    Parameters
    ----------
    image : (N, M[, P]) ndarray
        Array with input image data.
    sigmas : iterable of floats, optional
        Sigmas used as scales of filter, i.e.,
        np.arange(scale_range[0], scale_range[1], scale_step)
    scale_range : 2-tuple of floats, optional
        The range of sigmas used.
    scale_step : float, optional
        Step size between sigmas.
    beta : float, optional
        Frangi correction constant that adjusts the filter's
        sensitivity to deviation from a blob-like structure.
    gamma : float, optional
        Frangi correction constant that adjusts the filter's
        sensitivity to areas of high variance/texture/structure.
    black_ridges : boolean, optional
        When True (the default), the filter detects black ridges; when
        False, it detects white ridges.
    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
    -------
    out : (N, M[, P]) ndarray
        Filtered image (maximum of pixels across all scales).

    Notes
    -----
    Written by Marc Schrijver (November 2001)
    Re-Written by D. J. Kroon University of Twente (May 2009) [2]_

    See also
    --------
    meijering
    sato
    frangi

    References
    ----------
    .. [1] Ng, C. C., Yap, M. H., Costen, N., & Li, B. (2014,). Automatic
        wrinkle detection using hybrid Hessian filter. In Asian Conference on
        Computer Vision (pp. 609-622). Springer International Publishing.
        :DOI:`10.1007/978-3-319-16811-1_40`
    .. [2] Kroon, D. J.: Hessian based Frangi vesselness filter.
    )	r'   rd   re   rP   rf   rg   rQ   r/   r   r>   r   )rq   )r8   r'   rd   re   rP   rf   rg   rQ   r/   r   rT   r   r   r   hessian  s   ?rr   )r
   )r   )r)   r*   r   )__doc__warningsr   numpyr   _shared.utilsr   r   feature.cornerr   r   utilr   r	   r   r"   r(   r=   rG   rU   r]   rq   rr   r   r   r   r   <module>   s6    

 
>
h
S
 
