
    9i?                         S SK r S SKJr  S SKJr  S SKrS SKJr  S SKJ	r	  S SK
JrJr  SSKJr  SS	KJr  SS
KJr  SSKJrJr  SSKJrJr  S rS r\R6                  " SS9            SSS.S jj5       rg)    N)Iterable)warn)random)kmeans2)pdist
squareform   )utils)gaussian)rgb2lab)img_as_floatregular_grid   )"_enforce_label_connectivity_cython_slic_cythonc                 .   [         R                  " [         R                  " U 5      [        S9R                  n[
        R                  " S5      n[         R                  " [        U5      [        S9n[         R                  " UR                  U[        U[        U5      5      SS95      nSnU(       a  U R                  S-
  OU R                  n[        Xx-  U-  5      n	[        U5      U	:  a%  [         R                  " UR                  XYSS95      n
O[        n
[        X:   X6   SS9u  p[!        [#        U5      5      n[         R$                  " U[         R&                  5        UR)                  S	5      n[+        XUS
S
24   -
  5      R-                  S5      nX4$ )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      )iterNr   )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                   e/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/skimage/segmentation/slic_superpixels.py_get_mask_centroidsr?      s@   ( HHRZZ%U355E 

S
!C yyU3/H
''#**Xs;E
'CU*S
TC L$0499q=diiL<-<=G
5zG GGCJJx%JHI		5+UZa@LI eI&'DT266"++b/K	k1n556;;A>E    c                 B   U R                   SS u  p#n[        R                  SU2SU2SU24   u  pVn[        U R                   SS U5      nXX   R	                  5       S[        R
                  4   n	Xh   R	                  5       S[        R
                  4   n
Xx   R	                  5       S[        R
                  4   n[        R                  " XU/SS9n[        R                  " U Vs/ s H&  oR                  b  [        UR                  5      OSPM(     sn5      nX4$ s  snf )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    & kk"1oGA!XXbqb"1"bqbj1FF%++bq/;7F.&&(bjj9K.&&(bjj9K.&&(bjj9K+FRPIJJfUf);affDfUVE Vs   %-DF)multichannel_outputr   )channel_axisc                   U R                   S:X  a  Ub  [        SU S35      e[        U 5      n [        R                  " U R
                  5      nU R                  USS9n UbX  [        R                  " U[        S9nUb5  [        R                  " XS9n[        R                  " XR                  5      nOUnX   nOU nUR                  5       nUR                  5       n[        R                  " U5      (       a  [        S	5      e[        R                   " U5      (       d  [        R                   " U5      (       a  [        S
5      eU U-  n UU:w  a  U UU-
  -  n USLnU R
                  nSnUSLnU R                   S:X  a'  U [        R"                  S[        R"                  4   n SnO[U R                   S:X  a  U(       a  U [        R"                  S4   n SnO,U R                   S:X  a  U(       d  U S[        R"                  4   n U(       aM  U(       d  UcC  U R                  U   S:w  a  U(       a  [        S5      eU R                  U   S:X  a  [%        U 5      n US;  a  [        S5      eSnU(       a  UR'                  S5      nUR                   S:X  a)  [        R                  " U[        R"                  S4   5      nUR                  U R                  SS :w  a  [        S5      e[)        XU5      u  nnSnO[+        X5      u  nnUc  [        R,                  " SUS9nO[/        U[0        5      (       a  [        R2                  " UUS9nU(       ab  UR4                  S:w  a9  UR4                  S:X  a  [7        S[8        SS9  O[[        SUR4                   S35      e[        R:                  " USS5      nO)UR4                  S:w  a  [        SUR4                   S35      e[        R                  " UUS9nO[=        S5      e[        R>                  " U5      (       a  [        R@                  " XDU/US9nXE-  nO[/        U[0        5      (       a  [        R2                  " UUS9nU(       ab  UR4                  S:w  a9  UR4                  S:X  a  [7        S[8        SS9  O[[        SUR4                   S35      e[        R:                  " USS5      nO)UR4                  S:w  a  [        SUR4                   S35      eUS:  RC                  5       (       a  [E        U5      S/-   n[G        XSS 9n UR                  S   n[        R                  " [        RH                  " U[        RJ                  " UU R                  S   45      /S!S9US9n[        U5      nS"U-  n[        R                  " U U-  US9n U(       a  [M        U UUUUUU
SUS#9	  [M        U UUUUUU
SUS#9	nU(       ai  U(       a  URO                  5       U-  nO&[P        RR                  " U R                  SS 5      U-  n[U        UU-  5      n [U        U	U-  5      n![W        UU U!US$9nU(       a  US   nU$ )%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 zzQ<3L> *% %
 	
 E--ekk:K LL4L0E##D5#NN4;EOOE;;7EE| DD	xx~~IJJ	xx~~$NOO	TMEt|4HKKEEt+LzzQbjj#rzz12	q\bjj#o&	qc2::o&(;;;|$)kNOO[[&!+ENE& 899 yy!99>''RZZ_(=>D::Ra(IJJ.tN	5.uA	5''!5)	GX	&	&**WE2||q <<1$* &#$ %="<<.(?A 
 ))GQ2\\Q5<<. 79  &&we<;<<	{{5%.e<	E8	$	$

5.zzQ<<1$* &#$ %; ::,&=? 
 		%A.ZZ1_3::,57 
 		Uqc!)<//!$K##
	288[%++a.,I#JKRTUH u:D+E  e<E#
	
 
F 88:3L99U[[!_5CL56563HhK
 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@   