
    89ji             	          d dl m Z  d dlZd dlZd dlmZmZ d dlmZ d dlZd dl	Z
d dlmZ ddlmZmZmZmZmZ ddlmZ d	 Zd(d
Zd(dZd Zd Zd Z G d de      Zd Z G d de      Z G d de      Z G d de      Z G d de      Z ee G d de                     Z! G d de      Z"d)dZ# G d d e       Z$ee G d! d"e$                    Z% G d# d$e      Z&e$e%e!e"e eee&d%Z'd& Z(d' Z)y)*    )copyN)ABCabstractmethod)Self)spatial   )safe_as_int_deprecate_estimate_update_from_estimate_docstring_deprecate_inherited_estimateFailedEstimation)NP_COPY_IF_NEEDEDc                 @   | j                   }dt        j                  dd|z  z         z   dz  dz
  }t        t        j                  |            }||k7  rt        d|       t        j                  |dz         }t        j                  | ||dz   f      |ddddf<   |S )z8Affine matrix from linearized (d, d + 1) matrix entries.      r   z2Invalid number of elements for linearized matrix: N)sizenpsqrtintround
ValueErroreyereshape)vnparamddimensionalitymatrixs        \/media/conek/DATA/Code/OCR/venv/lib/python3.12/site-packages/skimage/transform/_geometric.py_affine_matrix_from_vectorr!      s    VVF	
RWWQV^$	$)A-A!%NNCF8L
 	
 VVNQ&'FZZNNQ4F#GHF3B36NM    c                 \   | j                   \  }}|j                         }t        j                  |dz         }|dk(  r|S t        j                  | d      }| |z
  }|dk(  r,t        j
                  t        j                  |dz              }nk|dk(  rWt        j                  t        j
                  t        j                  |dz  d                  t        j
                  |      z  }nt        d| d	      |dk(  r|t        j                  z   S | |d
||f<   |d
|d
d
fxx   |z  cc<   |S )a
  Calculate transformation `matrix` to center and normalize image points.

    Points are an array of shape (N, D).

    For `scaling` of 'raw', transformation returned `matrix` will be ``np.eye(D
    + 1)``.  For other values of `scaling`, `matrix` expresses a two-step
    translation and scaling procedure.  Points transformed with this `matrix`
    usually give better conditioning for fundamental matrix estimation than the
    original `points` [1]_.

    The two steps of transformation, for `scaling` other than 'raw', are:

    * Center the image points, such that the new coordinate system has its
      origin at the centroid of the image points.
    * Normalize the image points, such that the mean coordinate value of the
      centered points is 1 (`scaling` == 'rms') or such that the
      mean distance from the points to the origin of the coordinate system is
      ``sqrt(D)`` (`scaling` == 'mrs').

    If `scaling` != 'raw' and the points are all identical, the returned
    `matrix` will be all ``np.nan``.

    The 'mrs' scaling corresponds to the isotropic transformation
    algorithm in [1]_. 'rms' is the default, and gives very similar
    conditioning.

    Parameters
    ----------
    points : (N, D) array
        The coordinates of the image points.
    scaling : {'rms', 'mrs', 'raw'}, optional
        Scaling algorithm adjusting for magnitude of `points` after applying
        calculated translation. See above for explanation.

    Returns
    -------
    matrix : (D+1, D+1) array_like
        The transformation matrix to obtain the new points.

    References
    ----------
    .. [1] Hartley, Richard I. "In defense of the eight-point algorithm."
           Pattern Analysis and Machine Intelligence, IEEE Transactions on 19.6
           (1997): 580-593.

    r   rawr   axisrmsr   mrszUnexpected "scaling" of ""N)	shapelowerr   r   meanr   sumr   nan)pointsscalingnr   r   centroidcentereddivisors           r    _calc_center_normalizer5   $   s   ^ <<DAqmmoGVVAE]F%wwvA&H H%''"''(A+./	E	''"''"&&11"=>?"''!*L4WIQ?@@ !|IF2A2q5M
2A2q5MWMMr"   c                     t        | |      }t        j                  t        j                  |            s7|t        j                  z   t        j
                  | t        j                        fS |t        ||       fS )zConvenience function to calculate and apply scaling

    See: :func:`_calc_center_normalize` for details of the algorithm.
    )r5   r   allisfiniter.   	full_like_apply_homogeneous)r/   r0   r   s      r    _center_and_normalize_pointsr;   o   sZ    
 $FG4F66"++f%&VRVV <<<%ff555r"   c                     t        j                  |t        d      }t        |      }|| j                  z  }|dddf   }t        j
                  |dk(  t        j                  t              j                  |      }|ddddf   |dddf   z  S )a  Transform (N, D) `points` array with homogeneous (D+1, D+1) `matrix`.

    Parameters
    ----------
    matrix : (D+1, D+1) array_like
        The transformation matrix to obtain the new points. Note that any
        object with an `__array__` method [1]_ that returns a matrix with the
        correct dimensions can be used as input here. This includes all
        subclasses of :class:`ProjectiveTransform`, for example.
    points : (N, D) array
        The coordinates of the image points.

    Returns
    -------
    new_points : (N, D) array
        The transformed image points.

    References
    ----------
    .. [1]:
        https://numpy.org/doc/stable/user/basics.interoperability.html#using-arbitrary-objects-in-numpy
    r   )r   ndminNr   r   )	r   arrayr   _append_homogeneous_dimTwherefinfofloateps)r   r/   points_hnew_points_hdivss        r    r:   r:   z   s    . XXf#4A>F&v.Hfhh&L 2D88DAIrxx22D9D3B3$q$w-//r"   c                 l    t        j                  | t        j                  t        |       df      f      S )a  Append a column of ones to the right of `points`.

    This creates the representation of the points in the homogeneous coordinate
    space used by homogeneous matrix transforms.

    Parameters
    ----------
    points : array, shape (N, D)
        The input coordinates, where N is the number of points and D is the
        dimension of the coordinate space.

    Returns
    -------
    points_h : array, shape (N, D+1)
        The same points as homogeneous coordinates.
    r   )r   hstackoneslen)r/   s    r    r?   r?      s*    " 99fbggs6{A&67899r"   c                    t        j                  |       } t        j                  |      }| j                  d   }| j                  d   }| j                  d      }|j                  d      }| |z
  }||z
  }|j                  |z  |z  }	t        j
                  |ft         j                        }
t         j                  j                  |	      dk  rd|
|dz
  <   t        j                  |dz   t         j                        }t         j                  j                  |	      \  }}}|j                         t        j                  |	j                        z  t        j                  t              j                  z  }t        j                  ||kD        }|dk(  rt         j                   |z  S ||dz
  k(  rt         j                  j                  |      t         j                  j                  |      z  dkD  r||z  |d|d|f<   na|
|dz
     }d|
|dz
  <   |t        j"                  |
      z  |z  |d|d|f<   ||
|dz
  <   n$|t        j"                  |
      z  |z  |d|d|f<   |r*d|j%                  d      j'                         z  ||
z  z  }nd}|||d|d|f   |j                  z  z  z
  |d||f<   |d|d|fxx   |z  cc<   |S )a  Estimate N-D similarity transformation with or without scaling.

    Parameters
    ----------
    src : (M, N) array_like
        Source coordinates.
    dst : (M, N) array_like
        Destination coordinates.
    estimate_scale : bool
        Whether to estimate scaling factor.

    Returns
    -------
    T : (N + 1, N + 1)
        The homogeneous similarity transformation matrix. The matrix contains
        NaN values only if the problem is not well-conditioned.

    References
    ----------
    .. [1] "Least-squares estimation of transformation parameters between two
            point patterns", Shinji Umeyama, PAMI 1991, :DOI:`10.1109/34.88573`

    r   r   r%   dtyper   Ng      ?)r   asarrayr*   r,   r@   rJ   float64linalgdetr   svdmaxrB   rC   rD   count_nonzeror.   diagvarr-   )srcdstestimate_scalenumdimsrc_meandst_mean
src_demean
dst_demeanAr   r@   USVtolranksscales                      r    _umeyamari      s   0 **S/C
**S/C
))A,C
))A,C xxQxHxxQxH xJxJ 	z!C'A 	bjj)A	yy}}Q!#'

sQwbjj)AiimmAGAq!
 %%'BFF177O
#bhhuo&9&9
9CAG$Dqyvvz	q99==biimmA..2EAdsdDSDjM#'
AAcAgJ
NQ.AdsdDSDjMAcAgJBGGAJ*$3$*jnn!n,0022a!e<eq#tt}xzz'ABBAdsdCiLdsdDSDjMUMHr"   c                       e Zd ZdZed        Zeed               Zd Ze	ed
d              Z
e	d        Ze	deez  fd	       Zy)_GeometricTransformz2Abstract base class for geometric transformations.c                      y)zApply forward transformation.

        Parameters
        ----------
        coords : (N, 2) array_like
            Source coordinates.

        Returns
        -------
        coords : (N, 2) array
            Destination coordinates.

        N selfcoordss     r    __call__z_GeometricTransform.__call__      r"   c                      y)3Return a transform object representing the inverse.Nrm   ro   s    r    inversez_GeometricTransform.inverse  rr   r"   c                 n    t        j                  t        j                   | |      |z
  dz  d            S )a  Determine residuals of transformed destination coordinates.

        For each transformed source coordinate the Euclidean distance to the
        respective destination coordinate is determined.

        Parameters
        ----------
        src : (N, 2) array
            Source coordinates.
        dst : (N, 2) array
            Destination coordinates.

        Returns
        -------
        residuals : (N,) array
            Residual for coordinate.

        r   r   r%   )r   r   r-   ro   rX   rY   s      r    	residualsz_GeometricTransform.residuals  s+    & wwrvvtCy3141=>>r"   Nc                      y)  Identity transform

        Parameters
        ----------
        dimensionality : {None, 2}, optional
            This transform only allows dimensionality of 2, where None
            corresponds to 2. The parameter exists for compatibility with other
            transforms.

        Returns
        -------
        tform : transform
            Transform such that ``np.all(tform(pts) == pts)``.
        Nrm   clsr   s     r    identityz_GeometricTransform.identity-  rr   r"   c                     t        j                  |      }t        j                  |      }| j                  |j                  d         ||fS )z:Create identity transform and make sure points are arrays.r   )r   rO   r~   r*   r}   rX   rY   s      r    _prepare_estimationz'_GeometricTransform._prepare_estimation?  s<     jjojjo||CIIaL)333r"   returnc                 $    t        | ||g|i |S )as  Estimate transform.

        Parameters
        ----------
        src : (N, M) array_like
            Source coordinates.
        dst : (N, M) array_like
            Destination coordinates.
        \*args : sequence
            Any other positional arguments.
        \*\*kwargs : dict
            Any other keyword arguments.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = TransformClass.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")
        _from_estimate)r}   rX   rY   argskwargss        r    from_estimatez!_GeometricTransform.from_estimateF  s    : c3=d=f==r"   N)__name__
