
    0-Ph.                     P    d Z ddlZddlmZ d ZdddddddZdd	ZddZ	ddZ
dS )z4Utility functions used in the morphology subpackage.    N)ndimagec                 d   |d}t          j        |          rt          j        | |          }n4t          j        |t
                    }|j        | k    rt          d          |It          d |j	        D                       rt          d          t          j        |j	                  dz  }||fS )a  Convert any valid connectivity to a footprint and offset.

    Parameters
    ----------
    image_dim : int
        The number of dimensions of the input image.
    connectivity : int, array, or None
        The neighborhood connectivity. An integer is interpreted as in
        ``scipy.ndimage.generate_binary_structure``, as the maximum number
        of orthogonal steps to reach a neighbor. An array is directly
        interpreted as a footprint and its shape is validated against
        the input image shape. ``None`` is interpreted as a connectivity of 1.
    offset : tuple of int, or None
        The coordinates of the center of the footprint.

    Returns
    -------
    c_connectivity : array of bool
        The footprint (structuring element) corresponding to the input
        `connectivity`.
    offset : array of int
        The offset corresponding to the center of the footprint.

    Raises
    ------
    ValueError:
        If the image dimension and the connectivity or offset dimensions don't
        match.
    N   z,Connectivity dimension must be same as imagec                      g | ]}|d z  dk    S )   r    ).0xs     X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/skimage/morphology/_util.py
<listcomp>z*_validate_connectivity.<locals>.<listcomp>0   s     999qA
999    z2Connectivity array must have an unambiguous centerr   )
npisscalarndigenerate_binary_structurearrayboolndim
ValueErroranyshape)	image_dimconnectivityoffsetc_connectivitys       r   _validate_connectivityr      s    < 	{<   M6y,OO,55)++KLLL~99N$8999:: 	VTUUU..//146!!r   r   C)	footprintr   centerspacingorderc                j   t          |           }|t          j        ||          }|t          d |j        D                       }|j        |cxk    rt          |          k    sn t          d          t          j        d t          t          j
        |          |          D             d          }|dk    r|dddddf         }| ddd         } n|d	k    rt          d
          | dd         dz   }t          j        |ddd                   ddd         }||z                      d          }	|t          j        |          }||z  }
t          j        t          j        |
dz  d                    }|	t          j        |d                   }t          j        |d          }t#          d t          | |j                  D                       r?t          j        |d          \  }}t          j        |d          }||         }||         }|dd         }|dd         }||fS )au  Compute offsets to neighboring pixels in raveled coordinate space.

    This function also returns the corresponding distances from the center
    pixel given a spacing (assumed to be 1 along each axis by default).

    Parameters
    ----------
    image_shape : tuple of int
        The shape of the image for which the offsets are being computed.
    footprint : array of bool
        The footprint of the neighborhood, expressed as an n-dimensional array
        of 1s and 0s. If provided, the connectivity argument is ignored.
    connectivity : {1, ..., ndim}
        The square connectivity of the neighborhood: the number of orthogonal
        steps allowed to consider a pixel a neighbor. See
        `scipy.ndimage.generate_binary_structure`. Ignored if footprint is
        provided.
    center : tuple of int
        Tuple of indices to the center of the footprint. If not provided, it
        is assumed to be the center of the footprint, either provided or
        generated by the connectivity argument.
    spacing : tuple of float
        The spacing between pixels/voxels along each axis.
    order : 'C' or 'F'
        The ordering of the array, either C or Fortran ordering.

    Returns
    -------
    raveled_offsets : ndarray
        Linear offsets to a samples neighbors in the raveled image, sorted by
        their distance from the center.
    distances : ndarray
        The pixel distances corresponding to each offset.

    Notes
    -----
    This function will return values even if `image_shape` contains a dimension
    length that is smaller than `footprint`.

    Examples
    --------
    >>> off, d = _raveled_offsets_and_distances(
    ...         (4, 5), footprint=np.ones((4, 3)), center=(1, 1)
    ...         )
    >>> off
    array([-5, -1,  1,  5, -6, -4,  4,  6, 10,  9, 11])
    >>> d[0]
    1.0
    >>> d[-1]  # distance from (1, 1) to (3, 2)
    2.236...
    N)rankr   c              3       K   | ]	}|d z  V  
