
    9i~                         S SK r S SKJr  S SKrS SKJr  S SKJrJ	r	  \R                  " S5      rS rS r " S S	5      r " S
 S\5      r " S S\5      r " S S\5      rS rSSS\R&                  S SSS4S jrg)    N)warn)inv)optimizespatial   c                 h    U R                   S:w  d  U R                  S   U:w  a  [        SU S35      eg )N   r   zInput data must have shape (N, z).ndimshape
ValueError)datadims     S/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/skimage/measure/fit.py_check_data_dimr      s6    yyA~A#-:3%rBCC .    c                 `    U R                   S:  d  U R                  S   S:  a  [        S5      eg )Nr	   r   zInput data must be at least 2D.r
   )r   s    r   _check_data_atleast_2Dr      s-    yy1}

1):;; *r   c                       \ rS rSrS rSrg)	BaseModel   c                     S U l         g Nparams)selfs    r   __init__BaseModel.__init__   s	    r   r   N)__name__
__module____qualname____firstlineno__r   __static_attributes__ r   r   r   r      s    r   r   c                   F    \ rS rSrSrS rS
S jrSS jrS
S jrS
S jr	S	r
g)LineModelND   a	  Total least squares estimator for N-dimensional lines.

In contrast to ordinary least squares line estimation, this estimator
minimizes the orthogonal distances of points to the estimated line.

Lines are defined by a point (origin) and a unit vector (direction)
according to the following vector equation::

    X = origin + lambda * direction

Attributes
----------
params : tuple
    Line model parameters in the following order `origin`, `direction`.

Examples
--------
>>> x = np.linspace(1, 2, 25)
>>> y = 1.5 * x + 3
>>> lm = LineModelND()
>>> lm.estimate(np.stack([x, y], axis=-1))
True
>>> tuple(np.round(lm.params, 5))
(array([1.5 , 5.25]), array([0.5547 , 0.83205]))
>>> res = lm.residuals(np.stack([x, y], axis=-1))
>>> np.abs(np.round(res, 9))
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0.])
>>> np.round(lm.predict_y(x[:5]), 3)
array([4.5  , 4.562, 4.625, 4.688, 4.75 ])
>>> np.round(lm.predict_x(y[:5]), 3)
array([1.   , 1.042, 1.083, 1.125, 1.167])