__module____qualname____doc__r   rq   propertyrv   ry   classmethodr~   r   r   r   r   rm   r"   r    rk   rk      s    <  B  B?*     4 4 >@P9P > >r"   rk   c                     | j                  ||      \  }}} |j                  ||g|i |}||S t        | j                   d|       S )z8Detached function for from_estimate base implementation.: )r   	_estimater   r   )r}   rX   rY   r   r   tfmsgs          r    r   r   f  sZ    **34LBS
",,sC
1$
1&
1C2L"2cll^2cU3K"LLr"   c                   L    e Zd ZdZd	dddZd Zd Zed	d       Ze	d        Z
y)
_HMatrixTransformz0Transform accepting homogeneous matrix as input.Nr   c                    ||dn|}t        j                  |dz         }nt        j                  |      }| j                  ||       | j	                  |j
                  d   dz
         || _        y )Nr   r   r   )r   r   rO   _check_matrix_check_dimsr*   params)ro   r   r   r   s       r    __init__z_HMatrixTransform.__init__p  sd    >#+AVVAE]FZZ'F6>2a1,-r"   c                     |&||j                   d   dz
  k7  rt        d| d|       |j                   d   }|j                   ||fk7  rt        d      y )Nr   r   zDimensionality z does not match matrix z&Invalid shape of transformation matrix)r*   r   )ro   r   r   ms       r    r   z_HMatrixTransform._check_matrixz  so    %a1!44 %n%55Lh   LLO<<Aq6!EFF "r"   c                 >    |dk(  ry t        dt        |        d      )Nr   
Input for z should result in 2D transformNotImplementedErrortypero   r   s     r    r   z_HMatrixTransform._check_dims  s*    6!d$BC
 	
r"   c                 L    |dn|} | t        j                  |dz               S )r{   r   r   r   )r   r   )r}   r   r   s      r    r~   z_HMatrixTransform.identity  s'       'A^"&&Q-((r"   c                 :    | j                   j                  d   dz
  S )Nr   r   )r   r*   ru   s    r    r   z _HMatrixTransform.dimensionality  s    {{  #a''r"   r   )r   r   r   r   r   r   r   r   r~   r   r   rm   r"   r    r   r   m  sD    :d 	G
 ) )$ ( (r"   r   c                   h     e Zd ZdZdZd Zed        Zd Ze	 fd       Z
d Zd Zed	        Z xZS )
FundamentalMatrixTransforma#  Fundamental matrix transformation.

    The fundamental matrix relates corresponding points between a pair of
    uncalibrated images. The matrix transforms homogeneous image points in one
    image to epipolar lines in the other image.

    The fundamental matrix is only defined for a pair of moving images. In the
    case of pure rotation or planar scenes, the homography describes the
    geometric relation between two images (`ProjectiveTransform`). If the
    intrinsic calibration of the images is known, the essential matrix describes
    the metric relation between the two images (`EssentialMatrixTransform`).

    Notes
    -----
    See [1]_ and [2]_ for details of the estimation procedure.  [2]_ is a good
    place to start.

    References
    ----------
    .. [1] Hartley, Richard, and Andrew Zisserman. Multiple view geometry in
           computer vision. Cambridge university press, 2003.
    .. [2] Zhang, Zhengyou. "Determining the epipolar geometry and its
           uncertainty: A review." International journal of computer vision 27
           (1998): 161-195.
           :DOI:`10.1023/A:1007941100561`
           https://www.microsoft.com/en-us/research/wp-content/uploads/2016/11/RR-2927.pdf

    Parameters
    ----------
    matrix : (3, 3) array_like, optional
        Fundamental matrix.
    dimensionality : int, optional
        Fallback number of dimensions when `matrix` not specified, in which
        case, must equal 2 (the default).

    Attributes
    ----------
    params : (3, 3) array
        Fundamental matrix.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define source and destination points:

    >>> src = np.array([1.839035, 1.924743,
    ...                 0.543582, 0.375221,
    ...                 0.473240, 0.142522,
    ...                 0.964910, 0.598376,
    ...                 0.102388, 0.140092,
    ...                15.994343, 9.622164,
    ...                 0.285901, 0.430055,
    ...                 0.091150, 0.254594]).reshape(-1, 2)
    >>> dst = np.array([1.002114, 1.129644,
    ...                 1.521742, 1.846002,
    ...                 1.084332, 0.275134,
    ...                 0.293328, 0.588992,
    ...                 0.839509, 0.087290,
    ...                 1.779735, 1.116857,
    ...                 0.878616, 0.602447,
    ...                 0.642616, 1.028681]).reshape(-1, 2)

    Estimate the transformation matrix:

    >>> tform = ski.transform.FundamentalMatrixTransform.from_estimate(
    ...      src, dst)
    >>> tform.params
    array([[-0.21785884,  0.41928191, -0.03430748],
           [-0.07179414,  0.04516432,  0.02160726],
           [ 0.24806211, -0.42947814,  0.02210191]])

    Compute the Sampson distance:

    >>> tform.residuals(src, dst)
    array([0.0053886 , 0.00526101, 0.08689701, 0.01850534, 0.09418259,
           0.00185967, 0.06160489, 0.02655136])

    Apply inverse transformation:

    >>> tform.inverse(dst)
    array([[-0.0513591 ,  0.04170974,  0.01213043],
           [-0.21599496,  0.29193419,  0.00978184],
           [-0.0079222 ,  0.03758889, -0.00915389],
           [ 0.14187184, -0.27988959,  0.02476507],
           [ 0.05890075, -0.07354481, -0.00481342],
           [-0.21985267,  0.36717464, -0.01482408],
           [ 0.01339569, -0.03388123,  0.00497605],
           [ 0.03420927, -0.1135812 ,  0.02228236]])

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((8, 2))
    >>> bad_tform = ski.transform.FundamentalMatrixTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...

    r'   c                 F    t        |      | j                  j                  z  S )a  Apply forward transformation.

        Parameters
        ----------
        coords : (N, 2) array_like
            Source coordinates.

        Returns
        -------
        coords : (N, 3) array
            Epipolar lines in the destination image.

        )r?   r   r@   rn   s     r    rq   z#FundamentalMatrixTransform.__call__  s     'v.>>r"   c                 N     t        |       | j                  j                        S )zReturn a transform object representing the inverse.

        See Hartley & Zisserman, Ch. 8: Epipolar Geometry and the Fundamental
        Matrix, for an explanation of why F.T gives the inverse.

        r   )r   r   r@   ru   s    r    rv   z"FundamentalMatrixTransform.inverse-  s     tDz//r"   c                    t        j                  |      }t        j                  |      }|j                  |j                  k7  rt        d      |j                  d   dk  rt        d      t	        || j
                        }t	        || j
                        }t        j                  t        j                  ||z               rQt        j                  dt         j                        | _
        dt        j                  dt         j                        gz  S t        t        ||            }t        t        ||            }|j                  D cg c]  }|j                  D ]  }||z  	  }	}}t        j                  |	d      }
t         j                  j!                  |
      \  }}}|d	d
d
f   j#                  dd      }|||fS c c}}w )a  Setup and solve the homogeneous epipolar constraint matrix::

            dst' * F * src = 0.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        F_normalized : (3, 3) array
            The normalized solution to the homogeneous system. If the system
            is not well-conditioned, this matrix contains NaNs.
        src_matrix : (3, 3) array
            The transformation matrix to obtain the normalized source
            coordinates.
        dst_matrix : (3, 3) array
            The transformation matrix to obtain the normalized destination
            coordinates.

        z%src and dst shapes must be identical.r      z,src.shape[0] must be equal or larger than 8.   r   r   r   r%   r   N)r   rO   r*   r   r5   r0   anyisnanfullr.   r   r?   r:   r@   stackrQ   rS   r   )ro   rX   rY   
