Ë
     \;j¢A  ã                   óö   — d dl Z d dlm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mZ ddlmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZmZ d„ Zd„ Z ej6                  d¬«      	 	 	 	 	 	 	 	 	 	 	 	 dddœd„«       Zy)é    N)ÚIterable)Úwarn)Úrandom)Úkmeans2)ÚpdistÚ
squareformé   )Úutils)Úgaussian)Úrgb2lab)Úimg_as_floatÚregular_gridé   )Ú"_enforce_label_connectivity_cythonÚ_slic_cythonc                 ó@  — t        j                  t        j                  | «      t        ¬«      j                  }t        j                  d«      }t        j                  t        |«      t        ¬«      }t        j                  |j                  |t        |t        |«      «      d¬«      «      }d}|r| j                  dz
  n| j                  }t        ||z  |z  «      }	t        |«      |	kD  r(t        j                  |j                  ||	d¬«      «      }
nt        }
t        ||
   ||   d¬«      \  }}t!        t#        |«      «      }t        j$                  |t         j&                  «       |j)                  d	«      }t+        |||d
d
…f   z
  «      j-                  d«      }||fS )aÂ  Find regularly spaced centroids on a mask.

    Parameters
    ----------
    mask : 3D ndarray
        The mask within which the centroids must be positioned.
    n_centroids : int
        The number of centroids to be returned.

    Returns
    -------
    centroids : 2D ndarray
        The coordinates of the centroids with shape (n_centroids, 3).
    steps : 1D ndarray
        The approximate distance between two seeds in all dimensions.

    ©Údtypeé{   F)Úreplaceé
   r   é   )ÚiteréÿÿÿÿNr   )ÚnpÚarrayÚnonzeroÚfloatÚTr   ÚRandomStateÚarangeÚlenÚintÚsortÚchoiceÚminÚndimÚEllipsisr   r   r   Úfill_diagonalÚinfÚargminÚabsÚmean)ÚmaskÚn_centroidsÚmultichannelÚcoordÚrngÚidx_fullÚidxÚdense_factorÚndim_spatialÚn_denseÚ	idx_denseÚ	centroidsÚ_ÚdistÚclosest_ptsÚstepss                   únG:\00. PROJECTS\API\Inventory\templateJSON\kerjaOCR\Lib\site-packages\skimage/segmentation/slic_superpixels.pyÚ_get_mask_centroidsr?      sN  € ô( �H‰H”R—Z‘Z Ó%¬UÔ3×5Ñ5€Eô ×
Ñ
˜SÓ
!€Cô �y‰yœ˜U›¬3Ô/€HÜ
�'‰'�#—*‘*˜X¤s¨;¼¸E»
Ó'CÈU�*ÓSÓ
T€Cð €LÙ$0�4—9‘9˜q’=°d·i±i€LÜ�< Ñ-°Ñ<Ó=€GÜ
ˆ5ƒz�GÒô —G‘G˜CŸJ™J x°À%˜JÓHÓI‰	äˆ	Ü˜5 Ñ+¨U°3©Z¸aÔ@�L€Iˆqô ”e˜IÓ&Ó'€DÜ×Ñ�Tœ2Ÿ6™6Ô"Ø—+‘+˜b“/€KÜ�	˜I k²1 nÑ5Ñ5Ó6×;Ñ;¸AÓ>€Eà�eÐÐó    c                 óL  — | j                   dd \  }}}t        j                  d|…d|…d|…f   \  }}}t        | j                   dd |«      }||   j	                  «       dt        j
                  f   }	||   j	                  «       dt        j
                  f   }
||   j	                  «       dt        j
                  f   }t        j                  |	|