c                 V   [        U5        UR                  SS9nX-
  nUR                  S   S:X  a5  US   US   -
  n[        R                  R                  U5      nUS:w  a  X4-  nO;UR                  S   S:  a'  [        R                  R                  USS9u    pVUS   nOgX#4U l        g)a5  Estimate line model from data.

This minimizes the sum of shortest (orthogonal) distances
from the given data points to the estimated line.

Parameters
----------
data : (N, dim) array
    N points in a space of dimensionality dim >= 2.

Returns
-------
success : bool
    True, if model estimation succeeds.
r   axisr	   r   F)full_matricesT)r   meanr   nplinalgnormsvdr   )r   r   origin	directionr/   _vs          r   estimateLineModelND.estimate?   s      	t$"}::a=AQ$q')I99>>),Dqy!	ZZ]QiimmDm>GAq!I)r   Nc                 "   [        U5        Uc$  U R                  c  [        S5      eU R                  n[        U5      S:w  a  [        S5      eUu  p4X-
  X-
  U-  S[        R
                  4   U-  -
  n[        R                  R                  USS9$ )a  Determine residuals of data to model.

For each point, the shortest (orthogonal) distance to the line is
returned. It is obtained by projecting the data onto the line.

Parameters
----------
data : (N, dim) array
    N points in a space of dimension dim.
params : (2,) array, optional
    Optional custom parameter set in the form (`origin`, `direction`).

Returns
-------
residuals : (N,) array
    Residual for each data point.
Parameters cannot be Noner	   !Parameters are defined by 2 sets..r   r)   )r   r   r   lenr-   newaxisr.   r/   )r   r   r   r1   r2   ress         r   	residualsLineModelND.residualsd   s    $ 	t$>{{" !<==[[Fv;!@AA"}$-9!<O!
!  yy~~c~**r   c                    Uc$  U R                   c  [        S5      eU R                   n[        U5      S:w  a  [        S5      eUu  pEXR   S:X  a  [        SU 35      eXU   -
  XR   -  nXFS[        R                  4   U-  -   nU$ )a  Predict intersection of the estimated line model with a hyperplane
orthogonal to a given axis.

Parameters
----------
x : (n, 1) array
    Coordinates along an axis.
axis : int
    Axis orthogonal to the hyperplane intersecting the line.
params : (2,) array, optional
    Optional custom parameter set in the form (`origin`, `direction`).

Returns
-------
data : (n, m) array
    Predicted coordinates.

Raises
------
ValueError
    If the line is parallel to the given axis.
r8   r	   r9   r   zLine parallel to axis .)r   r   r:   r-   r;   )r   xr*   r   r1   r2   lr   s           r   predictLineModelND.predict   s    . >{{" !<==[[Fv;!@AA"?a5dV<==0#rzz/*Y66r   c                 6    U R                  USUS9SS2S4   nU$ )a;  Predict x-coordinates for 2D lines using the estimated model.

Alias for::

    predict(y, axis=1)[:, 0]

Parameters
----------
y : array
    y-coordinates.
params : (2,) array, optional
    Optional custom parameter set in the form (`origin`, `direction`).

Returns
-------
x : array
    Predicted x-coordinates.

r   r*   r   Nr   rB   )r   yr   r@   s       r   	predict_xLineModelND.predict_x   &    ( LL6L21a48r   c                 6    U R                  USUS9SS2S4   nU$ )a;  Predict y-coordinates for 2D lines using the estimated model.

Alias for::

    predict(x, axis=0)[:, 1]

Parameters
----------
x : array
    x-coordinates.
params : (2,) array, optional
    Optional custom parameter set in the form (`origin`, `direction`).

Returns
-------
y : array
    Predicted y-coordinates.

r   rE   Nr   rF   )r   r@   r   rG   s       r   	predict_yLineModelND.predict_y   rJ   r   r   r   )r   N)r   r    r!   r"   __doc__r5   r=   rB   rH   rL   r#   r$   r   r   r&   r&      s$    !F#J+@&P.r   r&   c                   .    \ rS rSrSrS rS rSS jrSrg)	CircleModel   a  Total least squares estimator for 2D circles.

The functional model of the circle is::

    r**2 = (x - xc)**2 + (y - yc)**2

This estimator minimizes the squared distances from all points to the
circle::

    min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc)**2))**2) }

A minimum number of 3 points is required to solve for the parameters.

Attributes
----------
params : tuple
    Circle model parameters in the following order `xc`, `yc`, `r`.

Notes
-----
The estimation is carried out using a 2D version of the spherical
estimation given in [1]_.

References
----------
.. [1] Jekel, Charles F. Obtaining non-linear orthotropic material models
       for pvc-coated polyester via inverse bubble inflation.
       Thesis (MEng), Stellenbosch University, 2016. Appendix A, pp. 83-87.
       https://hdl.handle.net/10019.1/98627