src_matrix
dst_matrixsrc_hdst_hd_vs_vcolsra   _rd   F_normalizeds                 r    _setup_constraint_matrixz3FundamentalMatrixTransform._setup_constraint_matrix7  sm   2 jjojjo99		!DEE99Q<!KLL ,C>
+C>
66"((:
234''&"&&1DK/000'(::s(KL'(::s(KL (-wwB%''B3sBBBHHT" ))--"1aQx''1-Z33 Cs   Gc                 $    t         |   ||      S )a  Estimate fundamental matrix using 8-point algorithm.

        The 8-point algorithm requires at least 8 corresponding point pairs.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = FundamentalMatrixTransform.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")

        Raises
        ------
        ValueError
            If `src` has fewer than 8 rows.
        superr   r}   rX   rY   	__class__s      r    r   z(FundamentalMatrixTransform.from_estimatem  s    @ w$S#..r"   c                 B   | j                  ||      \  }}}t        j                  t        j                  ||z   |z               ryt        j                  j                  |      \  }}}d|d<   |t        j                  |      z  |z  }	|j                  |	z  |z  | _        y )NScaling failed for input pointsr   r   	r   r   r   r   rQ   rS   rV   r@   r   )
ro   rX   rY   r   r   r   rb   rc   rd   Fs
             r    r   z$FundamentalMatrixTransform._estimate  s    /3/L/LSRU/V,j*66"((<*4zABC4 ))---1a!
NQ llQ&3r"   c                    t        |      }t        |      }| j                  |j                  z  }| j                  j                  |j                  z  }t        j                  ||j                  z  d      }t        j
                  |      t        j                  |d   dz  |d   dz  z   |d   dz  z   |d   dz  z         z  S )ax  Compute the Sampson distance.

        The Sampson distance is the first approximation to the geometric error.

        Parameters
        ----------
        src : (N, 2) array
            Source coordinates.
        dst : (N, 2) array
            Destination coordinates.

        Returns
        -------
        residuals : (N,) array
            Sampson distance.

        r   r%   r   r   )r?   r   r@   r   r-   absr   )ro   rX   rY   src_homogeneousdst_homogeneousF_srcFt_dst	dst_F_srcs           r    ry   z$FundamentalMatrixTransform.residuals  s    $ 2#61#6o///!2!22FF?UWW41=	vvi 277!HME!HM)F1IN:VAY!^K$
 
 	
r"   c                 *    | j                  ||      du S )a  Estimate fundamental matrix using 8-point algorithm.

        The 8-point algorithm requires at least 8 corresponding point pairs for
        a well-conditioned solution, otherwise the over-determined solution is
        estimated.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.

        Nr   rx   s      r    estimatez#FundamentalMatrixTransform.estimate      * ~~c3'4//r"   )r   r   r   r   r0   rq   r   rv   r   r   r   r   ry   r
   r   __classcell__r   s   @r    r   r     sc    tl G?  0 044l / /B
< 0 0r"   r   c                   f     e Zd ZdZdZdZddddd fd
Zd Ze fd       Z	d Z
ed	        Z xZS )
EssentialMatrixTransformar  Essential matrix transformation.

    The essential matrix relates corresponding points between a pair of
    calibrated images. The matrix transforms normalized, homogeneous image
    points in one image to epipolar lines in the other image.

    The essential matrix is only defined for a pair of moving images capturing a
    non-planar scene. In the case of pure rotation or planar scenes, the
    homography describes the geometric relation between two images
    (`ProjectiveTransform`). If the intrinsic calibration of the images is
    unknown, the fundamental matrix describes the projective relation between
    the two images (`FundamentalMatrixTransform`).

    References
    ----------
    .. [1] Hartley, Richard, and Andrew Zisserman. Multiple view geometry in
           computer vision. Cambridge university press, 2003.

    Parameters
    ----------
    rotation : (3, 3) array_like, optional
        Rotation matrix of the relative camera motion.
    translation : (3, 1) array_like, optional
        Translation vector of the relative camera motion. The vector must
        have unit length.
    matrix : (3, 3) array_like, optional
        Essential matrix.
    dimensionality : int, optional
        Fallback number of dimensions when `matrix` not specified, in which
        case, must equal 2 (the default).

    Attributes
    ----------
    params : (3, 3) array
        Essential matrix.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski
    >>>
    >>> tform = ski.transform.EssentialMatrixTransform(
    ...     rotation=np.eye(3), translation=np.array([0, 0, 1])
    ... )
    >>> tform.params
    array([[ 0., -1.,  0.],
           [ 1.,  0.,  0.],
           [ 0.,  0.,  0.]])
    >>> src = np.array([[ 1.839035, 1.924743],
    ...                 [ 0.543582, 0.375221],
    ...                 [ 0.47324 , 0.142522],
    ...                 [ 0.96491 , 0.598376],
    ...                 [ 0.102388, 0.140092],
    ...                 [15.994343, 9.622164],
    ...                 [ 0.285901, 0.430055],
    ...                 [ 0.09115 , 0.254594]])
    >>> dst = np.array([[1.002114, 1.129644],
    ...                 [1.521742, 1.846002],
    ...                 [1.084332, 0.275134],
    ...                 [0.293328, 0.588992],
    ...                 [0.839509, 0.08729 ],
    ...                 [1.779735, 1.116857],
    ...                 [0.878616, 0.602447],
    ...                 [0.642616, 1.028681]])
    >>> tform = ski.transform.EssentialMatrixTransform.from_estimate(src, dst)
    >>> tform.residuals(src, dst)
    array([0.42455187, 0.01460448, 0.13847034, 0.12140951, 0.27759346,
           0.32453118, 0.00210776, 0.26512283])

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((8, 2))
    >>> bad_tform = ski.transform.EssentialMatrixTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...
    gư>N)rotationtranslationr   r   c                    t        d ||fD              }|dk(  rt        d      |dk(  r|t        d      | j                  ||      }t        |   ||       y )Nc              3   $   K   | ]  }|d u  
 y wr   rm   .0ps     r    	<genexpr>z4EssentialMatrixTransform.__init__.<locals>.<genexpr>=       CaT	C   r   z=Both rotation and translation required when one is specified.r   z@Do not specify rotation or translation when matrix is specified.r   r   )r-   r   
_rt2matrixr   r   )ro   r   r   r   r   	n_rt_noner   s         r    r   z!EssentialMatrixTransform.__init__:  sv     CHk+BCC	>O  !^! +  __X{;F~Fr"   c                 4   t        j                  |      }t        j                  |      }|j                  dk7  rt        d      t	        t         j
                  j                  |      dz
        | j                  kD  rt        d      |j                  dk7  rt        d      t	        t         j
                  j                  |      dz
        | j                  kD  rt        d      |\  }}}t        j                  d| |g|d| g| |dggt        	      }||z  S )
Nr   z Invalid shape of rotation matrixr   z*Rotation matrix must have unit determinantr   z#Invalid shape of translation vectorz(Translation vector must have unit lengthr   rM   )r   rO   r*   r   r   rQ   rR   _rot_det_tolr   norm_trans_len_tolr>   rC   )ro   r   r   t0t1t2t_arrs          r    r   z#EssentialMatrixTransform._rt2matrixK  s    ::h'jj->>V#?@@ryy}}X&*+d.?.??IJJq BCCryy~~k*Q./$2E2EEGHH 
B1rc2,QsBlC5Qxr"   c                 $    t         |   ||      S )a%  Estimate essential matrix using 8-point algorithm.

        The 8-point algorithm requires at least 8 corresponding point pairs for
        a well-conditioned solution, otherwise the over-determined solution is
        estimated.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = EssentialMatrixTransform.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")

        Raises
        ------
        ValueError
            If `src` has fewer than 8 rows.

        r   r   s      r    r   z&EssentialMatrixTransform.from_estimate[  s    F w$S#..r"   c                 t   | j                  ||      \  }}}t        j                  t        j                  ||z   |z               ryt        j                  j                  |      \  }}}|d   |d   z   dz  |d<   |d   |d<   d|d<   |t        j                  |      z  |z  }	|j                  |	z  |z  | _        y )Nr   r   r   g       @r   r   )
ro   rX   rY   E_normalizedr   r   rb   rc   rd   Es
             r    r   z"EssentialMatrixTransform._estimate  s    /3/L/LSRU/V,j*66"((<*4zABC4 ))---1a!qts"!t!!
NQ llQ&3r"   c                 *    | j                  ||      du S )a  Estimate essential matrix using 8-point algorithm.

        The 8-point algorithm requires at least 8 corresponding point pairs for
        a well-conditioned solution, otherwise the over-determined solution is
        estimated.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.

        Nr   rx   s      r    r   z!EssentialMatrixTransform.estimate  r   r"   )r   r   r   r   r   r   r   r   r   r   r   r
   r   r   r   s   @r    r   r     s\    ]@ L N DdG"   "/ "/H" 0 0r"   r   c                        e Zd ZdZdZed        Zd Zed        ZddZ	d Z