|gd¬«      }t        j                  |D �cg c]%  }|j                  �t        |j                  «      nd‘Œ' c}«      }||fS c c}w )aò  Find regularly spaced centroids on the image.

    Parameters
    ----------
    image : 2D, 3D or 4D ndarray
        Input image, which can be 2D or 3D, and grayscale or
        multichannel.
    n_centroids : int
        The (approximate) number of centroids to be returned.

    Returns
    -------
    centroids : 2D ndarray
        The coordinates of the centroids with shape (~n_centroids, 3).
    steps : 1D ndarray
        The approximate distance between two seeds in all dimensions.

    Né   .r   ©Úaxisç      ð?)
Úshaper   Úmgridr   ÚravelÚnewaxisÚconcatenateÚasarrayÚstepr   )Úimager/   ÚdÚhÚwÚgrid_zÚgrid_yÚgrid_xÚslicesÚcentroids_zÚcentroids_yÚcentroids_xr9   Úsr=   s                  r>   Ú_get_grid_centroidsrY   G   s  € ð& �k‰k˜"˜1ˆo�G€A€qˆ!äŸX™X b q b¨"¨1¨"¨b¨q¨b jÑ1Ñ€FˆF�FÜ˜%Ÿ+™+ b q˜/¨;Ó7€Fà˜‘.×&Ñ&Ó(¨¬b¯j©j¨Ñ9€KØ˜‘.×&Ñ&Ó(¨¬b¯j©j¨Ñ9€KØ˜‘.×&Ñ&Ó(¨¬b¯j©j¨Ñ9€Kä—‘ ¨[¸+ÐFÈRÔP€Iä�J‰JÉfÓUÉfÈ¨¯©Ð);œ˜aŸf™fœÀÑDÈfÑUÓV€EØ�eÐÐùò Vs   Ã,*D!F)Úmultichannel_outputr   )Úchannel_axisc                óæ  — | j                   dk(  r|�t        d|› d�«      ‚t        | «      } t        j                  | j
                  «      }| j                  |d¬«      } |�]t        j                  |t        ¬«      }|�8t        j                  ||¬«      }t        j                  || j                  «      }n|}| |   }n| }|j                  «       }|j                  «       }t        j                  |«      rt        d	«      ‚t        j                   |«      st        j                   |«      rt        d
«      ‚| |z  } ||k7  r| ||z
  z  } |du}| j
                  }d}|du}| j                   dk(  r'| t        j"                  dt        j"                  f   } d}nO| j                   dk(  r|r| t        j"                  df   } d}n&| j                   dk(  r|s| dt        j"                  f   } |r@|s|€<| j                  |   dk7  r|rt        d«      ‚| j                  |   dk(  rt%        | «      } |dvrt        d«      ‚d}|r‚|j'                  d«      }|j                   dk(  r(t        j                  |t        j"                  df   «      }|j                  | j                  dd k7  rt        d«      ‚t)        |||«      \  }}d}nt+        | |«      \  }}|€t        j,                  d|¬«      }nÖt/        |t0        «      r»t        j2                  ||¬«      }|rb|j4                  dk7  r;|j4                  dk(  rt7        dt8        d¬«       nYt        d|j4                  › d�«      ‚t        j:                  |dd«      }n(|j4                  dk7  rt        d|j4                  › d�«      ‚t        j                  ||¬«      }nt=        d«      ‚t        j>                  |«      r t        j@                  |||g|¬«      }||z  }n³t/        |t0        «      r£t        j2                  ||¬«      }|rb|j4                  dk7  r;|j4                  dk(  rt7        dt8        d¬«       nYt        d|j4                  › d�«      ‚t        j:                  |dd«      }n(|j4                  dk7  rt        d|j4                  › d�«      ‚|dkD  jC                  «       rtE        |«      dgz   }tG        | |d¬ «      } |j                  d   }t        j                  t        jH                  |t        jJ                  || j                  d   f«      gd!¬«      |¬«      }t        |«      }d"|z  }t        j                  | |z  |¬«      } |rtM        | ||||||