Examples
--------
>>> t = np.linspace(0, 2 * np.pi, 25)
>>> xy = CircleModel().predict_xy(t, params=(2, 3, 4))
>>> model = CircleModel()
>>> model.estimate(xy)
True
>>> tuple(np.round(model.params, 5))
(2.0, 3.0, 4.0)
>>> res = model.residuals(xy)
>>> np.abs(np.round(res, 9))
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0.])
c                 (   [        USS9  [        R                  " UR                  [        R                  5      nUR                  USS9nUR                  SS9nX-
  nUR                  5       nU[        R                  " U5      R                  :  a  [        S[        SS9  gX-  n[        R                  " US-  [        R                  " UR                  S   S	4US
9S	S9n[        R                  " US-  S	S9n[        R                   R#                  XVSS9u  pxpU	S:w  a  [        S5        gUSS n
[$        R&                  " X5      n[        R(                  " [        R                  " US-  5      5      nX-  n
X-  nX-  n
[+        U
5      U4-   U l        g)zEstimate circle model from data using total least squares.

Parameters
----------
data : (N, 2) array
    N points with ``(x, y)`` coordinates, respectively.

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

r	   r   Fcopyr   r)   zUStandard deviation of data is too small to estimate circle with meaningful precision.category
stacklevelr   dtypeN)rcond   z6Input does not contain enough significant data points.T)r   r-   promote_typesrZ   float32astyper,   stdfinfotinyr   RuntimeWarningappendonesr   sumr.   lstsqr   minkowski_distancesqrttupler   )r   r   
float_typer1   scaleAfCr3   rankcenter	distancesrs                r   r5   CircleModel.estimate	  sk    	!$ %%djj"**=
{{:E{2 "}
288J',,,4'	 
 IIdQhA(:* MTUVFF47#		D9d19IJ1Q..v<	GGBGGIqL)* 		
Fmqd*r   c                     [        USS9  U R                  u  p#nUSS2S4   nUSS2S4   nU[        R                  " XR-
  S-  Xc-
  S-  -   5      -
  $ )a  Determine residuals of data to model.

For each point the shortest distance to the circle is returned.

Parameters
----------
data : (N, 2) array
    N points with ``(x, y)`` coordinates, respectively.

Returns
-------
residuals : (N,) array
    Residual for each data point.

r	   rS   Nr   r   )r   r   r-   ri   )r   r   xcycrs   r@   rG   s          r   r=   CircleModel.residualsC  sZ    " 	!$KK	AJAJ277AFq=AFq=8999r   Nc                     Uc  U R                   nUu  p4nX5[        R                  " U5      -  -   nXE[        R                  " U5      -  -   n[        R                  " US   US   4UR
                  S9$ )aa  Predict x- and y-coordinates using the estimated model.

Parameters
----------
t : array
    Angles in circle in radians. Angles start to count from positive
    x-axis to positive y-axis in a right-handed system.
params : (3,) array, optional
    Optional custom parameter set.

Returns
-------
xy : (..., 2) array
    Predicted x- and y-coordinates.

.Nr)   )r   r-   cossinconcatenater   )r   tr   rv   rw   rs   r@   rG   s           r   
predict_xyCircleModel.predict_xy]  se    " >[[F	RVVAYRVVAY~~q|Qy\:HHr   r   r   	r   r    r!   r"   rN   r5   r=   r   r#   r$   r   r   rP   rP      s    +Z8t:4Ir   rP   c                   .    \ rS rSrSrS rS rSS jrSrg)	EllipseModelix  a  Total least squares estimator for 2D ellipses.

The functional model of the ellipse is::

    xt = xc + a*cos(theta)*cos(t) - b*sin(theta)*sin(t)
    yt = yc + a*sin(theta)*cos(t) + b*cos(theta)*sin(t)
    d = sqrt((x - xt)**2 + (y - yt)**2)

where ``(xt, yt)`` is the closest point on the ellipse to ``(x, y)``. Thus
d is the shortest distance from the point to the ellipse.

The estimator is based on a least squares minimization. The optimal
solution is computed directly, no iterations are required. This leads
to a simple, stable and robust fitting method.

The ``params`` attribute contains the parameters in the following order::

    xc, yc, a, b, theta

Attributes
----------
params : tuple
    Ellipse model parameters in the following order `xc`, `yc`, `a`, `b`,
    `theta`.

Examples
--------

>>> xy = EllipseModel().predict_xy(np.linspace(0, 2 * np.pi, 25),
...                                params=(10, 15, 8, 4, np.deg2rad(30)))
>>> ellipse = EllipseModel()
>>> ellipse.estimate(xy)
True
>>> np.round(ellipse.params, 2)
array([10.  , 15.  ,  8.  ,  4.  ,  0.52])
>>> np.round(abs(ellipse.residuals(xy)), 5)
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
       0., 0., 0., 0., 0., 0., 0., 0.])
