
    1-Ph                        d dl Zd dlmZ ddlmZmZmZ ddl	m
Z
 ddlmZ ddlmZmZmZmZmZmZmZ eeefZd	 Z	 	 	 	 	 	 	 d"dZ e            	 	 	 	 	 	 	 d"ddd            Z	 	 	 	 	 	 	 d#dZd$dZd Z	 	 	 	 	 	 	 	 	 	 d%dZd Zej        fdZd Z 	 	 	 	 	 	 	 d&dZ!d Z"d Z# e            	 d'dddddd            Z$d  Z%	 d(ddd!Z&dS ))    N)ndimage   )SimilarityTransformAffineTransformProjectiveTransform)
_warp_fast   )block_reduce)get_bound_method_classsafe_as_intwarnconvert_to_float_to_ndimage_mode_validate_interpolation_orderchannel_as_last_axisc                 *   t          |          }t          |          }| j        }|| j        k    r&|d|| j        z
  z  z  }t	          j        | |          } n:|| j        dz
  k    r|| j        d         fz   }n|| j        k     rt          d          | |fS )a'  Validate resize output shape according to input image.

    Parameters
    ----------
    image: ndarray
        Image to be resized.
    output_shape: iterable
        Size of the generated output image `(rows, cols[, ...][, dim])`. If
        `dim` is not provided, the number of channels is preserved.

    Returns
    -------
    image: ndarray
        The input image, but with additional singleton dimensions appended in
        the case where ``len(output_shape) > input.ndim``.
    output_shape: tuple
        The output image converted to tuple.

    Raises
    ------
    ValueError:
        If output_shape length is smaller than the image number of
        dimensions

    Notes
    -----
    The input image is reshaped if its number of dimensions is not
    equal to output_shape_length.

    r   r   zIoutput_shape length cannot be smaller than the image number of dimensions)tuplelenshapendimnpreshape
ValueError)imageoutput_shapeoutput_ndiminput_shapes       X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/skimage/transform/_warps.py_preprocess_resize_output_shaper!      s    > &&Ll##K+KUZt{UZ788
5+..	
Q	&	&#u{2&88	uz	!	!)
 
 	

 ,    reflectTFc	                    t          | |          \  } }| j        }	| j        }
|
t          j        k    r|                     t          j                  } |Y|
t          k     oLt          j        |
t          j	                  o|dk     o&t          d t          ||	          D                       }|
t          k    r|rt          d          t          j        |	|          }t          |
|          }|dk    rt          | |          } t!          |          }|r|t          j        d|dz
  dz            }n~t          j        |          t          j        |          z  }t          j
        |dk               rt          d          t          j
        |dk    |dk    z            rt)          d           t+          j        | |||	          }n| }d
 |D             }t+          j        |||||d          }t1          | ||||           |S )a  Resize image to match a certain size.

    Performs interpolation to up-size or down-size N-dimensional images. Note
    that anti-aliasing should be enabled when down-sizing images to avoid
    aliasing artifacts. For downsampling with an integer factor also see
    `skimage.transform.downscale_local_mean`.

    Parameters
    ----------
    image : ndarray
        Input image.
    output_shape : iterable
        Size of the generated output image `(rows, cols[, ...][, dim])`. If
        `dim` is not provided, the number of channels is preserved. In case the
        number of input channels does not equal the number of output channels a
        n-dimensional interpolation is applied.

    Returns
    -------
    resized : ndarray
        Resized version of the input.

    Other parameters
    ----------------
    order : int, optional
        The order of the spline interpolation, default is 0 if
        image.dtype is bool and 1 otherwise. The order has to be in
        the range 0-5. See `skimage.transform.warp` for detail.
    mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional
        Points outside the boundaries of the input are filled according
        to the given mode.  Modes match the behaviour of `numpy.pad`.
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.
    clip : bool, optional
        Whether to clip the output to the range of values of the input image.
        This is enabled by default, since higher order interpolation may
        produce values outside the given input range.
    preserve_range : bool, optional
        Whether to keep the original range of values. Otherwise, the input
        image is converted according to the conventions of `img_as_float`.
        Also see https://scikit-image.org/docs/dev/user_guide/data_types.html
    anti_aliasing : bool, optional
        Whether to apply a Gaussian filter to smooth the image prior
        to downsampling. It is crucial to filter when downsampling
        the image to avoid aliasing artifacts. If not specified, it is set to
        True when downsampling an image whose data type is not bool.
        It is also set to False when using nearest neighbor interpolation
        (``order`` == 0) with integer input data type.
    anti_aliasing_sigma : {float, tuple of floats}, optional
        Standard deviation for Gaussian filtering used when anti-aliasing.
        By default, this value is chosen as (s - 1) / 2 where s is the
        downsampling factor, where s > 1. For the up-size case, s < 1, no
        anti-aliasing is performed prior to rescaling.

    Notes
    -----
    Modes 'reflect' and 'symmetric' are similar, but differ in whether the edge
    pixels are duplicated during the reflection.  As an example, if an array
    has values [0, 1, 2] and was padded to the right by four values using
    symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it
    would be [0, 1, 2, 1, 0, 1, 2].

    Examples
    --------
    >>> from skimage import data
    >>> from skimage.transform import resize
    >>> image = data.camera()
    >>> resize(image, (100, 100)).shape
    (100, 100)

    Nr   c              3   (   K   | ]\  }}||k     V  d S N ).0xys      r    	<genexpr>zresize.<locals>.<genexpr>   s*      EEdaAEEEEEEEr"   z.anti_aliasing must be False for boolean imagesr   r	   zFAnti-aliasing standard deviation must be greater than or equal to zerozWAnti-aliasing standard deviation greater than zero but not down-sampling along all axes)cvalmodec                     g | ]}d |z  S r   r'   )r(   fs     r    