ed        Zed fd		       Zdd
Zd Zd Zd Zd Zed        Zed fd	       Zedd       Z xZS )ProjectiveTransforma  Projective transformation.

    Apply a projective transformation (homography) on coordinates.

    For each homogeneous coordinate :math:`\mathbf{x} = [x, y, 1]^T`, its
    target position is calculated by multiplying with the given matrix,
    :math:`H`, to give :math:`H \mathbf{x}`::

      [[a0 a1 a2]
       [b0 b1 b2]
       [c0 c1 1 ]].

    E.g., to rotate by theta degrees clockwise, the matrix should be::

      [[cos(theta) -sin(theta) 0]
       [sin(theta)  cos(theta) 0]
       [0            0         1]]

    or, to translate x by 10 and y by 20::

      [[1 0 10]
       [0 1 20]
       [0 0 1 ]].

    Parameters
    ----------
    matrix : (D+1, D+1) array_like, optional
        Homogeneous transformation matrix.
    dimensionality : int, optional
        Fallback number of dimensions when `matrix` not specified.

    Attributes
    ----------
    params : (D+1, D+1) array
        Homogeneous transformation matrix.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define a transform with an homogeneous transformation matrix:

    >>> tform = ski.transform.ProjectiveTransform(np.diag([2., 3., 1.]))
    >>> tform.params
    array([[2., 0., 0.],
           [0., 3., 0.],
           [0., 0., 1.]])

    You can estimate a transformation to map between source and destination
    points:

    >>> src = np.array([[150, 150],
    ...                 [250, 100],
    ...                 [150, 200]])
    >>> dst = np.array([[200, 200],
    ...                 [300, 150],
    ...                 [150, 400]])
    >>> tform = ski.transform.ProjectiveTransform.from_estimate(src, dst)
    >>> np.allclose(tform.params, [[ -16.56,    5.82,  895.81],
    ...                            [ -10.31,   -8.29, 2075.43],
    ...                            [  -0.05,    0.02,    1.  ]], atol=0.01)
    True

    Apply the transformation to some image data.

    >>> img = ski.data.astronaut()
    >>> warped = ski.transform.warp(img, inverse_map=tform.inverse)

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((3, 2))
    >>> bad_tform = ski.transform.ProjectiveTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...
    r'   c                 F    t        | j                  j                  dz
        S z?Indices into flat ``self.params`` with coefficients to estimater   )ranger   r   ru   s    r    _coeff_indszProjectiveTransform._coeff_inds  s     T[[%%)**r"   c                 >    |dk\  ry t        dt        |        d      )Nr   r   z# should result in transform of >=2Dr   r   s     r    r   zProjectiveTransform._check_dims  s*    6!d$GH
 	
r"   c                 T    t         j                  j                  | j                        S r   )r   rQ   invr   ru   s    r    _inv_matrixzProjectiveTransform._inv_matrix  s    yy}}T[[))r"   c                 T    || j                   S | j                   j                  |      S r   )r   astype)ro   rN   r   s      r    	__array__zProjectiveTransform.__array__  s$    #mt{{J1C1CE1JJr"   c                 .    t        | j                  |      S )zApply forward transformation.

        Parameters
        ----------
        coords : (N, D) array_like
            Source coordinates.

        Returns
        -------
        coords_out : (N, D) array
            Destination coordinates.

        )r:   r   rn   s     r    rq   zProjectiveTransform.__call__  s     "$++v66r"   c                 :     t        |       | j                        S )rt   r   )r   r   ru   s    r    rv   zProjectiveTransform.inverse.  s     tDz!1!122r"   c                 &    t         |   |||      S )a
  Estimate the transformation from a set of corresponding points.

        You can determine the over-, well- and under-determined parameters
        with the total least-squares method.

        Number of source and destination coordinates must match.

        The transformation is defined as::

            X = (a0*x + a1*y + a2) / (c0*x + c1*y + 1)
            Y = (b0*x + b1*y + b2) / (c0*x + c1*y + 1)

        These equations can be transformed to the following form::

            0 = a0*x + a1*y + a2 - c0*x*X - c1*y*X - X
            0 = b0*x + b1*y + b2 - c0*x*Y - c1*y*Y - Y

        which exist for each set of corresponding points, so we have a set of
        N * 2 equations. The coefficients appear linearly so we can write
        A x = 0, where::

            A   = [[x y 1 0 0 0 -x*X -y*X -X]
                   [0 0 0 x y 1 -x*Y -y*Y -Y]
                    ...
                    ...
                  ]
            x.T = [a0 a1 a2 b0 b1 b2 c0 c1 c3]

        In case of total least-squares the solution of this homogeneous system
        of equations is the right singular vector of A which corresponds to the
        smallest singular value normed by the coefficient c3.

        Weights can be applied to each pair of corresponding points to
        indicate, particularly in an overdetermined system, if point pairs have
        higher or lower confidence or uncertainties associated with them. From
        the matrix treatment of least squares problems, these weight values are
        normalized, square-rooted, then built into a diagonal matrix, by which
        A is multiplied.

        In case of the affine transformation the coefficients c0 and c1 are 0.
        Thus the system of equations is::

            A   = [[x y 1 0 0 0 -X]
                   [0 0 0 x y 1 -Y]
                    ...
                    ...
                  ]
            x.T = [a0 a1 a2 b0 b1 b2 c3]

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.
        weights : (N,) array_like, optional
            Relative weight values for each pair of points.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = ProjectiveTransform.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")

        r   )r}   rX   rY   weightsr   s       r    r   z!ProjectiveTransform.from_estimate3  s    V w$S#w77r"   c           
         t        j                  |      }t        j                  |      }|j                  \  }}t        j                  |dz   |dz   ft         j                        }t        |      \  }}t        |      \  }}t        j                  t        j                  ||z               s|| _        yt        j                  ||z  |dz   dz  f      }	t        |      D ]  }
||	|
|z  |
dz   |z  |
|dz   z  |
|dz   z  |z   f<   d|	|
|z  |
dz   |z  |
|dz   z  |z   f<   ||	|
|z  |
dz   |z  | dz
  df<   d|	|
|z  |
dz   |z  df<   |	|
|z  |
dz   |z  | dz
  d fxx   |d d |
|
dz   f    z  cc<    |	d d t        | j                        dgz   f   }	|$t         j                  j                  |	      \  }}}nt        j                  |      }t        j                  t        j                   t        j"                  |t        j$                  |      z        |            }t         j                  j                  ||	z        \  }}}t        j                  |dz   |dz   f      }t        j&                  |d   d      r|| _        y|dd df    |d   z  |j(                  t        | j                        dgz   <   d|||f<   t         j                  j+                  |      |z  |z  }||d   z  }|| _        y )Nr   zScaling generated NaN valuesr   r   r   r   r   z)Right singular vector has 0 final element)r   rO   r*   r   r.   r;   r7   r8   r   zerosr   listr   rQ   rS   rV   tiler   rT   iscloseflatr   )ro   rX   rY   r   r1   r   fail_matrixr   r   ra   ddimr   rd   WHs                  r    r   zProjectiveTransform._estimate  s   jjojjoyy1ggq1ua!enbff56s;
C6s;
Cvvbkk*z"9:;%DK1 HHa!ea!e\*+ !H 	QDPSAdQh$(a'Q$!a%.1:L)LLM?@AdQh$(a'Q!);;<8;AdQh$(a'!a"45/1AdQh$(a'+,dQh$(a'!a12s1ddQh>O;O7P6PP2	Q ad&&'2$../ ?iimmA&GAq!jj)G"&&/(A BAFGAiimmAE*GAq!HHa!eQU^$ ::ai#%DK>122ss7ai0GtD$$%,-!Q$ IIMM*%)J6 	
QvYr"   c                     t        |t              rIt        |       t        |      k(  r| j                  }nt        } ||j                  | j                  z        S t        d      )z)Combine this transformation with another.z2Cannot combine transformations of differing types.)
isinstancer   r   r   r   	TypeError)ro   othertforms      r    __add__zProjectiveTransform.__add__  sQ    e01 DzT%[(+344STTr"   c                     t        | d      syt        j                  | j                  d      }dt	        j
                  |d      z   S )z.common 'paramstr' used by __str__ and __repr__r   z<not yet initialized>z, )	separatorzmatrix=
