B
    \*W              !   @   s`  d dl mZ d dlmZmZmZ d dlZd dlm	Z	 d dl
Zd dlmZ ddlmZ ddlmZ d d	lmZ d
dgZdZejd dd gdddgd dd ggejdZejdejdZejdejdZddddddddddddddddd d!d"d#d$d%d&d'd(dd)d*d+d,d-d.d/ Zee Z d0d1 Z!d2d3 Z"G d4d5 d5e#Z$d>d7d
Z%d?d9dZ&d:d; Z'd<d= Z(e(  dS )@    )division)sqrtatan2piN)warn)ndimage   )label)_moments)wrapsregionprops	perimetera=  regionprops and image moments (including moments, normalized moments, central moments, and inertia tensor) of 2D images will change from xy coordinates to rc coordinates in version 0.16.
See http://scikit-image.org/docs/0.14.x/release_notes_and_installation.html#deprecations for details on how to avoid this message.)dtype)   r   )r   r   r   areabbox	bbox_areamoments_centralcentroidconvex_areaconvex_imagecoordseccentricityequivalent_diametereuler_numberextentfilled_areafilled_image
moments_huimager	   major_axis_lengthmax_intensitymean_intensitymin_intensityminor_axis_lengthmomentsmoments_normalizedorientationsolidityweighted_moments_centralweighted_centroidweighted_moments_huweighted_momentsweighted_moments_normalized) ZAreaZBoundingBoxZBoundingBoxAreaZCentralMomentsZCentroidZ
ConvexAreaZConvexImageZCoordinatesZEccentricityZEquivDiameterZEulerNumberZExtentZ
FilledAreaZFilledImageZ	HuMomentsZImageZLabelZMajorAxisLengthZMaxIntensityZMeanIntensityZMinIntensityZMinorAxisLengthZMomentsZNormalizedMomentsZOrientationZ	PerimeterZSolidityZWeightedCentralMomentsZWeightedCentroidZWeightedHuMomentsZWeightedMomentsZWeightedNormalizedMomentsc                s   t   fdd}|S )Nc                s.   | j } j}||kr| js& | ||< || S )N)_cache__name___cache_active)objcacheZprop)f ;lib/python3.7/site-packages/skimage/measure/_regionprops.pywrapperJ   s
    z_cached.<locals>.wrapper)r   )r3   r6   r4   )r3   r5   _cachedI   s    
r7   c                s   t   fdd}|S )Nc                s(   | j dkrtd j  | f||S )N   z,Property %s is not implemented for 3D images)_ndimNotImplementedErrorr/   )selfargskwargs)methodr4   r5   func2dX   s    

zonly2d.<locals>.func2d)r   )r>   r?   r4   )r>   r5   only2dW   s    r@   c               @   s  e Zd ZdZdd Zedd Zdd Zdd	 Zd
d Z	edd Z
edd Zdd Zedd Zdd Zdd Zdd Zdd Zedd Zedd Zed d! Zed"d# Zed$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zed4d5 Zed6d7 Z ed8d9 Z!ed:d; Z"ed<d= Z#ed>d? Z$d@dA Z%dBdC Z&dDdE Z'edFdG Z(edHdI Z)edJdK Z*edLdM Z+dNdO Z,dPdQ Z-dRdS Z.dTS )U_RegionPropertieszoPlease refer to `skimage.measure.regionprops` for more information
    on the available region properties.
    c             C   s   |d k	r|j |j kstd|| _|| _|| _|| _|| _i | _|j| _	|jdksZ|dkrhd| _
d| _n4|dkr~d| _
d| _n|d krd| _
d| _ntdd S )Nz2Label and intensity image must have thesame shape.r8   ZrcFZxyTzYIncorrect value for regionprops coordinates: %s. Possible values are: "rc", "xy", or None)shape
ValueErrorr	   _slice_label_image_intensity_imager0   r.   ndimr9   _use_xy_warning_transpose_moments)r;   slicer	   label_imageintensity_imageZcache_activecoordinatesr4   r4   r5   __init__f   s(    z_RegionProperties.__init__c             C   s   t | jS )N)npsumr   )r;   r4   r4   r5   r      s    z_RegionProperties.areac                s4   t  fddt jD  fddt jD  S )z
        Returns
        -------
        A tuple of the bounding box's start coordinates for each dimension,
        followed by the end coordinates for each dimension
        c                s   g | ]} j | jqS r4   )rD   start).0i)r;   r4   r5   
<listcomp>   s    z*_RegionProperties.bbox.<locals>.<listcomp>c                s   g | ]} j | jqS r4   )rD   stop)rR   rS   )r;   r4   r5   rT      s    )tupleranger9   )r;   r4   )r;   r5   r      s    z_RegionProperties.bboxc             C   s   | j jS )N)r   size)r;   r4   r4   r5   r      s    z_RegionProperties.bbox_areac             C   s   t | jjddS )Nr   )Zaxis)rV   r   mean)r;   r4   r4   r5   r      s    z_RegionProperties.centroidc             C   s   t | jS )N)rO   rP   r   )r;   r4   r4   r5   r      s    z_RegionProperties.convex_areac             C   s   ddl m} || jS )Nr8   )convex_hull_image)Zmorphology.convex_hullrZ   r   )r;   rZ   r4   r4   r5   r      s    z_RegionProperties.convex_imagec                s.   t j t  fddtjD jS )Nc                s    g | ]} | j | j qS r4   )rD   rQ   )rR   rS   )indicesr;   r4   r5   rT      s   z,_RegionProperties.coords.<locals>.<listcomp>)rO   Znonzeror   ZvstackrW   r9   T)r;   r4   )r[   r;   r5   r      s    z_RegionProperties.coordsc             C   s&   | j \}}|dkrdS td||  S )Nr   r   )inertia_tensor_eigvalsr   )r;   l1l2r4   r4   r5   r      s    
z_RegionProperties.eccentricityc             C   s<   | j dkrtd| j t S | j dkr8d| j t d S d S )Nr8      r      gUUUUUU?)r9   r   r   PI)r;   r4   r4   r5   r      s    

z%_RegionProperties.equivalent_diameterc             C   s,   | j | jk}t|| jddd\}}| d S )NTr   )ZconnectivityZ
return_numZ
backgroundr   )r   r   r	   r9   )r;   Zeuler_array_Znumr4   r4   r5   r      s    
z_RegionProperties.euler_numberc             C   s   | j | jj S )N)r   r   rX   )r;   r4   r4   r5   r      s    z_RegionProperties.extentc             C   s   t | jS )N)rO   rP   r   )r;   r4   r4   r5   r      s    z_RegionProperties.filled_areac             C   s   t d| j }t| j|S )N)r   )rO   onesr9   ndiZbinary_fill_holesr   )r;   Z	structurer4   r4   r5   r      s    z_RegionProperties.filled_imagec             C   s   | j | j | jkS )N)rE   rD   r	   )r;   r4   r4   r5   r      s    z_RegionProperties.imagec             C   s   | j }t| j|S )N)r   r
   inertia_tensorr   )r;   mur4   r4   r5   rf      s    z _RegionProperties.inertia_tensorc             C   s   t j| j| jdS )N)r\   )r
   r]   r   rf   )r;   r4   r4   r5   r]      s    z(_RegionProperties.inertia_tensor_eigvalsc             C   s$   | j d krtd| j | j | j S )NzNo intensity image specified.)rF   AttributeErrorrD   r   )r;   r4   r4   r5   rL      s    
z!_RegionProperties.intensity_imagec             C   s   | j tjS )N)rL   astyperO   double)r;   r4   r4   r5   _intensity_image_double   s    z)_RegionProperties._intensity_image_doublec             C   s<   | j }| jr|j}t|ttj| jtd |d| j   S )N)r   )r   )r%   rI   r\   rV   rO   eyer9   int)r;   Mr4   r4   r5   local_centroid   s
    z _RegionProperties.local_centroidc             C   s   t | j| j S )N)rO   maxrL   r   )r;   r4   r4   r5   r!      s    z_RegionProperties.max_intensityc             C   s   t | j| j S )N)rO   rY   rL   r   )r;   r4   r4   r5   r"      s    z _RegionProperties.mean_intensityc             C   s   t | j| j S )N)rO   minrL   r   )r;   r4   r4   r5   r#      s    z_RegionProperties.min_intensityc             C   s   | j d }dt| S )Nr   r`   )r]   r   )r;   r^   r4   r4   r5   r       s    
