
    3jB                         S r SSKrSSKJr  SSKJrJrJr  SSKrSSKJ	r	  SSK
Jr  SSKJrJrJr  SSKJrJrJrJrJrJrJr  S	/r " S
 S	\	R2                  5      rg)z!Module containing RANSAC modules.    N)partial)CallableOptionalTuple)nn)KORNIA_CHECK_SHAPE)find_essentialfind_fundamentalsampson_epipolar_distance)find_homography_dltfind_homography_dlt_iteratedfind_homography_lines_dlt"find_homography_lines_dlt_iterated#line_segment_transfer_error_one_wayoneway_transfer_errorsample_is_valid_for_homographyRANSACc                     ^  \ rS rSrSr         S%S\S\S\S\S\S	\S
\S\S\	\   SS4U 4S jjjr
 S&S\S\S\S\S\	\R                     S\R                  4S jjr\S\S\S\S\S\4
S j5       rS\R                  S\R                  S\R                  4S jrS\R                  S\R                  S\R                  S\S\\R                  \R                  \\4   4
S jrS\R                  S\R                  S\\R                  \R                  4   4S jrS\R                  S\R                  4S jrS\R                  S\R                  S\R                  S\R                  4S  jrS&S\R                  S\R                  S!\	\R                     SS4S" jjr S&S\R                  S\R                  S!\	\R                     S\\R                  \R                  4   4S# jjrS$rU =r$ )'r   *   a  Module for robust geometry estimation with RANSAC. https://en.wikipedia.org/wiki/Random_sample_consensus.

Args:
    model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt",
        "homography_from_linesegments".
    inliers_threshold: threshold for the correspondence to be an inlier.
    batch_size: number of generated samples at once.
    max_iterations: maximum batches to generate. Actual number of models to try is ``batch_size * max_iterations``.
    confidence: desired confidence of the result, used for the early stopping.
    max_local_iterations: number of local optimization (polishing) iterations.