z    )hasattrr   array2stringr   textwrapindent)ro   npstrings     r    __nice__zProjectiveTransform.__nice__  s9    tX&*??4;;$?X__Xv>>>r"   c           
          dt        |       j                   d| j                          dt        t	        |              dS )z5Add standard repr formatting around a __nice__ string<(z) at >)r   r   r  hexidru   s    r    __repr__zProjectiveTransform.__repr__  s7    4:&&'q(9s2d8}oQOOr"   c                 V    dt        |       j                   d| j                          dS )z4Add standard str formatting around a __nice__ stringr  r  z)>)r   r   r  ru   s    r    __str__zProjectiveTransform.__str__  s)    4:&&'q(9<<r"   c                 :    | j                   j                  d   dz
  S )z)The dimensionality of the transformation.r   r   )r   r*   ru   s    r    r   z"ProjectiveTransform.dimensionality  s     {{  #a''r"   c                 $    t         |   |      S )a  Identity transform

        Parameters
        ----------
        dimensionality : {None, int}, optional
            Dimensionality of identity transform.

        Returns
        -------
        tform : transform
            Transform such that ``np.all(tform(pts) == pts)``.
        r   )r   r~   )r}   r   r   s     r    r~   zProjectiveTransform.identity  s     w~>>r"   c                 ,    | j                  |||      du S )a  Estimate the transformation from a set of corresponding points.

        You can determine the over-, well- and under-determined parameters
        with the total least-squares method.

        Number of source and destination coordinates must match.

        The transformation is defined as::

            X = (a0*x + a1*y + a2) / (c0*x + c1*y + 1)
            Y = (b0*x + b1*y + b2) / (c0*x + c1*y + 1)

        These equations can be transformed to the following form::

            0 = a0*x + a1*y + a2 - c0*x*X - c1*y*X - X
            0 = b0*x + b1*y + b2 - c0*x*Y - c1*y*Y - Y

        which exist for each set of corresponding points, so we have a set of
        N * 2 equations. The coefficients appear linearly so we can write
        A x = 0, where::

            A   = [[x y 1 0 0 0 -x*X -y*X -X]
                   [0 0 0 x y 1 -x*Y -y*Y -Y]
                    ...
                    ...
                  ]
            x.T = [a0 a1 a2 b0 b1 b2 c0 c1 c3]

        In case of total least-squares the solution of this homogeneous system
        of equations is the right singular vector of A which corresponds to the
        smallest singular value normed by the coefficient c3.

        Weights can be applied to each pair of corresponding points to
        indicate, particularly in an overdetermined system, if point pairs have
        higher or lower confidence or uncertainties associated with them. From
        the matrix treatment of least squares problems, these weight values are
        normalized, square-rooted, then built into a diagonal matrix, by which
        A is multiplied.

        In case of the affine transformation the coefficients c0 and c1 are 0.
        Thus the system of equations is::

            A   = [[x y 1 0 0 0 -X]
                   [0 0 0 x y 1 -Y]
                    ...
                    ...
                  ]
            x.T = [a0 a1 a2 b0 b1 b2 c3]

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.
        weights : (N,) array_like, optional
            Relative weight values for each pair of points.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.

        Nr   )ro   rX   rY   r   s       r    r   zProjectiveTransform.estimate  s    D ~~c30D88r"   NNr   )r   r   r   r   r0   r   r   r   r   r   rq   rv   r   r   r   r  r  r   r"  r   r~   r
   r   r   r   s   @r    r   r     s    ]~ G+ +
 * *K7  3 3 J8 J8X7rU?P= ( ( ? ? A9 A9r"   r   c                        e Zd ZdZ	 ddddddd fdZed        Zd Zed        Zed        Z	ed	        Z
ed
        Z xZS )AffineTransforma  Affine transformation.

    Has the following form::

        X = a0 * x + a1 * y + a2
          =   sx * x * [cos(rotation) + tan(shear_y) * sin(rotation)]
            - sy * y * [tan(shear_x) * cos(rotation) + sin(rotation)]
            + translation_x

        Y = b0 * x + b1 * y + b2
          =   sx * x * [sin(rotation) - tan(shear_y) * cos(rotation)]
            - sy * y * [tan(shear_x) * sin(rotation) - cos(rotation)]
            + translation_y

    where ``sx`` and ``sy`` are scale factors in the x and y directions.

    This is equivalent to applying the operations in the following order:

    1. Scale
    2. Shear
    3. Rotate
    4. Translate

    The homogeneous transformation matrix is::

        [[a0  a1  a2]
         [b0  b1  b2]
         [0   0    1]]

    In 2D, the transformation parameters can be given as the homogeneous
    transformation matrix, above, or as the implicit parameters, scale,
    rotation, shear, and translation in x (a2) and y (b2). For 3D and higher,
    only the matrix form is allowed.

    In narrower transforms, such as the Euclidean (only rotation and
    translation) or Similarity (rotation, translation, and a global scale
    factor) transforms, it is possible to specify 3D transforms using implicit
    parameters also.

    Parameters
    ----------
    matrix : (D+1, D+1) array_like, optional
        Homogeneous transformation matrix. If this matrix is provided, it is an
        error to provide any of scale, rotation, shear, or translation.
    scale : {s as float or (sx, sy) as array, list or tuple}, optional
        Scale factor(s). If a single value, it will be assigned to both
        sx and sy. Only available for 2D.

        .. versionadded:: 0.17
           Added support for supplying a single scalar value.
    shear : float or 2-tuple of float, optional
        The x and y shear angles, clockwise, by which these axes are
        rotated around the origin [2].
        If a single value is given, take that to be the x shear angle, with
        the y angle remaining 0. Only available in 2D.
    rotation : float, optional
        Rotation angle, clockwise, as radians. Only available for 2D.
    translation : (tx, ty) as array, list or tuple, optional
        Translation parameters. Only available for 2D.
    dimensionality : int, optional
        Fallback number of dimensions for transform when none of `matrix`,
        `scale`, `rotation`, `shear` or `translation` are specified.  If any of
        `scale`, `rotation`, `shear` or `translation` are specified, must equal
        2 (the default).

    Attributes
    ----------
    params : (D+1, D+1) array
        Homogeneous transformation matrix.

    Raises
    ------
    ValueError
        If both ``matrix`` and any of the other parameters are provided.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define a transform with an homogeneous transformation matrix:

    >>> tform = ski.transform.AffineTransform(np.diag([2., 3., 1.]))
    >>> tform.params
    array([[2., 0., 0.],
           [0., 3., 0.],
           [0., 0., 1.]])

    Define a transform with parameters:

    >>> tform = ski.transform.AffineTransform(scale=4, rotation=0.2)
    >>> np.round(tform.params, 2)
    array([[ 3.92, -0.79,  0.  ],
           [ 0.79,  3.92,  0.  ],
           [ 0.  ,  0.  ,  1.  ]])

    You can estimate a transformation to map between source and destination
    points:

    >>> src = np.array([[150, 150],
    ...                 [250, 100],
    ...                 [150, 200]])
    >>> dst = np.array([[200, 200],
    ...                 [300, 150],
    ...                 [150, 400]])
    >>> tform = ski.transform.AffineTransform.from_estimate(src, dst)
    >>> np.allclose(tform.params, [[   0.5,   -1. ,  275. ],
    ...                            [   1.5,    4. , -625. ],
    ...                            [   0. ,    0. ,    1. ]])
    True

    Apply the transformation to some image data.

    >>> img = ski.data.astronaut()
    >>> warped = ski.transform.warp(img, inverse_map=tform.inverse)

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((3, 2))
    >>> bad_tform = ski.transform.AffineTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...

    References
    ----------
    .. [1] Wikipedia, "Affine transformation",
           https://en.wikipedia.org/wiki/Affine_transformation#Image_transformation
    .. [2] Wikipedia, "Shear mapping",
           https://en.wikipedia.org/wiki/Shear_mapping
    N)rh   shearr   r   r   c                    t        d ||||fD              }|dk7  rP|t        d      ||dkD  rt        d      | j                  ||||      }|j                  d   dk7  rt        d      t        |   ||	       y )
Nc              3   $   K   | ]  }|d u  
 y wr   rm   r   s     r    r   z+AffineTransform.__init__.<locals>.<genexpr>  s     S!t)Sr   r   @Do not specify any implicit parameters when matrix is specified.r   z0Implicit parameters only valid for 2D transformsr   r   z+Implicit parameters must give 2D transformsr   )r-   r   _srst2matrixr*   r   r   )	ro   r   rh   r)  r   r   r   n_srst_noner   s	           r    r   zAffineTransform.__init__  s     SeXuk-RSS!! +  )nq.@ !STT&&uh{KF||A!# !NOO~Fr"   c                 L    t        | j                  | j                  dz   z        S r   )r   r   ru   s    r    r   zAffineTransform._coeff_inds  s%     T((D,?,?!,CDEEr"   c                    |dn|}t        j                  |      r||fn|\  }}|dn|}t        j                  |      st        d      |dn|}t        j                  |      r|dfn|\  }}|dn|}t        j                  |      rt        d      |\  }	}
|t        j                  |      t        j
                  |      t        j                  |      z  z   z  }| t        j
                  |      t        j                  |      z  t        j                  |      z   z  }|t        j                  |      t        j
                  |      t        j                  |      z  z
  z  }| t        j
                  |      t        j                  |      z  t        j                  |      z
  z  }t        j                  |||	g|||
gg dg      S )Nr   r   r   z%rotation must be scalar (2D rotation)r   r   ztranslation must be length 2r   r   r   )r   isscalarr   mathcostansinr>   )ro   rh   r   r)  r   sxsyshear_xshear_ya2b2a0a1b0b1s                  r    r-  zAffineTransform._srst2matrix  s   -U#%;;u#5%5B (1h{{8$DEE])+U);E1: + 3f;;{#;<<B488H%(9DHHX<N(NNOSDHHW%(::TXXh=OOP488H%(9DHHX<N(NNOSDHHW%(::TXXh=OOPxx"b"B|Y?@@r"   c                    | j                   dk7  rDt        j                  t        j                  | j                  dz  d            d | j                    S t        j                  | j                  dz  d      }|d   t        j                  | j                        dz  dz   z  |d<   t        j                  |      d | j                    S )Nr   r   r%   r   )r   r   r   r-   r   r5  r7  r)  )ro   sss     r    rh   zAffineTransform.scale  s    !#77266$++q.q9:;PT=P=PQQVVDKKN+1$**-2Q671wwr{0T0011r"   c                     | j                   dk7  rt        d      t        j                  | j                  d   | j                  d         S )Nr   z<The rotation property is only implemented for 2D transforms.r   r   r2  )r   r   r5  atan2r   ru   s    r    r   zAffineTransform.rotation  sE    !#%N  zz$++d+T[[->??r"   c                     | j                   dk7  rt        d      t        j                  | j                  d    | j                  d         }|| j
                  z
  S )Nr   z9The shear property is only implemented for 2D transforms.)r   r   r1  )r   r   r5  rG  r   r   )ro   betas     r    r)  zAffineTransform.shear	  sV    !#%K  zz4;;t,,dkk$.?@dmm##r"   c                 P    | j                   d| j                  | j                  f   S Nr   r   r   ru   s    r    r   zAffineTransform.translation  '    {{1t222D4G4GGHHr"   r   )r   r   r   r   r   r   r   r-  rh   r   r)  r   r   r   s   @r    r(  r(  /  s    Sn G G2 F FA( 2 2 @ @ $ $ I Ir"   r(  c                   p     e Zd ZdZd Ze fd       Zd Zd Ze	d        Z
ed	d       Zed        Z xZS )
PiecewiseAffineTransformaY	  Piecewise affine transformation.

    Control points are used to define the mapping. The transform is based on
    a Delaunay triangulation of the points to form a mesh. Each triangle is
    used to find a local affine transform.

    Attributes
    ----------
    affines : list of AffineTransform objects
        Affine transformations for each triangle in the mesh.
    inverse_affines : list of AffineTransform objects
        Inverse affine transformations for each triangle in the mesh.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define a transformation by estimation:

    >>> src = [[-12.3705, -10.5075],
    ...        [-10.7865, 15.4305],
    ...        [8.6985, 10.8675],
    ...        [11.4975, -9.5715],
    ...        [7.8435, 7.4835],
    ...        [-5.3325, 6.5025],
    ...        [6.7905, -6.3765],
    ...        [-6.1695, -0.8235]]
    >>> dst = [[0, 0],
    ...        [0, 5800],
    ...        [4900, 5800],
    ...        [4900, 0],
    ...        [4479, 4580],
    ...        [1176, 3660],
    ...        [3754, 790],
    ...        [1024, 1931]]
    >>> tform = ski.transform.PiecewiseAffineTransform.from_estimate(src, dst)

    Calling the transform applies the transformation to the points:

    >>> np.allclose(tform(src), dst)
    True

    You can apply the inverse transform:

    >>> np.allclose(tform.inverse(dst), src)
    True

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = [[1, 1]] * 6 + src[6:]
    >>> bad_tform = ski.transform.PiecewiseAffineTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...
    c                 <    d | _         d | _        d | _        d | _        y r   )_tesselation_inverse_tesselationaffinesinverse_affinesru   s    r    r   z!PiecewiseAffineTransform.__init__b  s!     $(!#r"   c                 $    t         |   ||      S )ac  Estimate the transformation from a set of corresponding points.

        Number of source and destination coordinates must match.

        Parameters
        ----------
        src : (N, D) array_like
            Source coordinates.
        dst : (N, D) array_like
            Destination coordinates.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = PiecewiseAffineTransform.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")

        r   r   s      r    r   z&PiecewiseAffineTransform.from_estimateh  s    8 w$S#..r"   c                    t        j                  |      }t        j                  |      }|j                  \  }}t        j                  |      | _        t        j                  |dz   |dz   ft         j                        }g | _        g }t        | j
                  j                        D ]v  \  }}t        j                  ||d d f   ||d d f         }	|	s0|j                  d| d|	        t        |j                               }	| j                  j                  |	       x t        j                  |      | _        g | _        t        | j                  j                        D ]v  \  }}t        j                  ||d d f   ||d d f         }	|	s0|j                  d| d|	        t        |j                               }	| j                   j                  |	       x |rdj#                  |      S d S )Nr   zFailure at forward simplex r   zFailure at inverse simplex z; )r   rO   r*   r   DelaunayrQ  r   r.   rS  	enumerate	simplicesr(  r   appendr   rR  rT  join)