c                    [        USS9  [        U5      S:  a  [        S[        SS9  g[        R
                  " UR                  [        R                  5      nUR                  USS9nUR                  SS	9nX-
  nUR                  5       nU[        R                  " U5      R                  :  a  [        S
[        SS9  gX-  nUSS2S4   nUSS2S4   n[        R                  " US-  XV-  US-  /5      R                  n[        R                  " XV[        R                  " U5      /5      R                  nUR                  U-  n	UR                  U-  n
UR                  U-  n[        R                   " / SQ/ SQ/ SQ/5      n [#        U5      X[#        U5      -  U
R                  -  -
  -  n[        R$                  R)                  U5      u  pS[        R*                  " USSS24   USSS24   5      -  [        R,                  " USSS24   S5      -
  nUSS2US:  4   nSUR.                  ;   d  [        UR1                  5       5      S:w  a  gUR1                  5       u  nnn[#        U5      * U
R                  -  U-  nUR1                  5       u  nnnUS-  nUS-  nUS-  nUU-  UU-  -
  US-  UU-  -
  -  nUU-  UU-  -
  US-  UU-  -
  -  nUUS-  -  UUS-  -  -   UUS-  -  -   SU-  U-  U-  -
  UU-  U-  -
  n[        R2                  " UU-
  S-  SUS-  -  -   5      nUS-  UU-  -
  UUU-   -
  -  nUS-  UU-  -
  U* UU-   -
  -  n[        R2                  " SU-  U-  5      n[        R2                  " SU-  U-  5      n S[        R4                  " SU-  UU-
  -  5      -  n!UU:  a  U!S[        R6                  -  -  n!UU :  a  U Un nU![        R6                  S-  -  n!U![        R6                  -  n![        R8                  " UUUU U!/5      R:                  n"U"SS=== U-  sss& U"SS=== U-  sss& [=        S U" 5       5      U l        g! [        R$                  R&                   a     gf = f)a  Estimate ellipse model from data using total least squares.

Parameters
----------
data : (N, 2) array
    N points with ``(x, y)`` coordinates, respectively.

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


References
----------
.. [1] Halir, R.; Flusser, J. "Numerically stable direct least squares
       fitting of ellipses". In Proc. 6th International Conference in
       Central Europe on Computer Graphics and Visualization.
       WSCG (Vol. 98, pp. 125-132).

r	   rS      z3Need at least 5 data points to estimate an ellipse.rV   FrT   r   r)   zVStandard deviation of data is too small to estimate ellipse with meaningful precision.Nr   )        r          @)r   g      r   )r   r   r      r\   r   g      ?c              3   8   #    U  H  n[        U5      v   M     g 7fr   )float).0ps     r   	<genexpr>(EllipseModel.estimate.<locals>.<genexpr>$  s     5fE!HHfs   T) r   r:   r   rc   r-   r]   rZ   r^   r_   r,   r`   ra   rb   vstackT	ones_likearrayr   r.   LinAlgErroreigmultiplypowerr   ravelri   arctanpi
nan_to_numrealrj   r   )#r   r   rk   r1   rl   r@   rG   D1D2S1S2S3C1Meig_valseig_vecsconda1abca2drn   gx0y0	numeratortermdenominator1denominator2widthheightphir   s#                                      r   r5   EllipseModel.estimate  sf   0 	!$t9q=E'
  %%djj"**=
{{:E{2 "}
288J',,,5'	 AJAJ YY1aeQT*+--YYbll1o./11 TTBYTTBYTTBY XX(8/JK	B2SWrtt 334A  YY]]1- 2;;x1~x1~>>QTNAB
 
 a$(m$=C
Oq0((*1a "gX_r!((*1a 	
S	S	S !ea!em3Q/!ea!em3Q/ 1Hq1a4x'!ad(2QUQY]BQUQYN	wwA!|a!Q$h./1q1uQ81q1u$!a%9I45Y56 BIIsQw1q5122q53;C
 6>"E6E25519Cruu Bvs;<AAr
e
r
f
5f55{ yy$$ 		s   )Q Q0/Q0c                 *  ^^^^^^ [        USS9  U R                  u  mmmmn[        R                  " U5      m[        R                  " U5      mUSS2S4   nUSS2S4   nUR
                  S   nUUUUUU4S jn[        R                  " U4[        R                  S9n[        R                  " UT-
  UT-
  5      U-
  n[        U5       HE  n	X9   n
XI   n[        R                  " XhU	   X4S9u  p[        R                  " U" XU5      5      Xy'   MG     U$ )	a  Determine residuals of data to model.

For each point the shortest distance to the ellipse is returned.

Parameters
----------
data : (N, 2) array
    N points with ``(x, y)`` coordinates, respectively.

Returns
-------
residuals : (N,) array
    Residual for each data point.

r	   rS   Nr   r   c                   > [         R                  " [        R                  " U 5      5      n[         R                  " [        R                  " U 5      5      nTTT	-  U-  -   TT
-  U-  -
  nTTT
-  U-  -   TT	-  U-  -   nX-
  S-  X&-
  S-  -   $ )Nr	   )mathr{   r-   squeezer|   )r~   xiyictstxtytr   r   cthetasthetarv   rw   s          r   fun#EllipseModel.residuals.<locals>.funE  s    "**Q-(B"**Q-(Ba&j2o%F
R7Ba&j2o%F
R7BG>RWN22r   rY   )args)r   r   r   r{   r|   r   r-   emptyfloat64arctan2ranger   leastsqri   )r   r   thetar@   rG   Nr   r=   t0ir   r   r~   r3   r   r   r   r   rv   rw   s                 @@@@@@r   r=   EllipseModel.residuals(  s    " 	!$"kkB1e%%AJAJJJqM	3 	3$ HHaT4	 ZZBB'%/ qABB##CAbX>DA773qb>2IL  r   Nc                 r   Uc  U R                   nUu  p4pVn[        R                  " U5      n[        R                  " U5      n	[        R                  " U5      n
[        R                  " U5      nX5U
-  U-  -   Xk-  U	-  -
  nXEU-  U-  -   Xj-  U	-  -   n[        R
                  " US   US   4UR                  S9$ )aa  Predict x- and y-coordinates using the estimated model.

Parameters
----------
t : array
    Angles in circle in radians. Angles start to count from positive
    x-axis to positive y-axis in a right-handed system.
params : (5,) array, optional
    Optional custom parameter set.

Returns
-------
xy : (..., 2) array
    Predicted x- and y-coordinates.

rz   r)   )r   r-   r{   r|   r   r}   r   )r   r~   r   rv   rw   r   r   r   r   r   r   r   r@   rG   s                 r   r   EllipseModel.predict_xyf  s    $ >[[F$eVVAYVVAY%%Vb 1:?2Vb 1:?2~~q|Qy\:HHr   r   r   r   r$   r   r   r   r   x  s    &PEN<|Ir   r   c                 b   US:X  a  gU S:X  a  [         R                  $ X-  nSU-
  nSXB-  -
  n[         R                  " U[        S[        -
  S9n[         R                  " U[        S[        -
  S9n[         R                  " [         R
                  " U5      [         R
                  " U5      -  5      $ )a  Determine number trials such that at least one outlier-free subset is
sampled for the given inlier/outlier ratio.

Parameters
----------
n_inliers : int
    Number of inliers in the data.
n_samples : int
    Total number of samples in the data.
min_samples : int
    Minimum number of samples chosen randomly from original data.
probability : float
    Probability (confidence) that one outlier-free sample is generated.

Returns
-------
trials : int
    Number of trials.
r   r   )a_mina_max)r-   infclip_EPSILONceillog)	n_inliers	n_samplesmin_samplesprobabilityinlier_rationomdenoms          r   _dynamic_max_trialsr     s    ( aA~vv(L
k/C))E ''#XQ\
:CGGEX>E77266#;.//r   d   c           	         Sn[         R                  n/ nUSLnUSLn[         R                  R                  U
5      n
[	        U [
        [        45      (       d  U 4n [        U S   5      nSUs=:  a  U::  d  O  [        SU S35      eUS:  a  [        S5      eUS:  a  [        S5      eSU	s=::  a  S::  d  O  [        S5      eUb*  [        U5      U:w  a  [        S	[        U5       S
U S35      eUb  UOU
R                  UUSS9nU" 5       nSnUU:  Ga  US-  nU  Vs/ s H  nUU   PM
     nnU
R                  UUSS9nU(       a  U" U6 (       d  ME  UR                  " U6 nUb	  U(       d  M`  U(       a  U" U/UQ76 (       d  Mw  [         R                  " UR                  " U 6 5      nUU:  nUR                  U5      n[         R                  " U5      nUU:  d  UU:X  a.  UU:  a(  UnUnUn[        U[!        UUX)5      5      nX:  d  X::  a  O	UU:  a  GM  [#        U5      (       aH  U  Vs/ s H  nUU   PM
     nnUR                  " U6   U(       a  U" U/UQ76 (       d  [%        S5        UU4$ SnSn[%        S5        UU4$ s  snf s  snf )a  Fit a model to data with the RANSAC (random sample consensus) algorithm.

RANSAC is an iterative algorithm for the robust estimation of parameters
from a subset of inliers from the complete data set. Each iteration
performs the following tasks:

1. Select `min_samples` random samples from the original data and check
   whether the set of data is valid (see `is_data_valid`).
2. Estimate a model to the random subset
   (`model_cls.estimate(*data[random_subset]`) and check whether the
   estimated model is valid (see `is_model_valid`).
3. Classify all data as inliers or outliers by calculating the residuals
   to the estimated model (`model_cls.residuals(*data)`) - all data samples
   with residuals smaller than the `residual_threshold` are considered as
   inliers.
4. Save estimated model as best model if number of inlier samples is
   maximal. In case the current estimated model has the same number of
   inliers, it is only considered as the best model if it has less sum of
   residuals.

These steps are performed either a maximum number of times or until one of
the special stop criteria are met. The final model is estimated using all
inlier samples of the previously determined best model.

Parameters
----------
data : [list, tuple of] (N, ...) array
    Data set to which the model is fitted, where N is the number of data
    points and the remaining dimension are depending on model requirements.
    If the model class requires multiple input data arrays (e.g. source and
    destination coordinates of  ``skimage.transform.AffineTransform``),
    they can be optionally passed as tuple or list. Note, that in this case
    the functions ``estimate(*data)``, ``residuals(*data)``,
    ``is_model_valid(model, *random_data)`` and
    ``is_data_valid(*random_data)`` must all take each data array as
    separate arguments.
model_class : object
    Object with the following object methods:

     * ``success = estimate(*data)``
     * ``residuals(*data)``

    where `success` indicates whether the model estimation succeeded
    (`True` or `None` for success, `False` for failure).
min_samples : int in range (0, N)
    The minimum number of data points to fit a model to.
residual_threshold : float larger than 0
    Maximum distance for a data point to be classified as an inlier.
is_data_valid : function, optional
    This function is called with the randomly selected data before the
    model is fitted to it: `is_data_valid(*random_data)`.
is_model_valid : function, optional
    This function is called with the estimated model and the randomly
    selected data: `is_model_valid(model, *random_data)`, .
max_trials : int, optional
    Maximum number of iterations for random sample selection.
stop_sample_num : int, optional
    Stop iteration if at least this number of inliers are found.
stop_residuals_sum : float, optional
    Stop iteration if sum of residuals is less than or equal to this
    threshold.
stop_probability : float in range [0, 1], optional
    RANSAC iteration stops if at least one outlier-free set of the
    training data is sampled with ``probability >= stop_probability``,
    depending on the current best model's inlier ratio and the number
    of trials. This requires to generate at least N samples (trials):

        N >= log(1 - probability) / log(1 - e**m)

    where the probability (confidence) is typically set to a high value
    such as 0.99, e is the current fraction of inliers w.r.t. the
    total number of samples, and m is the min_samples value.
rng : {`numpy.random.Generator`, int}, optional
    Pseudo-random number generator.
    By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`).
    If `rng` is an int, it is used to seed the generator.
initial_inliers : array-like of bool, shape (N,), optional
    Initial samples selection for model estimation


Returns
-------
model : object
    Best model with largest consensus set.
inliers : (N,) array
    Boolean mask of inliers classified as ``True``.

References
----------
.. [1] "RANSAC", Wikipedia, https://en.wikipedia.org/wiki/RANSAC

Examples
--------

Generate ellipse data without tilt and add noise:

>>> t = np.linspace(0, 2 * np.pi, 50)
>>> xc, yc = 20, 30
>>> a, b = 5, 10
>>> x = xc + a * np.cos(t)
>>> y = yc + b * np.sin(t)
>>> data = np.column_stack([x, y])
>>> rng = np.random.default_rng(203560)  # do not copy this value
>>> data += rng.normal(size=data.shape)

Add some faulty data:

>>> data[0] = (100, 100)
>>> data[1] = (110, 120)
>>> data[2] = (120, 130)
>>> data[3] = (140, 130)

Estimate ellipse model using all available data:

>>> model = EllipseModel()
>>> model.estimate(data)
True
>>> np.round(model.params)  # doctest: +SKIP
array([ 72.,  75.,  77.,  14.,   1.])

Estimate ellipse model using RANSAC:

>>> ransac_model, inliers = ransac(data, EllipseModel, 20, 3, max_trials=50)
>>> abs(np.round(ransac_model.params))  # doctest: +SKIP
array([20., 30., 10.,  6.,  2.])
>>> inliers  # doctest: +SKIP
array([False, False, False, False,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True], dtype=bool)
>>> sum(inliers) > 40
True

RANSAC can be used to robustly estimate a geometric
transformation. In this section, we also show how to use a
proportion of the total samples, rather than an absolute number.

>>> from skimage.transform import SimilarityTransform
>>> rng = np.random.default_rng()
>>> src = 100 * rng.random((50, 2))
>>> model0 = SimilarityTransform(scale=0.5, rotation=1,
...                              translation=(10, 20))
>>> dst = model0(src)
>>> dst[0] = (10000, 10000)
>>> dst[1] = (-100, 100)
>>> dst[2] = (50, 50)
>>> ratio = 0.5  # use half of the samples
>>> min_samples = int(ratio * len(src))
>>> model, inliers = ransac(
...     (src, dst),
...     SimilarityTransform,
...     min_samples,
...     10,
...     initial_inliers=np.ones(len(src), dtype=bool),
... )  # doctest: +SKIP
>>> inliers  # doctest: +SKIP
array([False, False, False,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True])

r   Nz#`min_samples` must be in range (0, ]z.`residual_threshold` must be greater than zeroz&`max_trials` must be greater than zeror   z*`stop_probability` must be in range [0, 1]z4RANSAC received a vector of initial inliers (length z+) that didn't match the number of samples (z). The vector of initial inliers should have the same length as the number of samples and contain only True (this sample is an initial inlier) and False (this one isn't) values.F)replacez8Estimated model is not valid. Try increasing max_trials.z"No inliers found. Model not fitted)r-   r   randomdefault_rng
isinstancerj   listr:   r   choicer5   absr=   dotcount_nonzerominr   anyr   )r   model_classr   residual_thresholdis_data_validis_model_valid
max_trialsstop_sample_numstop_residuals_sumstop_probabilityrnginitial_inliersbest_inlier_numbest_inlier_residuals_sumbest_inliersvalidate_modelvalidate_datanum_samplesspl_idxsmodel
num_trialsr   samplessuccessr=   inliersresiduals_suminliers_countdata_inlierss                                r   ransacr	    s   j O "L#4/N!-M
))


$C dUDM**wd1g,K*{*>{m1MNNAIJJA~ABB!&Q&EFF"s?';{'JB?#$ %#} %
 	
 & 	ZZ[%Z@  MEJ
z
!a
 )--11X;- ::k;:F !8..'*w ."A"A"AFF5??D12	00!i0 ((1 O+ 0!$== ,O(5%"L##[+J  2,Bi z
!n <156A,6%."F"F"FKL ,	 12,} .j 7s   J+J)r   warningsr   numpyr-   numpy.linalgr   scipyr   r   spacingr   r   r   r   r&   rP   r   r   r   r	  r$   r   r   <module>r     s        # ::a=D
<
 
}) }@ZI) ZIzMI9 MI` 0P FFfr   