z#_RegionProperties.major_axis_lengthc             C   s   | j d }dt| S )Nr`   )r]   r   )r;   r_   r4   r4   r5   r$      s    
z#_RegionProperties.minor_axis_lengthc             C   s4   t | jtjd}| jr$tt | j	r0|j
}|S )Nr   )r
   r%   r   ri   rO   uint8rH   r   XY_TO_RC_DEPRECATION_MESSAGErI   r\   )r;   rn   r4   r4   r5   r%      s    z_RegionProperties.momentsc             C   s:   t j| jtj| jdd}| jr*tt	 | j
r6|j}|S )Nr   )order)r
   r   r   ri   rO   rs   ro   rH   r   rt   rI   r\   )r;   rg   r4   r4   r5   r      s    z!_RegionProperties.moments_centralc             C   s   t | jS )N)r
   r   r&   )r;   r4   r4   r5   r   	  s    z_RegionProperties.moments_huc             C   s   t | jdS )Nr   )r
   r&   r   )r;   r4   r4   r5   r&     s    z$_RegionProperties.moments_normalizedc             C   sd   | j j\}}}}| jrdnd}|| dkrF|dk r<t d S td S n|d td| ||  S d S )Nrr   r   r   g      @g      ?)rf   ZflatrI   rb   r   )r;   abcZsignr4   r4   r5   r'     s    