N
model_typeinl_th
batch_sizemax_iter
confidencemax_lo_iters
score_typeprosac_samplingseedreturnc
                 (  > [         T
U ]  5         / SQU l        SS/U l        Xpl        X l        X@l        X0l        Xl        XPl	        X`l
        Xl        Xl        Xl        U   U   U   US:X  a0  [        U l        [        U l        ["        U l        SU l        SU l        gUS:X  a0  [*        U l        [,        U l        [.        U l        SU l        SU l        gUS:X  a0  [0        U l        [2        U l        SU l        [2        U l        SU l        gUS	:X  a8  [0        U l        [5        [2        S
S9U l        SU l        [2        U l        SU l        gUS:X  a0  [0        U l        [6        U l        SU l        [2        U l        SU l        g[9        U SU R                   35      e)a(  Initialize the RANSAC estimator.

Args:
    model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt", "essential",
        "homography_from_linesegments".
    inl_th: threshold for the correspondence to be an inlier. Internally is squared.
    batch_size: number of generated samples at once.
    max_iter: maximum batches to generate. Actual number of models to try is ``batch_size * max_iter``.
    confidence: desired confidence of the result, used for the early stopping.
    max_lo_iters: number of local optimization (polishing) iterations.
    score_type: scoring method to use: "ransac" or "msac".
    prosac_sampling: whether to use PROSAC sampling instead of random sampling.
    seed: optional random seed for reproducible results. If None, uses global random state.

)
homographyfundamentalfundamental_7pthomography_from_linesegments	essentialmsacransacr!      r$   r"      r#   7POINT)method   r%      z is unknown. Try one of N)super__init__supported_modelssupported_scoresr   r   r   r   r   r   r   r   r   r   error_fnr   minimal_solverr   polisher_solverminimal_sample_sizepolisher_sample_sizer   r   r   r   r
   r   r	   NotImplementedError)selfr   r   r   r   r   r   r   r   r   	__class__s             P/home/wildlama/miniconda3/lib/python3.13/site-packages/kornia/geometry/ransac.pyr/   RANSAC.__init__8   sy   6 	!
 "( 2$ $$$($.	%1DM"5D#?D '(D$()D%99?DM";D#ED '(D$()D%=(5DM"2D'(D$#3D ()D%,,5DM")*:8"LD'(D$#3D ()D%;&5DM"0D'(D$#3D ()D%%4LTMbMbLc&dee    sample_sizepop_size	iterationdevicec                 0   Uc  [         R                  " S5      nU R                  bH  [         R                  " US9nUR	                  U R                  U-   5        [         R
                  " X2XVS9nO[         R
                  " X2US9nUR                  USS9u  pU	$ )a  Minimal sampler, but unlike traditional RANSAC we sample in batches.

Yields the benefit of the parallel processing, esp. on GPU.

Args:
    sample_size: number of samples to draw from the population.
    pop_size: size of the population to sample from.
    batch_size: number of sample sets to generate.
    iteration: current iteration number (used for PROSAC sampling).
    device: device to place the samples on.

Returns:
    Tensor of sampled indices with shape :math:`(batch_size, sample_size)`.

cpu)r@   )r@   	generator   )kdim)torchr@   r   	Generatormanual_seedrandtopk)
r8   r=   r>   r   r?   r@   rC   rJ   _outs
             r:   sampleRANSAC.sample   s    $ >\\%(F99 v6I!!$))i"78::j6WD::j6BD[a0
r<   n_inlnum_tcconfc                 (   SnX::  a  gX:X  a  gX::  a  gUS:  a  gUS::  a  gSn[        U5       H  nXPU-
  X-
  -  -  nM     [        [        R                  " SU-
  5      [	        U* [        R                  " [        USU-
  5      5      5      -  5      $ )aT  Update max_iter to stop iterations earlier https://en.wikipedia.org/wiki/Random_sample_consensus.

Args:
    n_inl: number of inliers.
    num_tc: total number of correspondences.
    sample_size: size of minimal sample.
    conf: desired confidence level.

Returns:
    Maximum number of samples needed to achieve the desired confidence.

g&.>rD   g      ?        )rangeintmathlogminmax)rP   rQ   r=   rR   epsprob_inlieris          r:   max_samples_by_confRANSAC.max_samples_by_conf   s      ?3;3; {#AAI&*55K $ 488C$J'#sdDHHScKFW=X4Y*ZZ[[r<   kp1kp2c                     UR                   SS u  p4U R                  X[        R                  " X4UR                  UR
                  S95      nU$ )zEstimate models from minimal samples.

Args:
    kp1: source keypoints with shape :math:`(batch_size, sample_size, 2)`.
    kp2: target keypoints with shape :math:`(batch_size, sample_size, 2)`.

Returns:
    Estimated models tensor.

N   dtyper@   )shaper3   rG   onesre   r@   )r8   r`   ra   r   r=   Hs         r:   estimate_model_from_minsample$RANSAC.estimate_model_from_minsample   sH     #&))BQ-
%**ZTWT]T]fifpfp*qrr<   modelsc           	      &   [        UR                  5      S:X  a  US   n[        UR                  5      S:X  a  US   nUR                  S   nU R                  S:X  a8  U R                  UR	                  USSS5      UR	                  USSS5      U5      nO5U R                  UR	                  USS5      UR	                  USS5      U5      nXd:*  nUR                  SS9nU R                  S:X  a.  UR                  S   UR                  S	US
9R                  SS9-
  n	O+U R                  S:X  a  Un	O[        SU R                   35      eU	R                  5       n
X   R                  5       nX   R                  5       nX:   R                  5       nXz   nXX4$ )aE  Verify models by computing inliers and selecting the best model.

Args:
    kp1: source keypoints.
    kp2: target keypoints.
    models: candidate models to verify.
    inl_th: inlier threshold.

Returns:
    Tuple containing:
        - Best model
        - Inlier mask for the best model
        - Score of the best model

rc   Nr   r$   rD   rF   r&   rT   )rY   rZ   r'   zUnsupported score type: )lenrf   r   r2   expandsumr   clamp
ValueErrorargmaxitemclone)r8   r`   ra   rk   r   r   errorsinl_maskscore_ransacscorebest_model_idxbest_model_scorenum_inliers
model_bestinliers_bests                  r:   verifyRANSAC.verify   s   $ syy>Qd)Csyy>Qd)C\\!_
??<<]]3::j"a#CSZZPZ\^`acdEegmnF]]3::j"a#@#**ZY[]^B_aghF#|||*??f$LLOfllsl&G&K&KPQ&K&RRE__( E77HIJJ 0557"2779+113
/)9FFr<   c                 N    U R                   S:X  a  [        X5      nX   X#   4$ X4$ )zRemove degenerate samples based on model-specific constraints.

Args:
    kp1: source keypoints.
    kp2: target keypoints.

Returns:
    Tuple of filtered keypoints (kp1, kp2).

r!   )r   r   )r8   r`   ra   masks       r:   remove_bad_samplesRANSAC.remove_bad_samples  s0     ??l*1#;D9ci''xr<   c                 j    [         R                  " U5      R                  SS9R                  SS9nX   $ )zRemove degenerate models based on simple heuristics.

Args:
    models: candidate models to filter.

Returns:
    Filtered models tensor.

rm   rn   )rG   isfiniteall)r8   rk   r   s      r:   remove_bad_modelsRANSAC.remove_bad_models  s6     ~~f%))b)155"5=|r<   inliersc                     X   S   nX#   S   nUR                  S5      nU R                  XE[        R                  " SXdR                  UR
                  S95      nU$ )zPolish the model using inliers through local optimization.

Args:
    kp1: source keypoints.
    kp2: target keypoints.
    inliers: boolean mask indicating inlier correspondences.

Returns:
    Polished model tensor.

NrD   rd   )sizer4   rG   rg   re   r@   )r8   r`   ra   r   kp1_inlkp2_inlnum_inlmodels           r:   polish_modelRANSAC.polish_model$  s]     ,t$,t$,,q/$$ejjG==QXQ_Q_`
 r<   weightsc                 r   U R                   S;   a  [        USS/5        [        USS/5        UR                  S   UR                  S   :X  a  UR                  S   U R                  :  a2  [	        SU R                   SUR                   SUR                   35      eU R                   S:X  a  [        U/ S	Q5        [        U/ S	Q5        UR                  S   UR                  S   :X  a  UR                  S   U R                  :  a2  [	        SU R                   S
UR                   SUR                   35      egg)a  Validate input tensors for shape and size requirements.

Args:
    kp1: source keypoints.
    kp2: target keypoints.
    weights: optional correspondence weights (not used currently).

Raises:
    ValueError: if input shapes are invalid or insufficient correspondences.

)r!   r"   N2r   zMkp1 and kp2 should be                                  equal shape at least [z+, 2],                                  got z, r$   )r   r   r   z., 2, 2],                                  got N)r   r   rf   r5   rs   )r8   r`   ra   r   s       r:   validate_inputsRANSAC.validate_inputs9  s8    ??;;sS#J/sS#J/IIaLCIIaL0ciilTE]E]6] 1122]^a^g^g]hhjknktktjuw  ??<<sO4sO4IIaLCIIaL0ciilTE]E]6] 1122`adajaj`k l		{$  7^ =r<   c           	      `   U R                  XU5        [        U R                  5      n[        U5      n[        R
                  " SSUR                  UR                  S9n[        R
                  " USUR                  [        R                  S9n[        U R                  5       GH  nU R                  U R                  XPR                  XR                  5      n	X   n