dS )r   Nr   r	   ss     r   	<genexpr>z1_raveled_offsets_and_distances.<locals>.<genexpr>x   s&      77!qAv777777r   zQnumber of dimensions in image shape, footprint and itscenter index does not matchc                     g | ]
\  }}||z
  S r   r   )r	   idxcs      r   r   z2_raveled_offsets_and_distances.<locals>.<listcomp>   s     DDDvsA#'DDDr   )axisFr   zorder must be 'C' or 'F'r   r   r   stable)kindc              3   (   K   | ]\  }}||k     V  d S )Nr   )r	   r
   ys      r   r'   z1_raveled_offsets_and_distances.<locals>.<genexpr>   s*      
?
?TQ1q5
?
?
?
?
?
?r   T)return_index)lenr   r   tupler   r   r   r   stackzipnonzerocumprodsumonessqrtargsortsortr   unique)image_shaper   r   r   r    r!   r   offsetsravel_factorsraveled_offsetsweighted_offsets	distancessorted_raveled_offsetssorted_distances_indicess                   r   _raveled_offsets_and_distancesrJ   8   s|   x {D1t,WWW	~77y77777>T0000S[[0000*
 
 	

 hDDRZ	%:%:F!C!CDDD2  G ||!!!TTrT'"!$$B$'	#3444  Od*MJ}TTrT233DDbD9M.333;;O '$--(/2;;;<<I,RZ	-Q-Q-QRwyx888 
?
?Sio>>
?
?
??? 5Y5DIII
7''111!7!@+G4 4ABB7'+!#333r   c                 8    t          | |||          d         }|S )a  Compute offsets to a samples neighbors if the image would be raveled.

    Parameters
    ----------
    image_shape : tuple
        The shape of the image for which the offsets are computed.
    footprint : ndarray
        The footprint (structuring element) determining the neighborhood
        expressed as an n-D array of 1's and 0's.
    center : tuple
        Tuple of indices to the center of `footprint`.
    order : {"C", "F"}, optional
        Whether the image described by `image_shape` is in row-major (C-style)
        or column-major (Fortran-style) order.

    Returns
    -------
    raveled_offsets : ndarray
        Linear offsets to a samples neighbors in the raveled image, sorted by
        their distance from the center.

    Notes
    -----
    This function will return values even if `image_shape` contains a dimension
    length that is smaller than `footprint`.

    Examples
    --------
    >>> _offsets_to_raveled_neighbors((4, 5), np.ones((4, 3)), (1, 1))
    array([-5, -1,  1,  5, -6, -4,  4,  6, 10,  9, 11])
    >>> _offsets_to_raveled_neighbors((2, 3, 2), np.ones((3, 3, 3)), (1, 1, 1))
    array([-6, -2, -1,  1,  2,  6, -8, -7, -5, -4, -3,  3,  4,  5,  7,  8, -9,
            9])
    )r   r   r!   r   )rJ   )r@   r   r   r!   rC   s        r   _offsets_to_raveled_neighborsrL      s2    F 5yu  	O r   Tc                 `   | ||}t          j        ||          } nt          j        | t                    } | j        |k    rt          d          |r-t          d | j        D                       rt          d          t          d | j        D                       rt          d          | S )a  Validate or create a footprint (structuring element).

    Depending on the values of `connectivity` and `footprint` this function
    either creates a new footprint (`footprint` is None) using `connectivity`
    or validates the given footprint (`footprint` is not None).

    Parameters
    ----------
    footprint : ndarray
        The footprint (structuring) element used to determine the neighborhood
        of each evaluated pixel (``True`` denotes a connected pixel). It must
        be a boolean array and have the same number of dimensions as `image`.
        If neither `footprint` nor `connectivity` are given, all adjacent
        pixels are considered as part of the neighborhood.
    connectivity : int
        A number used to determine the neighborhood of each evaluated pixel.
        Adjacent pixels whose squared distance from the center is less than or
        equal to `connectivity` are considered neighbors. Ignored if
        `footprint` is not None.
    ndim : int
        Number of dimensions `footprint` ought to have.
    enforce_adjacency : bool
        A boolean that determines whether footprint must only specify direct
        neighbors.

    Returns
    -------
    footprint : ndarray
        Validated or new footprint specifying the neighborhood.

    Examples
    --------
    >>> _resolve_neighborhood(None, 1, 2)
    array([[False,  True, False],
           [ True,  True,  True],
           [False,  True, False]])
    >>> _resolve_neighborhood(None, None, 3).shape
    (3, 3, 3)
    N)dtypez7number of dimensions in image and footprint do notmatchc              3   "   K   | ]
}|d k    V  dS )   Nr   r%   s     r   r'   z(_resolve_neighborhood.<locals>.<genexpr>  s&      $E$EQ!V$E$E$E$E$E$Er   z$dimension size in footprint is not 3c              3   (   K   | ]}|d z  dk    V  dS )r   r   Nr   r%   s     r   r'   z(_resolve_neighborhood.<locals>.<genexpr>  s*      77!!a%1*777777r   z/footprint size must be odd along all dimensions)	r   r   r   asarrayr   r   r   r   r   )r   r   r   enforce_adjacencys       r   _resolve_neighborhoodrT      s    P L1$EE		 Jy555	>T!!L    	P$E$EY_$E$E$E!E!E 	PCDDD77y77777 	PNOOOr   c                 ^   t          j        |          r||ff| j        z  }n't          |          | j        k    rt	          d          t          |          D ]\  }}t          |          dk    rt	          d          |\  }}||cxk    rdk    rn n=||cxk    rdk    r"n nt          d          f|z  dz   dz   }|| |<   l|dk    r-t          d          f|z  t          d|          fz   dz   }|| |<   |dk    r.t          d          f|z  t          | d          fz   dz   }|| |<   dS )	a  Set edge values along all axes to a constant value.

    Parameters
    ----------
    image : ndarray
        The array to modify inplace.
    value : scalar
        The value to use. Should be compatible with `image`'s dtype.
    border_width : int or sequence of tuples
        A sequence with one 2-tuple per axis where the first and second values
        are the width of the border at the start and end of the axis,
        respectively. If an int is provided, a uniform border width along all
        axes is used.

    Examples
    --------
    >>> image = np.zeros((4, 5), dtype=int)
    >>> _set_border_values(image, 1)
    >>> image
    array([[1, 1, 1, 1, 1],
           [1, 0, 0, 0, 1],
           [1, 0, 0, 0, 1],
           [1, 1, 1, 1, 1]])
    >>> image = np.zeros((8, 8), dtype=int)
    >>> _set_border_values(image, 1, border_width=((1, 1), (2, 3)))
    >>> image
    array([[1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 0, 0, 0, 1, 1, 1],
           [1, 1, 0, 0, 0, 1, 1, 1],
           [1, 1, 0, 0, 0, 1, 1, 1],
           [1, 1, 0, 0, 0, 1, 1, 1],
           [1, 1, 0, 0, 0, 1, 1, 1],
           [1, 1, 0, 0, 0, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1]])
    z.length of `border_width` must match image.ndimr   z2each sequence in `border_width` must have length 2r   r   N))r   r+   ).)r   r   r   r4   r   	enumerateslice)imagevalueborder_widthr,   npadw_startw_endsls           r   _set_border_valuesr_     s   H 
{<   K%|46C	\		ej	(	(IJJJ--  
dt99>>TUUUe    q     """""""""++$&3f<BE"IQ;;++$&%7*;*;)==FBE"I199++$&%*=*=)??&HBE"I% r   )r   )Tr.   )__doc__numpyr   scipyr   r   r   rJ   rL   rT   r_   r   r   r   <module>rc      s    : :                ." ." ."h 
l4 l4 l4 l4 l4^' ' ' 'T: : : :z: : : : : :r   