z_RegionProperties.orientationc             C   s   t | jdS )Nr`   )r   r   )r;   r4   r4   r5   r     s    z_RegionProperties.perimeterc             C   s   | j | j S )N)r   r   )r;   r4   r4   r5   r(   !  s    z_RegionProperties.solidityc             C   s    | j }tdd t|| jD S )Nc             s   s   | ]\}}||j  V  qd S )N)rQ   )rR   idxZslcr4   r4   r5   	<genexpr>&  s   z6_RegionProperties.weighted_centroid.<locals>.<genexpr>)weighted_local_centroidrV   ziprD   )r;   ctrr4   r4   r5   r*   $  s    z#_RegionProperties.weighted_centroidc             C   s,   | j }|ttj| jtd |d| j   S )N)r   )r   )r,   rV   rO   rl   r9   rm   )r;   rn   r4   r4   r5   r|   )  s    z)_RegionProperties.weighted_local_centroidc             C   s   t |  dS )Nr   )r
   r%   rk   )r;   r4   r4   r5   r,   .  s    z"_RegionProperties.weighted_momentsc             C   s   | j }tj|  |ddS )Nr   )centerru   )r|   r
   r   rk   )r;   r~   r4   r4   r5   r)   2  s    
z*_RegionProperties.weighted_moments_centralc             C   s   t | jS )N)r
   r   r-   )r;   r4   r4   r5   r+   8  s    z%_RegionProperties.weighted_moments_huc             C   s   t | jdS )Nr   )r
   r&   r)   )r;   r4   r4   r5   r-   <  s    z-_RegionProperties.weighted_moments_normalizedc             C   s(   t }| jd krd}||}tt|S )N)
rL   r!   r"   r#   r,   r)   r*   r|   r+   r-   )	PROP_VALSrF   
differenceitersorted)r;   propsZunavailable_propsr4   r4   r5   __iter__@  s
    

z_RegionProperties.__iter__c             C   s*   t | |d }|d k	r|S t | t| S d S )N)getattrPROPS)r;   keyvaluer4   r4   r5   __getitem__S  s    z_RegionProperties.__getitem__c          	   C   sX   t |tsdS xDtD ]<}y"tjt| |d t||d  W q tk
rN   dS X qW dS )NFT)
isinstancerA   r   rO   ZtestingZassert_equalr   AssertionError)r;   otherr   r4   r4   r5   __eq__Z  s    


z_RegionProperties.__eq__N)/r/   
__module____qualname____doc__rN   r7   r   r   r   r   r   r   r   r@   r   r   r   r   r   r   r   rf   r]   rL   rk   ro   r!   r"   r#   r    r$   r%   r   r   r&   r'   r   r(   r*   r|   r,   r)   r+   r-   r   r   r   r4   r4   r4   r5   rA   a   sT   !
	
rA   Tc       
   	   C   s   | j dkrtdt| jtjs*tdg }t| }xDt|D ]8\}}|dkrTqB|d }t	||| |||d}	|
|	 qBW |S )uG  Measure properties of labeled image regions.

    Parameters
    ----------
    label_image : (N, M) ndarray
        Labeled input image. Labels with value 0 are ignored.

        .. versionchanged:: 0.14.2
            Previously, ``label_image`` was processed by ``numpy.squeeze`` and
            so any number of singleton dimensions was allowed. This resulted in
            inconsistent handling of images with singleton dimensions. To
            recover the old behaviour, use
            ``regionprops(np.squeeze(label_image), ...)``.
    intensity_image : (N, M) ndarray, optional
        Intensity (i.e., input) image with same size as labeled image.
        Default is None.
    cache : bool, optional
        Determine whether to cache calculated properties. The computation is
        much faster for cached properties, whereas the memory consumption
        increases.
    coordinates : 'rc' or 'xy', optional
        Coordinate conventions for 2D images. (Only 'rc' coordinates are
        supported for 3D images.)

    Returns
    -------
    properties : list of RegionProperties
        Each item describes one labeled region, and can be accessed using the
        attributes listed below.

    Notes
    -----
    The following properties can be accessed as attributes or keys:

    **area** : int
        Number of pixels of region.
    **bbox** : tuple
        Bounding box ``(min_row, min_col, max_row, max_col)``.
        Pixels belonging to the bounding box are in the half-open interval
        ``[min_row; max_row)`` and ``[min_col; max_col)``.
    **bbox_area** : int
        Number of pixels of bounding box.
    **centroid** : array
        Centroid coordinate tuple ``(row, col)``.
    **convex_area** : int
        Number of pixels of convex hull image.
    **convex_image** : (H, J) ndarray
        Binary convex hull image which has the same size as bounding box.
    **coords** : (N, 2) ndarray
        Coordinate list ``(row, col)`` of the region.
    **eccentricity** : float
        Eccentricity of the ellipse that has the same second-moments as the
        region. The eccentricity is the ratio of the focal distance
        (distance between focal points) over the major axis length.
        The value is in the interval [0, 1).
        When it is 0, the ellipse becomes a circle.
    **equivalent_diameter** : float
        The diameter of a circle with the same area as the region.
    **euler_number** : int
        Euler characteristic of region. Computed as number of objects (= 1)
        subtracted by number of holes (8-connectivity).
    **extent** : float
        Ratio of pixels in the region to pixels in the total bounding box.
        Computed as ``area / (rows * cols)``
    **filled_area** : int
        Number of pixels of filled region.
    **filled_image** : (H, J) ndarray
        Binary region image with filled holes which has the same size as
        bounding box.
    **image** : (H, J) ndarray
        Sliced binary region image which has the same size as bounding box.
    **inertia_tensor** : (2, 2) ndarray
        Inertia tensor of the region for the rotation around its mass.
    **inertia_tensor_eigvals** : tuple
        The two eigen values of the inertia tensor in decreasing order.
    **intensity_image** : ndarray
        Image inside region bounding box.
    **label** : int
        The label in the labeled input image.
    **local_centroid** : array
        Centroid coordinate tuple ``(row, col)``, relative to region bounding
        box.
    **major_axis_length** : float
        The length of the major axis of the ellipse that has the same
        normalized second central moments as the region.
    **max_intensity** : float
        Value with the greatest intensity in the region.
    **mean_intensity** : float
        Value with the mean intensity in the region.
    **min_intensity** : float
        Value with the least intensity in the region.
    **minor_axis_length** : float
        The length of the minor axis of the ellipse that has the same
        normalized second central moments as the region.
    **moments** : (3, 3) ndarray
        Spatial moments up to 3rd order::

            m_ji = sum{ array(x, y) * x^j * y^i }

        where the sum is over the `x`, `y` coordinates of the region.
    **moments_central** : (3, 3) ndarray
        Central moments (translation invariant) up to 3rd order::

            mu_ji = sum{ array(x, y) * (x - x_c)^j * (y - y_c)^i }

        where the sum is over the `x`, `y` coordinates of the region,
        and `x_c` and `y_c` are the coordinates of the region's centroid.
    **moments_hu** : tuple
        Hu moments (translation, scale and rotation invariant).
    **moments_normalized** : (3, 3) ndarray
        Normalized moments (translation and scale invariant) up to 3rd order::

            nu_ji = mu_ji / m_00^[(i+j)/2 + 1]

        where `m_00` is the zeroth spatial moment.
    **orientation** : float
        In 'rc' coordinates, angle between the 0th axis (rows) and the major
        axis of the ellipse that has the same second moments as the region,
        ranging from `-pi/2` to `pi/2` counter-clockwise.

        In `xy` coordinates, as above but the angle is now measured from the
        "x" or horizontal axis.
    **perimeter** : float
        Perimeter of object which approximates the contour as a line
        through the centers of border pixels using a 4-connectivity.
    **solidity** : float
        Ratio of pixels in the region to pixels of the convex hull image.
    **weighted_centroid** : array
        Centroid coordinate tuple ``(row, col)`` weighted with intensity
        image.
    **weighted_local_centroid** : array
        Centroid coordinate tuple ``(row, col)``, relative to region bounding
        box, weighted with intensity image.
    **weighted_moments** : (3, 3) ndarray
        Spatial moments of intensity image up to 3rd order::

            wm_ji = sum{ array(x, y) * x^j * y^i }

        where the sum is over the `x`, `y` coordinates of the region.
    **weighted_moments_central** : (3, 3) ndarray
        Central moments (translation invariant) of intensity image up to
        3rd order::

            wmu_ji = sum{ array(x, y) * (x - x_c)^j * (y - y_c)^i }

        where the sum is over the `x`, `y` coordinates of the region,
        and `x_c` and `y_c` are the coordinates of the region's weighted
        centroid.
    **weighted_moments_hu** : tuple
        Hu moments (translation, scale and rotation invariant) of intensity
        image.
    **weighted_moments_normalized** : (3, 3) ndarray
        Normalized moments (translation and scale invariant) of intensity
        image up to 3rd order::

            wnu_ji = wmu_ji / wm_00^[(i+j)/2 + 1]

        where ``wm_00`` is the zeroth spatial moment (intensity-weighted area).

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

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

    See Also
    --------
    label

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

    Examples
    --------
    >>> from skimage import data, util
    >>> from skimage.measure import label
    >>> img = util.img_as_ubyte(data.coins()) > 110
    >>> label_img = label(img, connectivity=img.ndim)
    >>> props = regionprops(label_img)
    >>> # centroid of first labeled object
    >>> props[0].centroid
    (22.729879860483141, 81.912285234465827)
    >>> # centroid of first labeled object
    >>> props[0]['centroid']
    (22.729879860483141, 81.912285234465827)

    )r8   r   z"Only 2-D and 3-D images supported.z$Label image must be of integer type.Nr   )rM   )rG   	TypeErrorrO   Z
issubdtyper   Zintegerre   Zfind_objects	enumeraterA   append)
rK   rL   r2   rM   ZregionsZobjectsrS   Zslr	   r   r4   r4   r5   r   i  s     F



r`   c       	   	   C   s   |dkrt }nt}| tj} tj| |dd}| | }tjdtjd}d|ddd	d
ddg< t	d|ddg< dt	d d |ddg< tj
|tdddgdddgdddggddd}tj| dd}t||}|S )aG  Calculate total perimeter of all objects in binary image.

    Parameters
    ----------
    image : array
        Binary image.
    neighbourhood : 4 or 8, optional
        Neighborhood connectivity for border pixel determination.

    Returns
    -------
    perimeter : float
        Total perimeter of all objects in binary image.

    References
    ----------
    .. [1] K. Benkrid, D. Crookes. Design and FPGA Implementation of
           a Perimeter Estimator. The Queen's University of Belfast.
           http://www.cs.qub.ac.uk/~d.crookes/webpubs/papers/perimeter.doc
    r`   r   )Zborder_value2   )r   r                     r8      !         
   Zconstant)modeZcval)Z	minlength)STREL_4STREL_8ri   rO   rs   re   Zbinary_erosionZzerosrj   r   ZconvolvearrayZbincountZraveldot)	r   ZneighbourhoodZstrelZeroded_imageZborder_imageZperimeter_weightsZperimeter_imageZperimeter_histogramZtotal_perimeterr4   r4   r5   r   D  s"    
c                 sB   dd l } dd l tj}| jd|| jd}t fdd|D }|S )Nr   z)\*\*(\w+)\*\* \:.*?
(.*?)(?=
    [\*\S]+))flagsc             3   s(   | ] }| d  | dfV  qdS )r   r8   N)groupdedent)rR   m)textwrapr4   r5   r{   {  s    z_parse_docs.<locals>.<genexpr>)rer   r   r   finditerDOTALLdict)r   docZmatchesprop_docr4   )r   r5   _parse_docst  s    r   c           	   C   sx   t  } xldd ttD D ]V}y| | tt|_W n& tk
rX   | | tt|j_Y nX tt|ttt| qW d S )Nc             S   s   g | ]}| d s|qS )rc   )
startswith)rR   memberr4   r4   r5   rT     s    z,_install_properties_docs.<locals>.<listcomp>)	r   dirrA   r   r   rh   Zim_funcsetattrproperty)r   pr4   r4   r5   _install_properties_docs  s    r   )NTN)r`   ))Z
__future__r   Zmathr   r   r   rb   	itertoolswarningsr   ZnumpyrO   Zscipyr   re   Z_labelr	    r
   	functoolsr   __all__rt   r   rs   r   rd   r   ZSTREL_26_3Dr   setvaluesr   r7   r@   objectrA   r   r   r   r   r4   r4   r4   r5   <module>   sx   
  
 
 [
0