X)   nU R                  X5      u  p[        U
5      S:X  a  Ma  U R                  X5      nU R                  S;   a  UR!                  SSS5      nU R#                  U5      nUb  [        U5      S:X  a  M  U R%                  XXR&                  S-  5      u  pnnX:  d  M  UU R(                  :  d  M  [        U R*                  5       H  nU R-                  XU5      nUb  [        U5      S:X  a  M)  U R%                  XUU R&                  S-  5      u  nnnnUU:  a7  UU R(                  :  a'  UR/                  5       S   nUR/                  5       nUnM    O   UR/                  5       nUR/                  5       nUnU R1                  [3        U5      XPR                  U R4                  5      nUS-   U R                  -  U:  d  GM    Xg4$    Xg4$ )	a  Call main forward method to execute the RANSAC algorithm.

Args:
    kp1: source image keypoints :math:`(N, 2)`.
    kp2: distance image keypoints :math:`(N, 2)`.
    weights: optional correspondences weights. Not used now.

Returns:
    - Estimated model, shape of :math:`(1, 3, 3)`.
    - The inlier/outlier mask, shape of :math:`(1, N)`, where N is number of input correspondences.

   rd   rD   )r@   re   r   )r%   r#   rm   rc   )r   floatr5   ro   rG   zerosre   r@   boolrU   r   rN   r   r   ri   r   reshaper   r   r   r6   r   r   rv   r^   rV   r   )r8   r`   ra   r   best_score_totalrQ   best_model_totalinliers_best_totalr]   idxskp1_sampledkp2_sampledrk   r   r   model_scorer}   rL   model_lo
inliers_loscore_lonum_inliers_lonew_max_iters                          r:   forwardRANSAC.forwardW  ss    	Sw/"'(@(@"A#h ;;q!399SZZP+0;;vq[`[e[e+ft}}%A;;t77RSU_U_`D)K)K'+'>'>{'X$K;1$77QF"BBAq1++F3FCK1$47;{{3VU`U`bcUc7d4EK.K4C\C\4\t001A#007CH (c(mq.@ >Bkk#T\^b^i^ikl^l>m;Az8^ ;.^tG`G`5` ( 0 3","2"2"4&. 2 $);;= %,]]_"#.   $77()63K3KT__ 
 ET__,<33[ &Z  33r<   )r   r   r2   r   r   r   r5   r3   r   r6   r4   r   r   r   r0   r1   )	r!   g       @i   
   gGz?r-   r'   FN)N)__name__
__module____qualname____firstlineno____doc__strr   rV   r   r   r/   rG   r@   TensorrN   staticmethodr^   ri   r   r   r   r   r   r   r   __static_attributes____classcell__)r9   s   @r:   r   r   *   s    ' " %"RfRf Rf 	Rf
 Rf Rf Rf Rf Rf smRf 
Rf Rfj rv*-;>KNX`afamamXn	: \3 \ \# \U \WZ \ \B ELL UZUaUa (G<<(G&+ll(G<ALL(GRW(G	u||U\\5%7	8(GTell  %PUP\P\^c^j^jPjJk $   5<< %,, [`[g[g *5<< ell XV[VbVbMc os > W[A4<<A4&+llA4=Eell=SA4	u||U\\)	*A4 A4r<   )r   rW   	functoolsr   typingr   r   r   rG   r   kornia.core.checkr   kornia.geometry.epipolarr	   r
   r   kornia.geometry.homographyr   r   r   r   r   r   r   __all__Moduler    r<   r:   <module>r      sO   $ (   , ,   0 ` `   *n4RYY n4r<   