ro   rX   rY   NDr  messagesitriaffines
             r    r   z"PiecewiseAffineTransform._estimate  s   jjojjoyy1 $,,S1ggq1ua!enbff5  1 1 ; ;< 	(FAs$223sAv;CFLF"=aS6( KL()9)9);<LL'	( %,$4$4S$9!! 9 9 C CD 	0FAs$223sAv;CFLF"=aS6( KL()9)9);<  ''/	0 '/tyy"8D8r"   c                 t   t        j                  |      }t        j                  |t         j                        }| j                  j                  |      }d||dk(  ddf<   t        t        | j                  j                              D ],  }| j                  |   }||k(  } |||ddf         ||ddf<   . |S )a4  Apply forward transformation.

        Coordinates outside of the mesh will be set to `- 1`.

        Parameters
        ----------
        coords : (N, D) array_like
            Source coordinates.

        Returns
        -------
        coords : (N, 2) array
            Transformed coordinates.

        r   N)
r   rO   
empty_likerP   rQ  find_simplexr   rK   rY  rS  )ro   rp   outsimplexindexra  
index_masks          r    rq   z!PiecewiseAffineTransform.__call__  s      F#mmFBJJ/ ##008 !#GrM13t00::;< 	?E\\%(F E)J!'z1}(=!>C
A	? 
r"   c                      t        |              }t        | j                        |_        t        | j                        |_        t        | j                        |_        t        | j
                        |_        |S )rt   )r   r   rR  rQ  rT  rS  )ro   r  s     r    rv   z PiecewiseAffineTransform.inverse  s_     T
!$";";<%)$*;*;%<"T112 $T\\ 2r"   c                      |        S )a  Identity transform

        Parameters
        ----------
        dimensionality : optional
            This transform does not use the `dimensionality` parameter, so the
            value is ignored.  The parameter exists for compatibility with
            other transforms.

        Returns
        -------
        tform : transform
            Transform such that ``np.all(tform(pts) == pts)``.
        rm   r|   s     r    r~   z!PiecewiseAffineTransform.identity  s      ur"   c                 *    | j                  ||      du S )a  Estimate the transformation from a set of corresponding points.

        Number of source and destination coordinates must match.

        Parameters
        ----------
        src : (N, D) array_like
            Source coordinates.
        dst : (N, D) array_like
            Destination coordinates.

        Returns
        -------
        success : bool
            True, if all pieces of the model are successfully estimated.

        Nr   rx   s      r    r   z!PiecewiseAffineTransform.estimate  s    & ~~c3'4//r"   r   )r   r   r   r   r   r   r   r   rq   r   rv   r~   r
   r   r   r   s   @r    rO  rO    sk    HT$ / /:!9F!F    " 0 0r"   rO  c                 v    t         j                  j                  j                  d| |      j	                         S )a  Produce an Euler rotation matrix from the given intrinsic rotation angles
    for the axes x, y and z.

    Parameters
    ----------
    angles : array of float, shape (3,)
        The transformation angles in radians.
    degrees : bool, optional
        If True, then the given angles are assumed to be in degrees. Default is False.

    Returns
    -------
    R : array of float, shape (3, 3)
        The Euler rotation matrix.

    XYZanglesdegrees)r   	transformRotation
from_euler	as_matrixrn  s     r    _euler_rotation_matrixru    s6    " %%00fg 1 ikr"   c                        e Zd ZdZdZ	 ddddd fdZd Zd Zede	e
z  fd	       Zd
 Zed        Zed        Zed        Z xZS )EuclideanTransforma  Euclidean transformation, also known as a rigid transform.

    Has the following form::

        X = a0 * x - b0 * y + a1 =
          = x * cos(rotation) - y * sin(rotation) + a1

        Y = b0 * x + a0 * y + b1 =
          = x * sin(rotation) + y * cos(rotation) + b1

    where the homogeneous transformation matrix is::

        [[a0 -b0  a1]
         [b0  a0  b1]
         [0   0   1 ]]

    The Euclidean transformation is a rigid transformation with rotation and
    translation parameters. The similarity transformation extends the Euclidean
    transformation with a single scaling factor.

    In 2D and 3D, the transformation parameters may be provided either via
    `matrix`, the homogeneous transformation matrix, above, or via the
    implicit parameters `rotation` and/or `translation` (where `a1` is the
    translation along `x`, `b1` along `y`, etc.). Beyond 3D, if the
    transformation is only a translation, you may use the implicit parameter
    `translation`; otherwise, you must use `matrix`.

    The implicit parameters are applied in the following order:

    1. Rotation;
    2. Translation.

    Parameters
    ----------
    matrix : (D+1, D+1) array_like, optional
        Homogeneous transformation matrix.
    rotation : float or sequence of float, optional
        Rotation angle, clockwise, in radians. If given as a vector, it is
        interpreted as Euler rotation angles [1]_. Only 2D (single rotation)
        and 3D (Euler rotations) values are supported. For higher dimensions,
        you must provide or estimate the transformation matrix instead, and
        pass that as `matrix` above.
    translation : (x, y[, z, ...]) sequence of float, length D, optional
        Translation parameters for each axis.
    dimensionality : int, optional
        Fallback number of dimensions for transform when no other parameter
        is specified.  Otherwise ignored, and we infer dimensionality from the
        input parameters.

    Attributes
    ----------
    params : (D+1, D+1) array
        Homogeneous transformation matrix.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define a transform with an homogeneous transformation matrix:

    >>> tform = ski.transform.EuclideanTransform(np.diag([2., 3., 1.]))
    >>> tform.params
    array([[2., 0., 0.],
           [0., 3., 0.],
           [0., 0., 1.]])

    Define a transform with parameters:

    >>> tform = ski.transform.EuclideanTransform(
    ...             rotation=0.2, translation=[1, 2])
    >>> np.round(tform.params, 2)
    array([[ 0.98, -0.2 ,  1.  ],
           [ 0.2 ,  0.98,  2.  ],
           [ 0.  ,  0.  ,  1.  ]])

    You can estimate a transformation to map between source and destination
    points:

    >>> src = np.array([[150, 150],
    ...                 [250, 100],
    ...                 [150, 200]])
    >>> dst = np.array([[200, 200],
    ...                 [300, 150],
    ...                 [150, 400]])
    >>> tform = ski.transform.EuclideanTransform.from_estimate(src, dst)
    >>> np.allclose(tform.params, [[ 0.99, 0.12,  16.77],
    ...                            [-0.12, 0.99, 122.91],
    ...                            [ 0.  , 0.  ,   1.  ]], atol=0.01)
    True

    Apply the transformation to some image data.

    >>> img = ski.data.astronaut()
    >>> warped = ski.transform.warp(img, inverse_map=tform.inverse)

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((3, 2))
    >>> bad_tform = ski.transform.EuclideanTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions

    FN)r   r   r   c                    t        d ||fD              }|dk7  rB|t        d      | j                  ||      \  }}|t        |      | j                  |||      }t        |   ||       y )Nc              3   $   K   | ]  }|d u  
 y wr   rm   r   s     r    r   z.EuclideanTransform.__init__.<locals>.<genexpr>  r   r   r   r,  r   )r-   r   _rt2ndims_msgr   r   r   )	ro   r   r   r   r   r   n_dimschk_msgr   s	           r    r   zEuclideanTransform.__init__  s     CHk+BCC	>! +  #00;GOFG" ))__X{FCF~Fr"   c                     |7t        j                  |      rdn