<listcomp>zresize.<locals>.<listcomp>   s    +++aAE+++r"   T)orderr-   r,   	grid_mode)r!   r   dtyper   float16astypefloat32bool
issubdtypeintegeranyzipr   divider   r   r   maximum
atleast_1d	ones_liker   ndigaussian_filterzoom_clip_warp_output)r   r   r1   r-   r,   clippreserve_rangeanti_aliasinganti_aliasing_sigmar   
input_typefactorsndi_modefilteredzoom_factorsouts                   r    resizerN   G   sR   h :%NNE<+KJRZRZ((d"" F]:rz::IuzJFEEc,&D&DEEEEE 	 TmIJJJi\22G)*e<<Eqyy 77  %%H &"$*Q10A"B"B"$-0C"D"Dr|H H # v)A-.. 	 4   ,q0W\BCC 7   &&T
 
 
 ++7+++L
(,e(QU  C eS$d333Jr"   )channel_axisc	                   t          j        |          }|	du}
t          |          dk    r_|
st          |          | j        k    s|
r*t          |          | j        dz
  k    rt	          d          |
rt          j        |dgf          }t          j        | j                  }t          j        t          j	        ||z            d          }|
r|d         |d<   t          | ||||||||	  	        S )ad  Scale image by a certain factor.

    Performs interpolation to up-scale or down-scale N-dimensional images.
    Note that anti-aliasing should be enabled when down-sizing images to avoid
    aliasing artifacts. For down-sampling with an integer factor also see
    `skimage.transform.downscale_local_mean`.

    Parameters
    ----------
    image : (M, N[, ...][, C]) ndarray
        Input image.
    scale : {float, tuple of floats}
        Scale factors for spatial dimensions. Separate scale factors can be defined as
        (m, n[, ...]).

    Returns
    -------
    scaled : ndarray
        Scaled version of the input.

    Other parameters
    ----------------
    order : int, optional
        The order of the spline interpolation, default is 0 if
        image.dtype is bool and 1 otherwise. The order has to be in
        the range 0-5. See `skimage.transform.warp` for detail.
    mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional
        Points outside the boundaries of the input are filled according
        to the given mode.  Modes match the behaviour of `numpy.pad`.
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.
    clip : bool, optional
        Whether to clip the output to the range of values of the input image.
        This is enabled by default, since higher order interpolation may
        produce values outside the given input range.
    preserve_range : bool, optional
        Whether to keep the original range of values. Otherwise, the input
        image is converted according to the conventions of `img_as_float`.
        Also see
        https://scikit-image.org/docs/dev/user_guide/data_types.html
    anti_aliasing : bool, optional
        Whether to apply a Gaussian filter to smooth the image prior
        to down-scaling. It is crucial to filter when down-sampling
        the image to avoid aliasing artifacts. If input image data
        type is bool, no anti-aliasing is applied.
    anti_aliasing_sigma : {float, tuple of floats}, optional
        Standard deviation for Gaussian filtering to avoid aliasing artifacts.
        By default, this value is chosen as (s - 1) / 2 where s is the
        down-scaling factor.
    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.

    Notes
    -----
    Modes 'reflect' and 'symmetric' are similar, but differ in whether the edge
    pixels are duplicated during the reflection.  As an example, if an array
    has values [0, 1, 2] and was padded to the right by four values using
    symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it
    would be [0, 1, 2, 1, 0, 1, 2].

    Examples
    --------
    >>> from skimage import data
    >>> from skimage.transform import rescale
    >>> image = data.camera()
    >>> rescale(image, 0.1).shape
    (51, 51)
    >>> rescale(image, 0.5).shape
    (256, 256)

    Nr   z4Supply a single scale, or one value per spatial axisr   )r1   r-   r,   rD   rE   rF   rG   )r   r>   r   r   r   concatenateasarrayr   r=   roundrN   )r   scaler1   r-   r,   rD   rE   rF   rG   rO   multichannel
orig_shaper   s                r    rescalerW      s   v M%  Et+L
5zzA~~ 	XUuz!9!9 ": ZZ5:>99VWWW 	1NEA3<00EEK((J:bhuz'9::A>>L *%b>R%#/
 
 
 
r"   constantc	           
         | j         d         | j         d         }
}	| j        t          j        k    r|                     t          j                  } |t          j        |
|	f          dz  dz
  }nt          j        |          }t          |          }t          t          j	        |                    }t          |           }||z   |z   }d}|rt          j        ddgd|	dz
  g|
