
    9i                        S SK rS SKJr  SSKJrJrJr  SSK	J
r
  SSKJr  SSKJrJrJrJrJrJrJr  \\\4rS	 r       SS
 jr\" 5              SSS.S jj5       r       SS jrSS jrS r          SS jrS r\R<                  4S jrS r        S S jr!S r"S r#\" 5        S!SSSSS.S jj5       r$S r% S"SS.S jjr&g)#    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                 F   [        U5      n[        U5      nU R                  nX R                  :  a-  USX R                  -
  -  -  n[        R
                  " X5      n X4$ X R                  S-
  :X  a  XR                  S   4-   nX4$ X R                  :  a  [        S5      eX4$ )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/land-doc-ocr/venv/lib/python3.13/site-packages/skimage/transform/_warps.py_preprocess_resize_output_shaper       s    > &Ll#K++KZZt{ZZ788

5.  


Q	&#{{2&88  
zz	!)
 	

     c	           	      H   [        X5      u  pU R                  n	U R                  n
U
[        R                  :X  a  U R                  [        R                  5      n Uci  U
[        :X  + =(       aX    [        R                  " U
[        R                  5      =(       a    US:H  (       + =(       a    [        S [        X5       5       5      nU
[        :X  a  U(       a  [        S5      e[        R                  " X5      n[        X5      nUS:  a  [        X5      n [!        U5      nU(       a  Uc  [        R"                  " SUS-
  S-  5      nO[        R$                  " U5      [        R&                  " U5      -  n[        R                  " US:  5      (       a  [        S5      e[        R                  " US:  US:*  -  5      (       a  [)        S5        [*        R,                  " XXLS9nOU nU Vs/ s H  nSU-  PM
     nn[*        R.                  " XX,US	S
9n[1        U UX4U5        U$ s  snf )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)

r   c              3   .   #    U  H  u  pX:  v   M     g 7fN ).0xys      r   	<genexpr>resize.<locals>.<genexpr>   s     E&DdaAE&Ds   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modeT)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   r-   r,   r+   clippreserve_rangeanti_aliasinganti_aliasing_sigmar   
input_typefactorsndi_modefilteredfzoom_factorsouts                    r   resizerK   G   s   h :%NE++KJRZZRZZ(d" F]]:rzz:IuzJFEc,&DEE 	 TmIJJii2G)*<Eqy 7  %H&"$**Q10A"B"$--0C"Dr||H # vv)A-.. 4  ,q0W\BCC7 &&T
 #*+7aAE7L+
((eQUC eS$d3J ,s   'H)channel_axisc	                
   [         R                  " U5      nU	SLn
[        U5      S:  an  U
(       d  [        U5      U R                  :w  d#  U
(       a'  [        U5      U R                  S-
  :w  a  [	        S5      eU
(       a  [         R
                  " US/45      n[         R                  " U R                  5      n[         R                  " [         R                  " X-  5      S5      nU
(       a  US   US'   [        U UUUUUUUUS9	$ )aT  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   )r-   r,   r+   r@   rA   rB   rC   )r   r:   r   r   r   concatenateasarrayr   r9   roundrK   )r   scaler-   r,   r+   r@   rA   rB   rC   rL   multichannel
orig_shaper   s                r   rescalerT      s    v MM% Et+L
5zA~Uuzz!9SZ5::>9VWWNNEA3<0EEKK(J::bhhu'9:A>L%b>R%#/
 
r!   c	                    U R                   S   U R                   S   pU R                  [        R                  :X  a  U R	                  [        R
                  5      n Uc  [        R                  " X45      S-  S-
  nO[        R                  " U5      n[        US9n[        [        R                  " U5      S9n[        U* S9nX-   U-   nSnU(       a  [        R                  " SS/SU	S-
  /U
S-
  U	S-
  /U
S-
  S//5      nUR                  U5      nUSS2S4   R                  5       nUSS2S4   R                  5       nUSS2S4   R                  5       nUSS2S4   R                  5       nUU-
  S-   nUU-
  S-   n[        R                  " UU45      nUU4n[        US9nUU-   nSUR                  S	'   [        U UUUUUUUS
9$ )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   r-   r,   r+   r@   rA   )r   r/   r   r0   r1   r2   arrayrO   r   deg2radinverseminmaxaroundparamswarp)r   anglerK   centerr-   r,   r+   r@   rA   rowscolstform1tform2tform3tformr   cornersmincminrmaxcmaxrout_rowsout_colsrW   tform4s                            r   rotaterq   J  s   \ QQ${{bjj RZZ( ~4,'#-3F# V4F "**U*;<F fW5FOf$EL((QFQqMD1HdQh3G$QR(TUWX--(q!t}  "q!t}  "q!t}  "q!t}  "$;?$;?yy(H!56 Tl$=  ELLO!%	 	r!   c                 8    [        X[        R                  U5      $ )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   rE   r+   r@   s       r   downscale_local_meanrt     s    X 66r!   c                    U R                   u  pVUu  px[        R                  " XW-
  S-  Xh-
  S-  -   5      n	US-  [        R                  " S5      -  nX#[        R                  " U	* U-  5      -  -   [        R
                  " Xh-
  XW-
  5      -   n
Xy[        R                  " U
5      -  -   U S'   X[        R                  " U
5      -  -   U S'   U $ )Nr	      ).r   ).r   )Tr   sqrtlogexparctan2cossin)xyrb   rX   strengthradiusr'   r(   x0y0rhothetas              r   _swirl_mappingr     s    44DAFB
''16a-16a-/
0C aZ"&&)#F"&&#"777"**QVQV:TTEBFF5M))BvJBFF5M))BvJIr!   c                     Uc,  [         R                  " U R                  5      SS SSS2   S-  nUUUUS.n[        U [        UUUUUU	U
S9	$ )a  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   )rb   rX   r   r   )map_argsr   r-   r,   r+   r@   rA   )r   rY   r   r`   r   )r   rb   r   r   rX   r   r-   r,   r+   r@   rA   	warp_argss               r   swirlr     sp    z ~%++&r*4R4014 	I !%
 
r!   c                 h    U R                   S:X  a  USS2SS2[        R                  4   U SS& gXSS& g)a	  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   \  s/    " 	vv{Arzz!"!!r!   c                    [        U5      nUS   US   pC[        U5      X4/n[        U5      S:X  a  UR                  US   5        [        R                  " XRS9n[        R
                  " XC4US9R                  SS5      R                  nU " U5      nUR                  R                  SXC45      R                  SS5      n[        US   US   5        [        US   US   5        [        U5      S:X  a  [        US   5      US	'   U$ )
aQ  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	   r/   r   )r   .)r   .)r	   .)r   r   appendr   emptyindicesr   rw   swapaxesr   range)	coord_mapr   r/   rc   rd   coords_shapecoords	tf_coordss           r   warp_coordsr   s  s    b Eq58$J+L
5zQE!H%XXl0F 

D<u5==aDFFI )$I ##R$45>>q!DI vf~y01 vf~y01
5zQuQxvMr!   c                    U(       GaH  [         R                  " U 5      n[         R                  " U5      (       a)  [         R                  n[         R                  nU" U 5      nO [         R                  n[         R
                  nU" U 5      nUS:H  =(       aA    XSs=:*  =(       a    U:*  Os  (       + =(       a!    U" U5      Us=:*  =(       a    U" U5      :*  Os  n	U	(       a1  U R                  R                  U5      n[        XS5      n[        X5      n[         R                  " U5      [         R                  " U5      p[         R                  " XXS9  gg)aD  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.

constant)rJ   N)
r   r\   isnannanminnanmaxr]   r/   typerO   r@   )
input_imageoutput_imager,   r+   r@   min_valmin_funcmax_funcmax_valpreserve_cvals
             r   r?   r?     s    6 &&%88GyyHyyH{+GvvHvvH;'
 J I..w..I&$HH(<2HH 	 $$))$/D'(G'(G ::g.

70C
wA; r!   c	                   ^^ Tc  0 mU R                   S:X  a  [        SU R                  5      e[        U R                  U5      nUS:  aH  [        X5      n U R                  [        R                  :X  a  U R                  [        R                  5      n [        R                  " U R                  5      n	Uc  U	nO[        U5      nSn
US:X  a  [        S5        US;   Ga  T(       Gd  Sn[        T[        R                  5      (       a  TR                  S:X  a  TnO[        T[        5      (       a  TR                   nOg[#        TS5      (       aV  TR$                  S	:X  aF  ['        T5      [        ;   a3  [        R(                  R+                  TR,                  R                   5      nUb  UR                  U R                  5      nU R                  [        R                  :X  a  S
OSnU R.                  S:X  a  [0        U   " U UUUUUS9n
OmU R.                  S:X  a]  / n[3        U R                  S   5       H)  nUR5                  [0        U   " U SU4   UUUUUS95        M+     [        R6                  " U5      n
U
c  [        T[        R                  5      (       a  TR                  S:X  a	  [9        TS9m[        T[        R                  5      (       a  TnOjU R.                  S:  d  U R.                  S:  a  [        S5      eUU4S jn[;        U	5      S:X  a  [;        U5      S:X  a  US   US   U	S   4n[=        UU5      nUS:  n[?        U5      n[@        RB                  " XUUXFS9n
[E        X
XVU5        U
$ )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   r-   r,   r+   r   .)matrixz\Only 2-D images (grayscale or color) are supported, when providing a callable `inverse_map`.c                     > T" U 0 TD6$ r$   r%   )argsinverse_mapr   s    r   r   warp.<locals>.coord_map  s    "D5H55r!   r   )	prefilterr,   r-   r+   )#sizer   r   r   r/   r   r   r0   r1   r2   rY   r   r   
isinstancendarrayHOMOGRAPHY_TRANSFORMSr_   hasattrr   r   linalginv__self__r   r   r   r   dstackr   r   r   r   r<   map_coordinatesr?   )r   r   r   r   r-   r,   r+   r@   rA   r   warpedr   ctypedimsdimr   r   r   rF   s    ``                r   r`   r`     s	   n zzQBEKKPP)%++u=Eqy 7;;"**$LL,E((5;;'K""<0Fz 	B	
 x k2::..;3D3D3N F%:;; ''F K,,$$	1&{37LL YY]];#7#7#>#>?F]]5;;/F#(;;"**#<K+EzzQ#E*!- q Q0CKK"5)!#s(O")5"'!%!%	 1 4~ k2::..;3D3D3N .[AKk2::.. F zzA~a % 6 ;1$\):a)? !-Qa+a.Q L9F AI	#D)$$YXU
 eT6Mr!   c                     U SS2S4   U-  nU SS2S4   U-  [         R                  " U5      -  US   -   nU SS2S4   U-  [         R                  " U5      -  US   -   n[         R                  " Xe45      nU$ )aC  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_radiusrb   ra   rrccr   s           r   _linear_polar_mappingr     s~    0 !Q$')EA)RVVE]
:fQi	GBA)RVVE]
:fQi	GB__bX&FMr!   c                 @   U SS2S4   U-  n[         R                  " U SS2S4   U-  5      [         R                  " U5      -  US   -   n[         R                  " U SS2S4   U-  5      [         R                  " U5      -  US   -   n[         R                  " Xe45      nU$ )aV  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   rz   r}   r|   r   r   s           r   _log_polar_mappingr   4  s    0 !Q$')E66-1%01RVVE]
BfQi	OB66-1%01RVVE]
BfQi	OB__bX&FMr!   linear)r   r   scalingrL   c                   USLnU R                   S:w  a  U(       d  [        SU R                    35      eU R                   S:w  a  U(       a  [        SU R                    35      eUc)  [        R                  " U R                  5      SS S-  S-
  nUcG  [        R                  " U R                  5      SS S-  u  p[        R
                  " US-  U	S-  -   5      nUc%  Sn
[        [        R                  " U5      5      nX4nO[        U5      nUS   n
US	   nUS
:X  a  X-  n[        nO1US:X  a   U[        R                  " U5      -  n[        nO[        S5      eU
S[        R                  -  -  nXUS.n[        X4XS.UD6nU$ )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 rV   ih  r   r   r   ry   z*Scaling value must be in {'linear', 'log'})r   r   rb   )r   r   )r   r   r   rY   r   rx   intceilr   r   ry   r   pir`   )r   rb   r   r   r   rL   kwargsrR   whheightwidthr   map_funcr   r   r   s                    r   
warp_polarr   S  s   F  t+LzzQ|((-

|5
 	

 zzQ<005

|=
 	

 ~((5;;'+a/36~xx$Ra(1,A1%BGGFO$"<0aQ(>(	E	266&>)%EFFBEE	"G#VLI"+JPF Mr!   c           	         U(       a3  [         R                  " SX S-   US9n[         R                  " SXS-   US9nOU S-
  US-
  pv[         R                  " [         R                  " SUS-
  XcS9SSSU4S9nUS:X  a  [         R                  nOSU-  U-  n[         R                  " [         R                  " XU-
  XsS9SSSU4S9n[         R                  " USS2[         R
                  4   U[         R
                  SS24   5      n	[         R                  " USS	2[         R
                  4   U[         R
                  SS	24   5      n
[         R                  " X-
  S5      nXR                  SS
S9-  nU$ )ak  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   )numr/   rV   r   r   )constant_valuesNr   T)axiskeepdims)r   linspacepadinfminimumr   r9   sum)old_sizenew_sizer.   r/   
old_breaks
new_breaksoldnewvalupperlowerweightss               r   _local_mean_weightsr     sK   * [[HQ,eL
[[HQ,eL
a<ASVVKKS3Y9H	

 !8&&C)c/CVVKK3Y9H	

 JJz!"bjj.1:bjj!"n3MNEJJz#2#rzz/2Jrzz3B34OPEjj*G{{D{11GNr!   c                   Ub  X@R                   * :  d  X@R                   :  a  [        S5      e[        R                  " XS5      n U R                  S   n[        U5      nX`R                   S-
  :X  a  X4-   nOJX`R                   :X  a0  X   U:w  a  [        S5      eX@R                   -  nUSU XS -   U4-   nO[        S5      eU nO[        X5      u  pq[        Xs5      nUR                  n[        [        U R                  U5      5       HN  u  n	u  pX:X  a  M  [        XX(5      n[        R                  " X|U	/S//5      n[        R                  " USU	5      nMP     Ub  [        R                  " USU5      nU$ )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   r/   	enumerater7   r   	tensordot)r   r   r.   rA   rL   ncr   resizedr/   r   r   r   r   products                 r   resize_local_meanr     s   J ::+%)C344 E4[[_,'**q.('%/LJJ&)R/ C 
 (**4L]l+l=.IIREQ  4   ? Tw7GMME&/EKK0N&O""x%h)K,,w4&2$@++gr40 'P ++gr<8Nr!   )Nreflectr   TFNN)FNNr   r   TF)r   T)
Nr   d   r   NNr   r   TF)NNNr   g        TFr$   )TF)'numpyr   scipyr   r<   
_geometricr   r   r   	_warps_cyr   measurer
   _shared.utilsr   r   r   r   r   r   r   r   r    rK   rT   rq   rt   r   r   r   float64r   r?   r`   r   r   r   r   r   r%   r!   r   <module>r      sw      Q Q ! "   -o?RS /j 		
	JZ  		
	r r rp 
		
	{|,7^& 
		
	Qh. )+

 K\8B| 
			Vr>>  o o od1j 9>rOSrr!   