d|¬#«	       tM        | ||||||
d|¬#«	      }|rf|r|jO                  «       |z  }n%tQ        jR                  | j                  dd «      |z  }tU        ||z  «      } tU        |	|z  «      }!tW        || |!|¬$«      }|r|d   }|S )%u‚  Segments image using k-means clustering in Color-(x,y,z) space.

    Parameters
    ----------
    image : (M, N[, P][, C]) ndarray
        Input image. Can be 2D or 3D, and grayscale or multichannel
        (see `channel_axis` parameter).
        Input image must either be NaN-free or the NaN's must be masked out.
    n_segments : int, optional
        The (approximate) number of labels in the segmented output image.
    compactness : float, optional
        Balances color proximity and space proximity. Higher values give
        more weight to space proximity, making superpixel shapes more
        square/cubic. In SLICO mode, this is the initial compactness.
        This parameter depends strongly on image contrast and on the
        shapes of objects in the image. We recommend exploring possible
        values on a log scale, e.g., 0.01, 0.1, 1, 10, 100, before
        refining around a chosen value.
    max_num_iter : int, optional
        Maximum number of iterations of k-means.
    sigma : float or array-like of floats, optional
        Width of Gaussian smoothing kernel for pre-processing for each
        dimension of the image. The same sigma is applied to each dimension in
        case of a scalar value. Zero means no smoothing.
        Note that `sigma` is automatically scaled if it is scalar and
        if a manual voxel spacing is provided (see Notes section). If
        sigma is array-like, its size must match ``image``'s number
        of spatial dimensions.
    spacing : array-like of floats, optional
        The voxel spacing along each spatial dimension. By default,
        `slic` assumes uniform spacing (same voxel resolution along
        each spatial dimension).
        This parameter controls the weights of the distances along the
        spatial dimensions during k-means clustering.
    convert2lab : bool, optional
        Whether the input should be converted to Lab colorspace prior to
        segmentation. The input image *must* be RGB. Highly recommended.
        This option defaults to ``True`` when ``channel_axis` is not None *and*
        ``image.shape[-1] == 3``.
    enforce_connectivity : bool, optional
        Whether the generated segments are connected or not
    min_size_factor : float, optional
        Proportion of the minimum segment size to be removed with respect
        to the supposed segment size ```depth*width*height/n_segments```
    max_size_factor : float, optional
        Proportion of the maximum connected segment size. A value of 3 works
        in most of the cases.
    slic_zero : bool, optional
        Run SLIC-zero, the zero-parameter mode of SLIC. [2]_
    start_label : int, optional
        The labels' index start. Should be 0 or 1.

        .. versionadded:: 0.17
           ``start_label`` was introduced in 0.17
    mask : ndarray, optional
        If provided, superpixels are computed only where mask is True,
        and seed points are homogeneously distributed over the mask
        using a k-means clustering strategy. Mask number of dimensions
        must be equal to image number of spatial dimensions.

        .. versionadded:: 0.17
           ``mask`` was introduced in 0.17
    channel_axis : int or None, optional
        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.

        .. versionadded:: 0.19
           ``channel_axis`` was added in 0.19.

    Returns
    -------
    labels : 2D or 3D array
        Integer mask indicating segment labels.

    Raises
    ------
    ValueError
        If ``convert2lab`` is set to ``True`` but the last array
        dimension is not of length 3.
    ValueError
        If ``start_label`` is not 0 or 1.
    ValueError
        If ``image`` contains unmasked NaN values.
    ValueError
        If ``image`` contains unmasked infinite values.
    ValueError
        If ``image`` is 2D but ``channel_axis`` is -1 (the default).

    Notes
    -----
    * If `sigma > 0`, the image is smoothed using a Gaussian kernel prior to
      segmentation.

    * If `sigma` is scalar and `spacing` is provided, the kernel width is
      divided along each dimension by the spacing. For example, if ``sigma=1``
      and ``spacing=[5, 1, 1]``, the effective `sigma` is ``[0.2, 1, 1]``. This
      ensures sensible smoothing for anisotropic images.

    * The image is rescaled to be in [0, 1] prior to processing (masked
      values are ignored).

    * Images of shape (M, N, 3) are interpreted as 2D RGB images by default. To
      interpret them as 3D with the last dimension having length 3, use
      `channel_axis=None`.

    * `start_label` is introduced to handle the issue [4]_. Label indexing
      starts at 1 by default.

    References
    ----------
    .. [1] Radhakrishna Achanta, Appu Shaji, Kevin Smith, Aurelien Lucchi,
        Pascal Fua, and Sabine SÃ¼sstrunk, SLIC Superpixels Compared to
        State-of-the-art Superpixel Methods, TPAMI, May 2012.
        :DOI:`10.1109/TPAMI.2012.120`
    .. [2] https://www.epfl.ch/labs/ivrl/research/slic-superpixels/#SLICO
    .. [3] Irving, Benjamin. "maskSLIC: regional superpixel generation with
           application to local pathology characterisation in medical images.",
           2016, :arXiv:`1606.09518`
    .. [4] https://github.com/scikit-image/scikit-image/issues/3722

    Examples
    --------
    >>> from skimage.segmentation import slic
    >>> from skimage.data import astronaut
    >>> img = astronaut()
    >>> segments = slic(img, n_segments=100, compactness=10)

    Increasing the compactness parameter yields more square regions:

    >>> segments = slic(img, n_segments=100, compactness=20)

    r	   Nzchannel_axis=z| indicates multichannel, which is not supported for a two-dimensional image; use channel_axis=None if the image is grayscaleT)Úcopyr   rC   z.unmasked NaN values in image are not supportedz3unmasked infinite values in image are not supportedF.rB   z/Lab colorspace conversion requires a RGB image.)r   r   zstart_label should be 0 or 1.Úuint8z*image and mask should have the same shape.zdInput image is 2D: spacing number of elements must be 2. In the future, a ValueError will be raised.)Ú
stacklevelz#Input image is 2D, but spacing has z elements (expected 2).r   r   z#Input image is 3D, but spacing has z elements (expected 3).z!spacing must be None or iterable.zbInput image is 2D: sigma number of elements must be 2. In the future, a ValueError will be raised.z!Input image is 2D, but sigma has z!Input image is 3D, but sigma has Úreflect)ÚsigmaÚmoder   rE   )Úignore_colorÚstart_label)rd   ),r'   Ú
ValueErrorr   r
   Ú_supported_float_typer   Úastyper   ÚascontiguousarrayÚboolÚexpand_dimsÚbroadcast_torF   r&   ÚmaxÚisnanÚisinfrI   r   Úviewr?   rY   ÚonesÚ
isinstancer   rK   Úsizer   ÚFutureWarningÚinsertÚ	TypeErrorÚisscalarr   ÚanyÚlistr   rJ   Úzerosr   ÚsumÚmathÚprodr#   r   )"rM   Ú
n_segmentsÚcompactnessÚmax_num_iterra   ÚspacingÚconvert2labÚenforce_connectivityÚmin_size_factorÚmax_size_factorÚ	slic_zerord   r.   r[   Úfloat_dtypeÚmask_Úimage_valuesÚiminÚimaxÚuse_maskr   Úis_2dr0   Úupdate_centroidsr9   r=   r/   ÚsegmentsrL   ÚratioÚlabelsÚsegment_sizeÚmin_sizeÚmax_sizes"                                     r>   Úslicr”   i   sÉ  € ðn ‡z�z�Q‚˜<Ð3ÜØ˜L˜>ð *%ð %ó
ð 	
ô ˜Ó€EÜ×-Ñ-¨e¯k©kÓ:€Kð �L‰L˜¨4ˆLÓ0€EàÐä×#Ñ# D´Ô5ˆØÐ#Ü—N‘N 4¨lÔ;ˆEÜ—O‘O E¨5¯;©;Ó7‰EàˆEØ˜U‘|‰àˆð ×ÑÓ€DØ×ÑÓ€DÜ	‡x�x�„~ÜÐIÓJÐJÜ	‡x�x�„~œŸ™ $œÜÐNÓOÐOØ	ˆT�M€EØˆt‚|Ø�˜‘Ñˆà˜4Ð€HØ�K‰K€Eà€Eà tÐ+€LØ‡z�z�Q‚à”b—j‘j #¤r§z¡zÐ1Ñ2ˆØ‰Ø	�‰�qŠ™\à”b—j‘j #�oÑ&ˆØ‰Ø	�‰�qŠ¡à�cœ2Ÿ:™:�oÑ&ˆá™¨Ð(;Ø�;‰;�|Ñ$¨Ò)©kÜÐNÓOÐOØ�[‰[˜Ñ&¨!Ò+Ü˜E“NˆEà˜&Ñ ÜÐ8Ó9Ð9ð ÐÙØ�y‰y˜Ó!ˆØ�9‰9˜Š>Ü×'Ñ'¨¬R¯Z©Z¸¨_Ñ(=Ó>ˆDØ�:‰:˜Ÿ™ R a˜Ò(ÜÐIÓJÐJÜ.¨t°ZÀÓNÑˆ	�5ØÑä.¨u°jÓAÑˆ	�5à€Ü—'‘'˜! 5Ô)‰Ü	�GœXÔ	&Ü—*‘*˜W¨EÔ2ˆÙØ�|‰|˜qÒ Ø—<‘< 1Ò$Üð*ô &Ø#$öô %Ø=Ø"Ÿ<™<˜.Ð(?ðAóð ô
 Ÿ)™) G¨Q°Ó2‘Ø�\‰\˜QÒÜØ5Ø—<‘<�.Ð 7ð9óð ô ×&Ñ& w°eÔ<‰äÐ;Ó<Ð<ä	‡{�{�5ÔÜ—‘˜% ¨Ð.°eÔ<ˆØ�Ñ‰Ü	�Eœ8Ô	$Ü—
‘
˜5¨Ô.ˆÙØ�z‰z˜QŠØ—<‘< 1Ò$Üð*ô &Ø#$öô %Ø;Ø Ÿ:™:˜,Ð&=ð?óð ô
 Ÿ	™	 %¨¨AÓ.‘Ø�Z‰Z˜1Š_ÜØ3Ø—:‘:�,Ð5ð7óð ð
 	�‰	‡�Ôä�U“˜q˜cÑ!ˆÜ˜ e°)Ô<ˆà—/‘/ !Ñ$€KÜ×#Ñ#Ü
�‰˜	¤2§8¡8¨[¸%¿+¹+Àa¹.Ð,IÓ#JÐKÐRTÔUØô€Hô ˆu‹:€DØ�+Ñ€Eä× Ñ  ¨¡°eÔ<€EáäØØØØØØØØØ#õ
	
ô ØØØØØØØØØô
€Fñ ÙØŸ8™8›:¨Ñ3‰LäŸ9™9 U§[¡[°°! _Ó5¸ÑCˆLÜ�¨Ñ5Ó6ˆÜ�¨Ñ5Ó6ˆÜ3Ø�H˜h°Kô
ˆñ Ø˜‘ˆà€Mr@   )éd   g      $@r   r   NNTg      à?rB   Fr   N)r{   Úcollections.abcr   Úwarningsr   Únumpyr   r   Úscipy.cluster.vqr   Úscipy.spatial.distancer   r   Ú_sharedr
   Ú_shared.filtersr   Úcolorr   Úutilr   r   Ú_slicr   r   r?   rY   Úchannel_as_last_axisr”   © r@   r>   Ú<module>r¢      s‰   ðÛ Ý $Ý ã Ý Ý $ß 4å Ý &Ý ß -ß Cò3òlðD €×Ñ°Ô6ð ØØØ
ØØØØØØØØ	ðWð óWó 7ñWr@   