dz
  |	dz
  g|
dz
  dgg          }|
                    |          }|dddf                                         }|dddf                                         }|dddf                                         }|dddf                                         }||z
  dz   }||z
  dz   }t          j        ||f          }||f}t          |          }||z   }d|j        d	<   t          | |||||||
          S )a	  Rotate image by a certain angle around its center.

    Parameters
    ----------
    image : ndarray
        Input image.
    angle : float
        Rotation angle in degrees in counter-clockwise direction.
    resize : bool, optional
        Determine whether the shape of the output image will be automatically
        calculated, so the complete rotated image exactly fits. Default is
        False.
    center : iterable of length 2
        The rotation center. If ``center=None``, the image is rotated around
        its center, i.e. ``center=(cols / 2 - 0.5, rows / 2 - 0.5)``.  Please
        note that this parameter is (cols, rows), contrary to normal skimage
        ordering.

    Returns
    -------
    rotated : ndarray
        Rotated version of the input.

    Other parameters
    ----------------
    order : int, optional
        The order of the spline interpolation, default is 0 if
        image.dtype is bool and 1 otherwise. The order has to be in
        the range 0-5. See `skimage.transform.warp` for detail.
    mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional
        Points outside the boundaries of the input are filled according
        to the given mode.  Modes match the behaviour of `numpy.pad`.
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.
    clip : bool, optional
        Whether to clip the output to the range of values of the input image.
        This is enabled by default, since higher order interpolation may
        produce values outside the given input range.
    preserve_range : bool, optional
        Whether to keep the original range of values. Otherwise, the input
        image is converted according to the conventions of `img_as_float`.
        Also see
        https://scikit-image.org/docs/dev/user_guide/data_types.html

    Notes
    -----
    Modes 'reflect' and 'symmetric' are similar, but differ in whether the edge
    pixels are duplicated during the reflection.  As an example, if an array
    has values [0, 1, 2] and was padded to the right by four values using
    symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it
    would be [0, 1, 2, 1, 0, 1, 2].

    Examples
    --------
    >>> from skimage import data
    >>> from skimage.transform import rotate
    >>> image = data.camera()
    >>> rotate(image, 2).shape
    (512, 512)
    >>> rotate(image, 2, resize=True).shape
    (530, 530)
    >>> rotate(image, 90, resize=True).shape
    (512, 512)

    r   r   Ng       @      ?)translation)rotation)r   r   r   r	   )r   r1   r-   r,   rD   rE   )r   r3   r   r4   r5   r6   arrayrR   r   deg2radinverseminmaxaroundparamswarp)r   anglerN   centerr1   r-   r,   rD   rE   rowscolstform1tform2tform3tformr   cornersmincminrmaxcmaxrout_rowsout_colsr[   tform4s                            r    rotateru   J  s   \ QQ$D{bj  RZ(( ~4,''#-3F## V444F "*U*;*;<<<F fW555FVOf$EL (QFQqMD1HdQh3G$QR(TUWXX--((qqq!t}  ""qqq!t}  ""qqq!t}  ""qqq!t}  ""$;?$;?y(H!566 Tl$===  ELO!%	 	 	 	r"   c                 :    t          | |t          j        |          S )a  Down-sample N-dimensional image by local averaging.

    The image is padded with `cval` if it is not perfectly divisible by the
    integer factors.

    In contrast to interpolation in `skimage.transform.resize` and
    `skimage.transform.rescale` this function calculates the local mean of
    elements in each block of size `factors` in the input image.

    Parameters
    ----------
    image : (M[, ...]) ndarray
        Input image.
    factors : array_like
        Array containing down-sampling integer factor along each axis.
    cval : float, optional
        Constant padding value if image is not perfectly divisible by the
        integer factors.
    clip : bool, optional
        Unused, but kept here for API consistency with the other transforms
        in this module. (The local mean will never fall outside the range
        of values in the input image, assuming the provided `cval` also
        falls within that range.)

    Returns
    -------
    image : ndarray
        Down-sampled image with same number of dimensions as input image.
        For integer inputs, the output dtype will be ``float64``.
        See :func:`numpy.mean` for details.

    Examples
    --------
    >>> a = np.arange(15).reshape(3, 5)
    >>> a
    array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14]])
    >>> downscale_local_mean(a, (2, 3))
    array([[3.5, 4. ],
           [5.5, 4.5]])

    )r
   r   mean)r   rI   r,   rD   s       r    downscale_local_meanrx     s    X w666r"   c                    | j         \  }}|\  }}t          j        ||z
  dz  ||z
  dz  z             }	|dz  t          j        d          z  }||t          j        |	 |z            z  z   t          j        ||z
  ||z
            z   }
||	t          j        |
          z  z   | d<   ||	t          j        |
          z  z   | d<   | S )Nr	      ).r   ).r   )Tr   sqrtlogexparctan2cossin)xyrf   r\   strengthradiusr)   r*   x0y0rhothetas              r    _swirl_mappingr     s    4DAqFB