t        |      }|dvrdnd }|dk(  rd|fS ||fS |&t        j                  |      rdd fS t        |      d fS y)Nr   )r   r   z2``rotations`` must be scalar (3D) or length 3 (3D)r   r&  )r   r4  rK   )ro   r   r   r\  r   s        r    rz  z EuclideanTransform._rt2ndims_msg  s    [[*HA F? E 
 Q1s**As**"[1ANNs;7GNNr"   c                 H   |d|z  }||dk(  rdnt        j                  d      }t        j                  |dz         }|dk(  r=t        j                  |      t        j
                  |      }}|| g||gg|d dd df<   n|dk(  rt        |      |d dd df<   ||d||f<   |S )N)r   r   r   r   r   )r   r  r   r5  r6  r8  ru  )ro   r   r   r{  r   cos_rsin_rs          r    r   zEuclideanTransform._rt2matrix  s    -K"aKqRXXa[H
#Q;88H-txx/A5E$ufou~>F2A2rr6Nq[3H=F2A2rr6N#.qx r"   r   c                     t        | ||      S )a  Estimate the transformation from a set of corresponding points.

        You can determine the over-, well- and under-determined parameters
        with the total least-squares method.

        Number of source and destination coordinates must match.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = EuclideanTransform.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")

        r   r   s      r    r   z EuclideanTransform.from_estimate  s    B c3,,r"   c                     t        ||| j                        | _        t        j                  t        j
                  | j                              rdS d S )Nz Poor conditioning for estimation)ri   _estimate_scaler   r   r   r   rx   s      r    r   zEuclideanTransform._estimate  sG    sC)=)=>
 vvbhht{{+, /	
 	
r"   c                     | j                   dk(  r0t        j                  | j                  d   | j                  d         S | j                   dk(  r| j                  d dd df   S t	        d      )Nr   rF  r1  r   z3Rotation only implemented for 2D and 3D transforms.)r   r5  rG  r   r   ru   s    r    r   zEuclideanTransform.rotation  sl    !#::dkk$/T1BCC  A%;;rr2A2v&&%E r"   c                 P    | j                   d| j                  | j                  f   S rK  rL  ru   s    r    r   zEuclideanTransform.translation  rM  r"   c                 *    | j                  ||      du S )a  Estimate the transformation from a set of corresponding points.

        You can determine the over-, well- and under-determined parameters
        with the total least-squares method.

        Number of source and destination coordinates must match.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.

        Nr   rx   s      r    r   zEuclideanTransform.estimate   s    , ~~c3'4//r"   r   )r   r   r   r   r  r   rz  r   r   r   r   r   r   r   r   r   r
   r   r   r   s   @r    rw  rw    s    }@ O G'+dG   -/?(?  -  -D
 	 	 I I 0 0r"   rw  c                   L     e Zd ZdZdZ	 dddddd fdZd Zed        Z xZ	S )	SimilarityTransforma  Similarity transformation.

    Has the following form in 2D::

        X = a0 * x - b0 * y + a1 =
          = s * x * cos(rotation) - s * y * sin(rotation) + a1

        Y = b0 * x + a0 * y + b1 =
          = s * x * sin(rotation) + s * y * cos(rotation) + b1

    where ``s`` is a scale factor and the homogeneous transformation matrix is::

        [[a0 -b0  a1]
         [b0  a0  b1]
         [0   0   1 ]]

    The similarity transformation extends the Euclidean transformation with a
    single scaling factor in addition to the rotation and translation
    parameters.

    The implicit parameters are applied in the following order:

    1. Scale;
    2. Rotation;
    3. Translation.

    Parameters
    ----------
    matrix : (dim+1, dim+1) array_like, optional
        Homogeneous transformation matrix.
    scale : float, optional
        Scale factor. Implemented only for 2D and 3D.
    rotation : float, optional
        Rotation angle, clockwise, as radians.
        Implemented only for 2D and 3D. For 3D, this is given in ZYX Euler
        angles.
    translation : (dim,) array_like, optional
        x, y[, z] translation parameters. Implemented only for 2D and 3D.
    dimensionality : int, optional
        The dimensionality of the transform, corresponding to ``dim`` above.
        Ignored if `matrix` is not None, and set to ``matrix.shape[0] - 1``.
        Otherwise, must be one of 2 or 3.

    Attributes
    ----------
    params : (dim+1, dim+1) array
        Homogeneous transformation matrix.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define a transform with an homogeneous transformation matrix:

    >>> tform = ski.transform.SimilarityTransform(np.diag([2., 3., 1.]))
    >>> tform.params
    array([[2., 0., 0.],
           [0., 3., 0.],
           [0., 0., 1.]])

    Define a transform with parameters:

    >>> tform = ski.transform.SimilarityTransform(
    ...             rotation=0.2, translation=[1, 2])
    >>> np.round(tform.params, 2)
    array([[ 0.98, -0.2 ,  1.  ],
           [ 0.2 ,  0.98,  2.  ],
           [ 0.  ,  0.  ,  1.  ]])

    You can estimate a transformation to map between source and destination
    points:

    >>> src = np.array([[150, 150],
    ...                 [250, 100],
    ...                 [150, 200]])
    >>> dst = np.array([[200, 200],
    ...                 [300, 150],
    ...                 [150, 400]])
    >>> tform = ski.transform.SimilarityTransform.from_estimate(src, dst)
    >>> np.allclose(tform.params, [[ 1.79, 0.21, -142.86],
    ...                            [-0.21, 1.79,   21.43],
    ...                            [ 0.  , 0.  ,    1.  ]], atol=0.01)
    True

    Apply the transformation to some image data.

    >>> img = ski.data.astronaut()
    >>> warped = ski.transform.warp(img, inverse_map=tform.inverse)

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((3, 2))
    >>> bad_tform = ski.transform.SimilarityTransform.from_estimate(
    ...      bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...
    TN)rh   r   r   r   c                   t        d |||fD              }|dk7  r|t        d      | j                  |||f|       |#t        j                  |      st        |      d }}n| j                  ||      \  }}|t        |      ||n||nd}| j                  |||      }|dvr|d |d |fxx   |z  cc<   t        	| %  ||       y )Nc              3   $   K   | ]  }|d u  
 y wr   rm   r   s     r    r   z/SimilarityTransform.__init__.<locals>.<genexpr>  s     KqdKr   r   r,  r   )Nr   r   )
r-   r   _check_scaler   r4  rK   rz  r   r   r   )
ro   r   rh   r   r   r   
n_srt_noner{  r|  r   s
            r    r   zSimilarityTransform.__init__  s    KUHk,JKK
?! +  eh%<nM U);"%e*d"&"4"4X{"K" )) %  "- $  __X{FCFI%ww'(E1(~Fr"   c                     |dv s|t        j                  |      syt        d |D              rt        j                  dt
        d       yy)zCheck, warn for scalar scaling)Nr   Nc              3   $   K   | ]  }|d u  
 y wr   rm   r   s     r    r   z3SimilarityTransform._check_scale.<locals>.<genexpr>  s     /QqDy/r   a  In the future, it will be a ValueError to pass a scalar `scale` value with a ``dimensionality`` > 2
,and without other implicit parameters to indicate the dimensionality of the transform.
Please indicate dimensionality by passing a vector of suitable length to `scale`.r   )
stacklevel)r   r4  r7   warningswarnFutureWarning)ro   rh   other_paramsr   s       r    r  z SimilarityTransform._check_scale  sH    Y&%-r{{5?Q/,//MM1 	 0r"   c                 D   | j                   dk(  r<t        j                  t        j                  j	                  | j
                              S | j                   dk(  r<t        j                  t        j                  j	                  | j
                              S t        d      )Nr   r   z(Scale is only implemented for 2D and 3D.)r   r   r   rQ   rR   r   cbrtr   ru   s    r    rh   zSimilarityTransform.scale  sl     !#77299==566  A%77299==566%&PQQr"   r   )
r   r   r   r   r  r   r  r   rh   r   r   s   @r    r  r    sL    rj O #G #GJ  R Rr"   r  c                   ~     e Zd ZdZddddZed fd	       ZddZd Zedd       Z	e
d	        Zedd
       Z xZS )PolynomialTransformaz  2D polynomial transformation.

    Has the following form::

        X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i ))
        Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i ))

    Parameters
    ----------
    params : (2, N) array_like, optional
        Polynomial coefficients where `N * 2 = (order + 1) * (order + 2)`. So,
        a_ji is defined in `params[0, :]` and b_ji in `params[1, :]`.
    dimensionality : int, optional
        Must have value 2 (the default) for polynomial transforms.

    Attributes
    ----------
    params : (2, N) array
        Polynomial coefficients where `N * 2 = (order + 1) * (order + 2)`. So,
        a_ji is defined in `params[0, :]` and b_ji in `params[1, :]`.

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    Define a transformation by estimation:

    >>> src = [[-12.3705, -10.5075],
    ...        [-10.7865, 15.4305],
    ...        [8.6985, 10.8675],
    ...        [11.4975, -9.5715],
    ...        [7.8435, 7.4835],
    ...        [-5.3325, 6.5025],
    ...        [6.7905, -6.3765],
    ...        [-6.1695, -0.8235]]
    >>> dst = [[0, 0],
    ...        [0, 5800],
    ...        [4900, 5800],
    ...        [4900, 0],
    ...        [4479, 4580],
    ...        [1176, 3660],
    ...        [3754, 790],
    ...        [1024, 1931]]
    >>> tform = ski.transform.PolynomialTransform.from_estimate(src, dst)

    Calling the transform applies the transformation to the points:

    >>> pts = tform(src)
    >>> np.allclose(pts, [[   7.54,   12.27],
    ...                   [   2.98, 5796.95],
    ...                   [4870.44, 5766.59],
    ...                   [4889.72,   -6.72],
    ...                   [4515.62, 4617.5 ],
    ...                   [1183.25, 3694.  ],
    ...                   [3767.57,  800.53],
    ...                   [ 998.02, 1881.97]], atol=0.01)
    True
    Nr   c                    |d}n|dk7  rt        d      t        j                  |g dg dgn|      | _        | j                  j                  dk(  s| j                  j                  d   dk7  rt        d      y )Nr   z2Polynomial transforms are only implemented for 2D.)r   r   r   r3  rm   r   z.Transformation parameters must be shape (2, N))r   r   r>   r   r*   r   )ro   r   r   s      r    r   zPolynomialTransform.__init__	  s|    !Nq %D  hh	95VT;;"dkk&7&7&:a&?MNN '@r"   c                 (    t         |   ||||      S )a
  Estimate the transformation from a set of corresponding points.

        You can determine the over-, well- and under-determined parameters
        with the total least-squares method.

        Number of source and destination coordinates must match.

        The transformation is defined as::

            X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i ))
            Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i ))

        These equations can be transformed to the following form::

            0 = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) - X
            0 = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) - Y

        which exist for each set of corresponding points, so we have a set of
        N * 2 equations. The coefficients appear linearly so we can write
        A x = 0, where::

            A   = [[1 x y x**2 x*y y**2 ... 0 ...             0 -X]
                   [0 ...                 0 1 x y x**2 x*y y**2 -Y]
                    ...
                    ...
                  ]
            x.T = [a00 a10 a11 a20 a21 a22 ... ann
                   b00 b10 b11 b20 b21 b22 ... bnn c3]

        In case of total least-squares the solution of this homogeneous system
        of equations is the right singular vector of A which corresponds to the
        smallest singular value normed by the coefficient c3.

        Weights can be applied to each pair of corresponding points to
        indicate, particularly in an overdetermined system, if point pairs have
        higher or lower confidence or uncertainties associated with them. From
        the matrix treatment of least squares problems, these weight values are
        normalized, square-rooted, then built into a diagonal matrix, by which
        A is multiplied.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.
        order : int, optional
            Polynomial order (number of coefficients is order + 1).
        weights : (N,) array_like, optional
            Relative weight values for each pair of points.

        Returns
        -------
        tf : Self or ``FailedEstimation``
            An instance of the transformation if the estimation succeeded.
            Otherwise, we return a special ``FailedEstimation`` object to
            signal a failed estimation. Testing the truth value of the failed
            estimation object will return ``False``. E.g.

            .. code-block:: python

                tf = PolynomialTransform.from_estimate(...)
                if not tf:
                    raise RuntimeError(f"Failed estimation: {tf}")

        r   )r}   rX   rY   orderr   r   s        r    r   z!PolynomialTransform.from_estimate	  s    H w$S#ug>>r"   c           
         t        j                  |      }t        j                  |      }|d d df   }|d d df   }|d d df   }|d d df   }|j                  d   }	t        |      }|dz   |dz   z  }