'1r6a-1r6a-/
0
0C aZ"&))#Fx"&#"7"777"*QVQQSV:T:TTEcBF5MM))BvJcBF5MM))BvJIr"   d   c                     |-t          j        | j                  dd         ddd         dz  }||||d}t          | t          ||||||	|
	  	        S )aZ  Perform a swirl transformation.

    Parameters
    ----------
    image : ndarray
        Input image.
    center : (column, row) tuple or (2,) ndarray, optional
        Center coordinate of transformation.
    strength : float, optional
        The amount of swirling applied.
    radius : float, optional
        The extent of the swirl in pixels.  The effect dies out
        rapidly beyond `radius`.
    rotation : float, optional
        Additional rotation applied to the image.

    Returns
    -------
    swirled : ndarray
        Swirled version of the input.

    Other parameters
    ----------------
    output_shape : tuple (rows, cols), optional
        Shape of the output image generated. By default the shape of the input
        image is preserved.
    order : int, optional
        The order of the spline interpolation, default is 0 if
        image.dtype is bool and 1 otherwise. The order has to be in
        the range 0-5. See `skimage.transform.warp` for detail.
    mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional
        Points outside the boundaries of the input are filled according
        to the given mode, with 'reflect' used as the default. Modes match
        the behaviour of `numpy.pad`.
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.
    clip : bool, optional
        Whether to clip the output to the range of values of the input image.
        This is enabled by default, since higher order interpolation may
        produce values outside the given input range.
    preserve_range : bool, optional
        Whether to keep the original range of values. Otherwise, the input
        image is converted according to the conventions of `img_as_float`.
        Also see
        https://scikit-image.org/docs/dev/user_guide/data_types.html

    Nr	   r   )rf   r\   r   r   )map_argsr   r1   r-   r,   rD   rE   )r   r]   r   rd   r   )r   rf   r   r   r\   r   r1   r-   r,   rD   rE   	warp_argss               r    swirlr     s    z ~%+&&rr*44R4014 	 I !%
 
 
 
r"   c                 j    | j         dk    r |ddddt          j        f         | dd<   dS || dd<   dS )a5  Copy b into each color layer of a, such that::

      a[:,:,0] = a[:,:,1] = ... = b

    Parameters
    ----------
    a : (M, N) or (M, N, P) ndarray
        Target array.
    b : (M, N)
        Source array.

    Notes
    -----
    Color images are stored as an ``(M, N, 3)`` or ``(M, N, 4)`` arrays.

       N)r   r   newaxis)abs     r    
_stackcopyr   \  sG    " 	v{{AAArz!"!!!!!!r"   c                    t          |          }|d         |d         }}t          |          ||g}t          |          dk    r|                    |d                    t          j        ||          }t          j        ||f|                              dd          j        } | |          }|j                            d||f                              dd          }t          |d         |d                    t          |d         |d                    t          |          dk    rt          |d                   |d	<   |S )
a  Build the source coordinates for the output of a 2-D image warp.

    Parameters
    ----------
    coord_map : callable like GeometricTransform.inverse
        Return input coordinates for given output coordinates.
        Coordinates are in the shape (P, 2), where P is the number
        of coordinates and each element is a ``(row, col)`` pair.
    shape : tuple
        Shape of output image ``(rows, cols[, bands])``.
    dtype : np.dtype or string
        dtype for return value (sane choices: float32 or float64).

    Returns
    -------
    coords : (ndim, rows, cols[, bands]) array of dtype `dtype`
            Coordinates for `scipy.ndimage.map_coordinates`, that will yield
            an image of shape (orows, ocols, bands) by drawing from source
            points according to the `coord_transform_fn`.

    Notes
    -----

    This is a lower-level routine that produces the source coordinates for 2-D
    images used by `warp()`.

    It is provided separately from `warp` to give additional flexibility to
    users who would like, for example, to re-use a particular coordinate
    mapping, to use specific dtypes at various points along the the
    image-warping process, or to implement different post-processing logic
    than `warp` performs after the call to `ndi.map_coordinates`.


    Examples
    --------
    Produce a coordinate map that shifts an image up and to the right:

    >>> from skimage import data
    >>> from scipy.ndimage import map_coordinates
    >>>
    >>> def shift_up10_left20(xy):
    ...     return xy - np.array([-20, 10])[None, :]
    >>>
    >>> image = data.astronaut().astype(np.float32)
    >>> coords = warp_coords(shift_up10_left20, image.shape)
    >>> warped_image = map_coordinates(image, coords)

    r   r   r   r	   r3   r   )r   .)r   .)r	   .)r   r   appendr   emptyindicesr   r{   swapaxesr   range)	coord_mapr   r3   rg   rh   coords_shapecoords	tf_coordss           r    warp_coordsr   s  s9   b Eq58$DJJd+L
5zzQE!H%%%Xl%000F 
D$<u555==aDDFI 	)$$I ##Rt$455>>q!DDI vf~y0111 vf~y0111
5zzQuQxvMr"   c                 X   |r&t          j        |           }t          j        |          r$t           j        }t           j        } ||           }nt           j        }t           j        } ||           }|dk    o2||cxk    o|k    nc  o! ||          |cxk    o ||          k    nc }	|	r:| j                            |          }t          ||          }t          ||          }t          j        |          t          j        |          }}t          j	        ||||           dS dS )a  Clip output image to range of values of input image.

    Note that this function modifies the values of `output_image` in-place
    and it is only modified if ``clip=True``.

    Parameters
    ----------
    input_image : ndarray
        Input image.
    output_image : ndarray
        Output image, which is modified in-place.

    Other parameters
    ----------------
    mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}
        Points outside the boundaries of the input are filled according
        to the given mode.  Modes match the behaviour of `numpy.pad`.
    cval : float
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.
    clip : bool
        Whether to clip the output to the range of values of the input image.
        This is enabled by default, since higher order interpolation may
        produce values outside the given input range.

    rX   )rM   N)
r   r`   isnannanminnanmaxra   r3   typerR   rD   )
input_imageoutput_imager-   r,   rD   min_valmin_funcmax_funcmax_valpreserve_cvals
             r    rC   rC     sb   6  B&%%8G 	yHyHh{++GGvHvH(;''
 J It....w.....I&&$HHHH((<2H2HHHHH 	  	)$))$//D'4((G'4((G :g..
70C0C
gwLAAAAAA;B Br"           c	                    i | j         dk    rt          d| j                  t          | j        |          }|dk    rDt          | |          } | j        t          j        k    r|                     t          j	                  } t          j
        | j                  }	||	}nt          |          }d}
|dk    rt          d           |dv rtsqd}t          t          j                  rj        dk    r}nwt          t                    rj        }nZt#          d          rJj        d	k    r?t'                    t          v r)t          j                            j        j                  }||                    | j                  }| j        t          j	        k    rd
nd}| j        dk    rt1          |         | |||||          }
nt| j        dk    rig }t3          | j        d                   D ]8}|                    t1          |         | d|f         |||||                     9t          j        |          }
|
t          t          j                  rj        dk    rt9                    t          t          j                  r}nx| j        dk     s| j        dk    rt          d          fd}t;          |	          dk    r*t;          |          dk    r|d         |d         |	d         f}t=          ||          }|dk    }t?          |          }tA          j!        | |||||          }
tE          | |
|||           |
S )a  Warp an image according to a given coordinate transformation.

    Parameters
    ----------
    image : ndarray
        Input image.
    inverse_map : transformation object, callable ``cr = f(cr, **kwargs)``, or ndarray
        Inverse coordinate map, which transforms coordinates in the output
        images into their corresponding coordinates in the input image.

        There are a number of different options to define this map, depending
        on the dimensionality of the input image. A 2-D image can have 2
        dimensions for gray-scale images, or 3 dimensions with color
        information.

         - For 2-D images, you can directly pass a transformation object,
           e.g. `skimage.transform.SimilarityTransform`, or its inverse.
         - For 2-D images, you can pass a ``(3, 3)`` homogeneous
           transformation matrix, e.g.
           `skimage.transform.SimilarityTransform.params`.
         - For 2-D images, a function that transforms a ``(M, 2)`` array of
           ``(col, row)`` coordinates in the output image to their
           corresponding coordinates in the input image. Extra parameters to
           the function can be specified through `map_args`.
         - For N-D images, you can directly pass an array of coordinates.
           The first dimension specifies the coordinates in the input image,
           while the subsequent dimensions determine the position in the
           output image. E.g. in case of 2-D images, you need to pass an array
           of shape ``(2, rows, cols)``, where `rows` and `cols` determine the
           shape of the output image, and the first dimension contains the
           ``(row, col)`` coordinate in the input image.
           See `scipy.ndimage.map_coordinates` for further documentation.

        Note, that a ``(3, 3)`` matrix is interpreted as a homogeneous
        transformation matrix, so you cannot interpolate values from a 3-D
        input, if the output is of shape ``(3,)``.

        See example section for usage.
    map_args : dict, optional
        Keyword arguments passed to `inverse_map`.
    output_shape : tuple (rows, cols), optional
        Shape of the output image generated. By default the shape of the input
        image is preserved.  Note that, even for multi-band images, only rows
        and columns need to be specified.
    order : int, optional
        The order of interpolation. The order has to be in the range 0-5:
         - 0: Nearest-neighbor
         - 1: Bi-linear (default)
         - 2: Bi-quadratic
         - 3: Bi-cubic
         - 4: Bi-quartic
         - 5: Bi-quintic

         Default is 0 if image.dtype is bool and 1 otherwise.
    mode : {'constant', 'edge', 'symmetric', 'reflect', 'wrap'}, optional
        Points outside the boundaries of the input are filled according
        to the given mode.  Modes match the behaviour of `numpy.pad`.
    cval : float, optional
        Used in conjunction with mode 'constant', the value outside
        the image boundaries.
    clip : bool, optional
        Whether to clip the output to the range of values of the input image.
        This is enabled by default, since higher order interpolation may
        produce values outside the given input range.
    preserve_range : bool, optional
        Whether to keep the original range of values. Otherwise, the input
        image is converted according to the conventions of `img_as_float`.
        Also see
        https://scikit-image.org/docs/dev/user_guide/data_types.html

    Returns
    -------
    warped : double ndarray
        The warped input image.

    Notes
    -----
    - The input image is converted to a `double` image.
    - In case of a `SimilarityTransform`, `AffineTransform` and
      `ProjectiveTransform` and `order` in [0, 3] this function uses the
      underlying transformation matrix to warp the image with a much faster
      routine.

    Examples
    --------
    >>> from skimage.transform import warp
    >>> from skimage import data
    >>> image = data.camera()

    The following image warps are all equal but differ substantially in
    execution time. The image is shifted to the bottom.

    Use a geometric transform to warp an image (fast):

    >>> from skimage.transform import SimilarityTransform
    >>> tform = SimilarityTransform(translation=(0, -10))
    >>> warped = warp(image, tform)

    Use a callable (slow):

    >>> def shift_down(xy):
    ...     xy[:, 1] -= 10
    ...     return xy
    >>> warped = warp(image, shift_down)

    Use a transformation matrix to warp an image (fast):

    >>> matrix = np.array([[1, 0, 0], [0, 1, -10], [0, 0, 1]])
    >>> warped = warp(image, matrix)
    >>> from skimage.transform import ProjectiveTransform
    >>> warped = warp(image, ProjectiveTransform(matrix=matrix))

    You can also use the inverse of a geometric transformation (fast):

    >>> warped = warp(image, tform.inverse)

    For N-D images you can pass a coordinate array, that specifies the
    coordinates in the input image for every element in the output image. E.g.
    if you want to rescale a 3-D cube, you can do:

    >>> cube_shape = np.array([30, 30, 30])
    >>> rng = np.random.default_rng()
    >>> cube = rng.random(cube_shape)

    Setup the coordinate array, that defines the scaling:

    >>> scale = 0.1
    >>> output_shape = (scale * cube_shape).astype(int)
    >>> coords0, coords1, coords2 = np.mgrid[:output_shape[0],
    ...                    :output_shape[1], :output_shape[2]]
    >>> coords = np.array([coords0, coords1, coords2])

    Assume that the cube contains spatial data, where the first array element
    center is at coordinate (0.5, 0.5, 0.5) in real space, i.e. we have to
    account for this extra offset when scaling the image:

    >>> coords = (coords + 0.5) / scale - 0.5
    >>> warped = warp(cube, coords)

    Nr   z'Cannot warp empty image with dimensionsr	   aZ  Bi-quadratic interpolation behavior has changed due to a bug in the implementation of scikit-image. The new version now serves as a wrapper around SciPy's interpolation functions, which itself is not verified to be a correct implementation. Until skimage's implementation is fixed, we recommend to use bi-linear or bi-cubic interpolation instead.)r   r   )r   r   __name__r_   	float32_t	float64_t)r   r1   r-   r,   r   .)matrixz\Only 2-D images (grayscale or color) are supported, when providing a callable `inverse_map`.c                       | i S r&   r'   )argsinverse_mapr   s    r    r   zwarp.<locals>.coord_map  s    "{D5H555r"   r   )	prefilterr-   r1   r,   )#sizer   r   r   r3   r   r   r4   r5   r6   r]   r   r   
isinstancendarrayHOMOGRAPHY_TRANSFORMSrc   hasattrr   r   linalginv__self__r   r   r   r   dstackr   r   r   r   r@   map_coordinatesrC   )r   r   r   r   r1   r-   r,   rD   rE   r   warpedr   ctypedimsdimr   r   r   rJ   s    ``                r    rd   rd     s   n zQBEKPPP)%+u==Eqyy 77;"*$$LL,,E(5;''K""<00Fzz 	B	
 	
 	
 x k2:.. 	@;3D3N3N FF%:;; 
	@ 'FF K,,	@$	11&{337LLL Y]];#7#>??F]]5;//F#(;"*#<#<KK+EzQ#E*!-   q Q00 
 
CKK"5)!#s(O")5"'!%!%  	 	 	 	 4~ k2:.. 	B;3D3N3N .[AAAKk2:.. 	: FF zA~~a %  6 6 6 6 6 6 ;1$$\):):a)?)? !-Qa+a.Q L99F AI	#D))$6YXUQU
 
 
 eVT4666Mr"   c                    | dddf         |z  }| dddf         |z  t          j        |          z  |d         z   }| dddf         |z  t          j        |          z  |d         z   }t          j        ||f          }|S )a  Inverse mapping function to convert from cartesian to polar coordinates

    Parameters
    ----------
    output_coords : (M, 2) ndarray
        Array of `(col, row)` coordinates in the output image.
    k_angle : float
        Scaling factor that relates the intended number of rows in the output
        image to angle: ``k_angle = nrows / (2 * np.pi)``.
    k_radius : float
        Scaling factor that relates the radius of the circle bounding the
        area to be transformed to the intended number of columns in the output
        image: ``k_radius = ncols / radius``.
    center : tuple (row, col)
        Coordinates that represent the center of the circle that bounds the
        area to be transformed in an input image.

    Returns
    -------
    coords : (M, 2) ndarray
        Array of `(col, row)` coordinates in the input image that
        correspond to the `output_coords` given as input.
    Nr   r   )r   r   r   column_stackoutput_coordsk_anglek_radiusrf   re   rrccr   s           r    _linear_polar_mappingr     s    0 !!!Q$')EA)RVE]]
:fQi	GBA)RVE]]
:fQi	GB_b"X&&FMr"   c                 L   | dddf         |z  }t          j        | dddf         |z            t          j        |          z  |d         z   }t          j        | dddf         |z            t          j        |          z  |d         z   }t          j        ||f          }|S )a  Inverse mapping function to convert from cartesian to polar coordinates

    Parameters
    ----------
    output_coords : (M, 2) ndarray
        Array of `(col, row)` coordinates in the output image.
    k_angle : float
        Scaling factor that relates the intended number of rows in the output
        image to angle: ``k_angle = nrows / (2 * np.pi)``.
    k_radius : float
        Scaling factor that relates the radius of the circle bounding the
        area to be transformed to the intended number of columns in the output
        image: ``k_radius = width / np.log(radius)``.
    center : 2-tuple
        `(row, col)` coordinates that represent the center of the circle that bounds the
        area to be transformed in an input image.

    Returns
    -------
    coords : ndarray, shape (M, 2)
        Array of `(col, row)` coordinates in the input image that
        correspond to the `output_coords` given as input.
    Nr   r   )r   r~   r   r   r   r   s           r    _log_polar_mappingr   4  s    0 !!!Q$')E6-1%011RVE]]
BfQi	OB6-1%011RVE]]
BfQi	OB_b"X&&FMr"   linear)r   r   scalingrO   c                   |du}| j         dk    r|st          d| j                    | j         dk    r|rt          d| j                    |'t          j        | j                  dd         dz  dz
  }|Dt          j        | j                  dd         dz  \  }}	t          j        |dz  |	dz  z             }|(d}
t          t          j        |                    }|
|f}nt          |          }|d         }
|d	         }|d
k    r||z  }t          }n4|dk    r|t          j
        |          z  }t          }nt          d          |
dt          j        z  z  }|||d}t          | |f||d|}|S )a  Remap image to polar or log-polar coordinates space.

    Parameters
    ----------
    image : (M, N[, C]) ndarray
        Input image. For multichannel images `channel_axis` has to be specified.
    center : 2-tuple, optional
        `(row, col)` coordinates of the point in `image` that represents the center of
        the transformation (i.e., the origin in Cartesian space). Values can be of
        type `float`. If no value is given, the center is assumed to be the center point
        of `image`.
    radius : float, optional
        Radius of the circle that bounds the area to be transformed.
    output_shape : tuple (row, col), optional
    scaling : {'linear', 'log'}, optional
        Specify whether the image warp is polar or log-polar. Defaults to
        'linear'.
    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.
    **kwargs : keyword arguments
        Passed to `transform.warp`.

    Returns
    -------
    warped : ndarray
        The polar or log-polar warped image.

    Examples
    --------
    Perform a basic polar warp on a grayscale image:

    >>> from skimage import data
    >>> from skimage.transform import warp_polar
    >>> image = data.checkerboard()
    >>> warped = warp_polar(image)

    Perform a log-polar warp on a grayscale image:

    >>> warped = warp_polar(image, scaling='log')

    Perform a log-polar warp on a grayscale image while specifying center,
    radius, and output shape:

    >>> warped = warp_polar(image, (100,100), radius=100,
    ...                     output_shape=image.shape, scaling='log')

    Perform a log-polar warp on a color image:

    >>> image = data.astronaut()
    >>> warped = warp_polar(image, scaling='log', channel_axis=-1)
    Nr	   z@Input array must be 2-dimensional when `channel_axis=None`, got r   zHInput array must be 3-dimensional when `channel_axis` is specified, got rZ   ih  r   r   r   r}   z*Scaling value must be in {'linear', 'log'})r   r   rf   )r   r   )r   r   r   r]   r   r|   intceilr   r   r}   r   pird   )r   rf   r   r   r   rO   kwargsrU   whheightwidthr   map_funcr   r   r   s                    r    
warp_polarr   S  s   F  t+LzQ|5(-
5 5
 
 	

 zQ<=05
= =
 
 	

 ~(5;''+a/36~x$$RaR(1,1A1%%BGFOO$$"<00aQ(6>(	E		26&>>)%EFFFBE	"G#VLLIx"+, JP F Mr"   c                    |r7t          j        d| | dz   |          }t          j        d| |dz   |          }n| dz
  |dz
  }}t          j        t          j        d|dz
  ||          ddd|f          }|dk    rt           j        }nd|z  |z  }t          j        t          j        |||z
  ||          ddd|f          }t          j        |ddt           j        f         |t           j        ddf                   }	t          j        |dd	t           j        f         |t           j        dd	f                   }
t          j        |	|
z
  d          }||                    dd
          z  }|S )a  Create a 2D weight matrix for resizing with the local mean.

    Parameters
    ----------
    old_size: int
        Old size.
    new_size: int
        New size.
    grid_mode : bool
        Whether to use grid data model of pixel/voxel model for
        average weights computation.
    dtype: dtype
        Output array data type.

    Returns
    -------
    weights: (new_size, old_size) array
        Rows sum to 1.

    r   r   )numr3   rZ   r   rX   )constant_valuesNr   T)axiskeepdims)r   linspacepadinfminimumr   r=   sum)old_sizenew_sizer2   r3   
old_breaks
new_breaksoldnewvalupperlowerweightss               r    _local_mean_weightsr     s   *  
[H(Q,eLLL
[H(Q,eLLL

a<ASVKS3Y5999H	
 
 

 !88&CC)c/CVKS3Y5999H	
 
 

 Jz!""bj.1:bj!""n3MNNEJz#2#rz/2Jrz3B34OPPEj**Gw{{D{111GNr"   c                   ||| j          k     s|| j         k    rt          d          t          j        | |d          } | j        d         }t          |          }|| j         dz
  k    r||fz   }nY|| j         k    r?||         |k    rt          d          || j         z  }|d|         ||d         z   |fz   }nt          d          | }nt          | |          \  }}t          ||          }|j        }t          t          | j        |                    D ]Q\  }	\  }
}|
|k    rt          |
|||          }t          j        |||	gdgg          }t          j        |d|	          }R|t          j        |d|          }|S )a
  Resize an array with the local mean / bilinear scaling.

    Parameters
    ----------
    image : ndarray
        Input image. If this is a multichannel image, the axis corresponding
        to channels should be specified using `channel_axis`.
    output_shape : iterable
        Size of the generated output image. When `channel_axis` is not None,
        the `channel_axis` should either be omitted from `output_shape` or the
        ``output_shape[channel_axis]`` must match
        ``image.shape[channel_axis]``. If the length of `output_shape` exceeds
        image.ndim, additional singleton dimensions will be appended to the
        input ``image`` as needed.
    grid_mode : bool, optional
        Defines ``image`` pixels position: if True, pixels are assumed to be at
        grid intersections, otherwise at cell centers. As a consequence,
        for example, a 1d signal of length 5 is considered to have length 4
        when `grid_mode` is False, but length 5 when `grid_mode` is True. See
        the following visual illustration:

        .. code-block:: text

                | pixel 1 | pixel 2 | pixel 3 | pixel 4 | pixel 5 |
                     |<-------------------------------------->|
                                        vs.
                |<----------------------------------------------->|

        The starting point of the arrow in the diagram above corresponds to
        coordinate location 0 in each mode.
    preserve_range : bool, optional
        Whether to keep the original range of values. Otherwise, the input
        image is converted according to the conventions of `img_as_float`.
        Also see
        https://scikit-image.org/docs/dev/user_guide/data_types.html

    Returns
    -------
    resized : ndarray
        Resized version of the input.

    See Also
    --------
    resize, downscale_local_mean

    Notes
    -----
    This method is sometimes referred to as "area-based" interpolation or
    "pixel mixing" interpolation [1]_. When `grid_mode` is True, it is
    equivalent to using OpenCV's resize with `INTER_AREA` interpolation mode.
    It is commonly used for image downsizing. If the downsizing factors are
    integers, then `downscale_local_mean` should be preferred instead.

    References
    ----------
    .. [1] http://entropymine.com/imageworsener/pixelmixing/

    Examples
    --------
    >>> from skimage import data
    >>> from skimage.transform import resize_local_mean
    >>> image = data.camera()
    >>> resize_local_mean(image, (100, 100)).shape
    (100, 100)

    Nzinvalid channel_axisr   r   zWCannot reshape along the channel_axis. Use channel_axis=None to reshape along all axes.zZlen(output_shape) must be image.ndim or (image.ndim - 1) when a channel_axis is specified.)r   r   r   moveaxisr   r   r!   r   r3   	enumerater;   r   	tensordot)r   r   r2   rE   rO   ncr   resizedr3   r   r   r   r   products                 r    resize_local_meanr     s   J 5:+%%)C)C3444 E<44[_,''%*q.(('2%/LLEJ&&L)R// C  
 (%*4L]l]+l<==.IIREQ L 4    ?| T Tw77GME&/EK0N0N&O&O 1 1""xx%h)UKK,w4&2$@@+gr400+gr<88Nr"   )Nr#   r   TFNN)FNNrX   r   TF)r   T)
Nr   r   r   NNr#   r   TF)NNNrX   r   TFr&   )TF)'numpyr   scipyr   r@   
_geometricr   r   r   	_warps_cyr   measurer
   _shared.utilsr   r   r   r   r   r   r   r   r!   rN   rW   ru   rx   r   r   r   float64r   rC   rd   r   r   r   r   r   r'   r"   r    <module>r     s                   Q Q Q Q Q Q Q Q Q Q ! ! ! ! ! ! " " " " " "                  -o?RS / / /j 		
	J J J JZ  		
	r r r r r rp 
		
	{ { { {|,7 ,7 ,7 ,7^  & 
		
	Q Q Q Qh  . )+
 K K K K\8B 8B 8B| 
			V V V Vr  >  >  o o o o o od1 1 1j 9>rOSr r r r r r rr"   