t        j                  |	dz  |
dz   f      }d}t        |dz         D ]J  }t        |dz         D ]7  }|||z
  z  ||z  z  |d |	|f<   |||z
  z  ||z  z  ||	d ||
dz  z   f<   |dz  }9 L ||d |	df<   |||	d df<   |$t         j                  j                  |      \  }}}nt        j                  |      }t        j                  t        j                  t        j                  |t        j                  |      z        d            }t         j                  j                  ||z        \  }}}|dd df    |d   z  }|j                  d|
dz  f      | _        y )Nr   r   r   r   r  )r   rO   r*   r	   r  r   rQ   rS   rV   r  r   rT   r   r   )ro   rX   rY   r  r   xsysxdydrowsura   pidxjr_  r   rd   r
  r   s                      r    r   zPolynomialTransform._estimatea	  s   jjojjoAYAYAYAYyy| E"QY519%HHdQhA&'uqy! 	A1q5\ !#AQ!6%4%+*,Q-"a%*?$%Q&'		 %4%)$%) ?iimmA&GAq!jj)G"&&/(A BAFGAiimmAE*GAq! BG*qy(nnaa[1r"   c           	      H   t        j                  |      }|dddf   }|dddf   }t        | j                  j	                               }t        dt        j                  ddd|z
  z  z
        z   dz        }t        j                  |j                        }d}t        |dz         D ]x  }t        |dz         D ]e  }	|dddfxx   | j                  d|f   |||	z
  z  z  ||	z  z  z  cc<   |dddfxx   | j                  d|f   |||	z
  z  z  ||	z  z  z  cc<   |dz  }g z |S )zApply forward transformation.

        Parameters
        ----------
        coords : (N, 2) array_like
            source coordinates

        Returns
        -------
        coords : (N, 2) array
            Transformed coordinates.

        Nr   r   	   r   r   )r   rO   rK   r   ravelr   r5  r   r  r*   r   )
ro   rp   xyr  r  rY   r  r  r_  s
             r    rq   zPolynomialTransform.__call__	  s,    F#1a4L1a4L!!#$R$))AQUO449:hhv||$uqy! 	A1q5\ AqD	T[[D1A!a%L@1a4GG	AqD	T[[D1A!a%L@1a4GG			 
r"   c                      | d|      S )r{   NrL  rm   r|   s     r    r~   zPolynomialTransform.identity	  s      $~>>r"   c                     t        d      )NzThere is no explicit way to do the inverse polynomial transformation. Instead, estimate the inverse transformation parameters by exchanging source and destination coordinates,then apply the forward transformation.)r   ru   s    r    rv   zPolynomialTransform.inverse	  s    !5
 	
r"   c                 .    | j                  ||||      du S )a  Estimate the transformation from a set of corresponding points.

        You can determine the over-, well- and under-determined parameters
        with the total least-squares method.

        Number of source and destination coordinates must match.

        The transformation is defined as::

            X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i ))
            Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i ))

        These equations can be transformed to the following form::

            0 = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) - X
            0 = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) - Y

        which exist for each set of corresponding points, so we have a set of
        N * 2 equations. The coefficients appear linearly so we can write
        A x = 0, where::

            A   = [[1 x y x**2 x*y y**2 ... 0 ...             0 -X]
                   [0 ...                 0 1 x y x**2 x*y y**2 -Y]
                    ...
                    ...
                  ]
            x.T = [a00 a10 a11 a20 a21 a22 ... ann
                   b00 b10 b11 b20 b21 b22 ... bnn c3]

        In case of total least-squares the solution of this homogeneous system
        of equations is the right singular vector of A which corresponds to the
        smallest singular value normed by the coefficient c3.

        Weights can be applied to each pair of corresponding points to
        indicate, particularly in an overdetermined system, if point pairs have
        higher or lower confidence or uncertainties associated with them. From
        the matrix treatment of least squares problems, these weight values are
        normalized, square-rooted, then built into a diagonal matrix, by which
        A is multiplied.

        Parameters
        ----------
        src : (N, 2) array_like
            Source coordinates.
        dst : (N, 2) array_like
            Destination coordinates.
        order : int, optional
            Polynomial order (number of coefficients is order + 1).
        weights : (N,) array_like, optional
            Relative weight values for each pair of points.

        Returns
        -------
        success : bool
            True, if model estimation succeeds.

        Nr   )ro   rX   rY   r  r   s        r    r   zPolynomialTransform.estimate	  s    v ~~c3w74??r"   r   )r   N)r   r   r   r   r   r   r   r   rq   r~   r   rv   r
   r   r   r   s   @r    r  r    sw    :x	Od 	O C? C?J'R> ? ?" 
 
 :@ :@r"   r  )	euclidean
similarityra  zpiecewise-affine
projectivefundamental	essential
polynomialc                     | j                         } | t        vrt        d|  d      t        |    j                  ||g|i |S )a  Estimate 2D geometric transformation parameters.

    You can determine the over-, well- and under-determined parameters
    with the total least-squares method.

    Number of source and destination coordinates must match.

    Parameters
    ----------
    ttype : {'euclidean', similarity', 'affine', 'piecewise-affine',              'projective', 'polynomial'}
        Type of transform.
    kwargs : array_like or int
        Function parameters (src, dst, n, angle)::

            NAME / TTYPE        FUNCTION PARAMETERS
            'euclidean'         `src, `dst`
            'similarity'        `src, `dst`
            'affine'            `src, `dst`
            'piecewise-affine'  `src, `dst`
            'projective'        `src, `dst`
            'polynomial'        `src, `dst`, `order` (polynomial order,
                                                      default order is 2)

        Also see examples below.

    Returns
    -------
    tf : :class:`_GeometricTransform` or ``FailedEstimation``
        An instance of the requested transformation if the estimation
        Otherwise, we return a special ``FailedEstimation`` object to signal a
        failed estimation. Testing the truth value of the failed estimation
        object will return ``False``. E.g.

        .. code-block:: python

            tf = estimate_transform(...)
            if not tf:
                raise RuntimeError(f"Failed estimation: {tf}")

    Examples
    --------
    >>> import numpy as np
    >>> import skimage as ski

    >>> # estimate transformation parameters
    >>> src = np.array([0, 0, 10, 10]).reshape((2, 2))
    >>> dst = np.array([12, 14, 1, -20]).reshape((2, 2))

    >>> tform = ski.transform.estimate_transform('similarity', src, dst)

    >>> np.allclose(tform.inverse(tform(src)), src)
    True

    >>> # warp image using the estimated transformation
    >>> image = ski.data.camera()

    >>> ski.transform.warp(image, inverse_map=tform.inverse) # doctest: +SKIP

    >>> # create transformation with explicit parameters
    >>> tform2 = ski.transform.SimilarityTransform(scale=1.1, rotation=1,
    ...     translation=(10, 20))

    >>> # unite transformations, applied in order from left to right
    >>> tform3 = tform + tform2
    >>> np.allclose(tform3(src), tform2(tform(src)))
    True

    The estimation can fail - for example, if all the input or output points
    are the same.  If this happens, you will get a transform that is not
    "truthy" - meaning that ``bool(tform)`` is ``False``:

    >>> # A successfully estimated model is truthy (applying ``bool()``
    >>> # gives ``True``):
    >>> if tform:
    ...     print("Estimation succeeded.")
    Estimation succeeded.
    >>> # Not so for a degenerate transform with identical points.
    >>> bad_src = np.ones((2, 2))
    >>> bad_tform = ski.transform.estimate_transform('similarity',
    ...                                              bad_src, dst)
    >>> if not bad_tform:
    ...     print("Estimation failed.")
    Estimation failed.

    Trying to use this failed estimation transform result will give a suitable
    error:

    >>> bad_tform.params  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
      ...
    FailedEstimationAccessError: No attribute "params" for failed estimation ...

    zthe transformation type 'z' is not implemented)r+   
TRANSFORMSr   r   )ttyperX   rY   r   r   s        r    estimate_transformr  
  sP    ~ KKMEJ5eW<QRSSe**3EdEfEEr"   c                 $     t        |      |       S )a"  Apply 2D matrix transform.

    Parameters
    ----------
    coords : (N, 2) array_like
        x, y coordinates to transform
    matrix : (3, 3) array_like
        Homogeneous transformation matrix.

    Returns
    -------
    coords : (N, 2) array
        Transformed coordinates.

    )r   )rp   r   s     r    matrix_transformr  t
  s      'v&v..r"   )r'   )F)*r   r5  r  abcr   r   typingr   r  numpyr   scipyr   _shared.utilsr	   r
   r   r   r   _shared.compatr   r!   r5   r;   r:   r?   ri   rk   r   r   r   r   r   r(  rO  ru  rw  r  r  r  r  r  rm   r"   r    <module>r     s]      #      /HV60D:(M`c># c>LM4(+ 4(nm0!2 m0`	R09 R0jC9+ C9L !cI) cI  !cILe02 e0P,A0, A0H !uR, uR  !uRpl@- l@`	 $%0%-)%	
cFL/r"   