
    3jGg                     R   % S SK r S SKJrJrJrJr  S SKrS SKJs  J	r
  S SKJr  S SKJr  S SKJr  S SKJrJrJrJrJr  S SKJrJrJr  SS	KJr  SS
KJr  SSKJr  \ R>                  " S\ R@                  -  S-  5      r!\"\#S'   S\RH                  S\RH                  S\%S\RH                  4S jr&S\RH                  S\\%   S\RH                  4S jr' " S S\RP                  5      r) " S S\5      r*S\*4S jr+ " S S\RP                  5      r,SSS\ RZ                  " S 5      S!S".r.\*\#S#'   g)$    N)ListOptionalTupleUnion)nn)	TypedDict)KORNIA_CHECK_SHAPE)AdaptiveQuadInterp3dConvQuadInterp3dIterativeQuadInterp3dNonMaximaSuppression2dnms3d_minmax)ScalePyramidpyrdownresize   )laf_from_center_scale_ori)PassLAF)BlobHessian      _MAX_ABS_SIN_12
max_coordssigmas
num_levelsreturnc           	          U R                   S   nUSS2S4   R                  USS5      nU[        R                  " SU SS2SS2SS24   [	        U5      -  5      -  U SS2SS2SS24'   U $ )aP  Auxiliary function for ScaleSpaceDetector.

Converts scale level index from the subpix module to the actual
scale, using the sigmas from the ScalePyramid output.

Args:
    max_coords: torch.Tensor [BxNx3].
    sigmas: torch.Tensor [BxD], D >= 1
    num_levels: number of levels in the scale index.

Returns:
    torch.Tensor [BxNx3].

r   Nr          @)shapeviewtorchpowfloat)r   r   r   B
base_sigmas        ]/home/wildlama/miniconda3/lib/python3.13/site-packages/kornia/feature/scale_space_detector.py_scale_index_to_scaler'   0   su     	A1""1a+J&3
1a198MPUV`Pa8a)bbJq!QqSy    maskoctave_shapec                 Z    USS n[         R                  " XSSS9nUR                  S5      $ )z2Downsample a mask based on the given octave shape.NbilinearF)modealign_cornersr   )Finterpolate	unsqueeze)r)   r*   
mask_shapemask_octaves       r&   _create_octave_maskr5   E   s2    bc"J--zQVWK  ##r(   c                     ^  \ rS rSrSr          SS\S\S\\R                     S\\R                     S\\R                     S	\\R                     S
\\R                     S\
S\
S\\
\\   4   SS4U 4S jjjrS\4S jrS\R"                  S\R"                  S\S\\R"                     S\R"                  S\S\
S\S\\R"                  \R"                  4   4S jr SS\R"                  S\S\\R"                     S\\R"                  \R"                  4   4S jjrSS\R"                  S\\R"                     S\\R"                  \R"                  4   4S jjrSrU =r$ ) ScaleSpaceDetectorL   a  nn.Module for differentiable local feature detection.

As close as possible to classical local feature detectors
like Harris, Hessian-Affine or SIFT (DoG).

It has 5 modules inside: scale pyramid generator, response ("cornerness") function,
sub-pixel localization, affine shape estimator and patch orientation estimator.
Each of those modules could be replaced with a learned custom one, as long as
they respect output shape.

Args:
    num_features: Number of features to detect. In order to keep everything batchable,
      output would always have num_features output, even for completely homogeneous images.
    mr_size: multiplier for local feature scale compared to the detection scale.
      6.0 is matching OpenCV 12.0 convention for SIFT.
    scale_pyr_module: generates scale pyramid. See :class:`~kornia.geometry.ScalePyramid` for details.
      Default: ScalePyramid(3, 1.6, 15).
    resp_module: calculates ``'cornerness'`` of the pixel.
    subpix_module: performs non-maximum suppression and refines keypoint location to sub-pixel /
      sub-scale accuracy. See :class:`~kornia.geometry.subpix.ConvQuadInterp3d` for details.
    ori_module: for local feature orientation estimation. Default:class:`~kornia.feature.PassLAF`,
       which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.
    aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,
        which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.
    minima_are_also_good: if True, then both response function minima and maxima are detected.
        Useful for symmetric response functions like DoG or Hessian. Default is False.
    compile_modules: selects which sub-modules to wrap with :func:`torch.compile`.
        Pass ``True`` to compile every sub-module, ``False`` (default) for none, or a list
        containing any subset of ``["scale_pyr", "resp", "subpix", "ori", "aff"]``.
        Compiling ``subpix`` gives ~5x GPU speedup for the default
        :class:`~kornia.geometry.subpix.ConvQuadInterp3d` backend by fusing its iteration loop.
        The first call incurs a one-time compilation cost; subsequent calls are fast.

Nnum_featuresmr_sizescale_pyr_moduleresp_modulesubpix_module
ori_module
aff_moduleminima_are_also_goodscale_space_responsecompile_modulesr   c                   >^ [         TU ]  5         X l        Xl        1 SknU
SL a  UmO8U
SL a  [	        5       mO([	        U
5      mTU-
  nU(       a  [        SU SU 35      eT(       a  S[        R                  R                  l	        S[        R                  S[        S[        R                  4U4S	 jjnUc  U	(       a  S
OSn[        S
SSUS9nU" US5      U l        Uc
  [        5       nU" US5      U l        Uc
  [#        SSS9n[%        U[&        ["        [(        45      U l        U" US5      U l        Uc
  [/        5       nU" US5      U l        Uc
  [/        5       nU" US5      U l        Xl        Xl        g )N>   afforirespsubpix	scale_pyrTFz)Unknown module names in compile_modules: z	. Valid: modnamer   c                 >   > UT;   a  [         R                  " U SS9$ U $ )NTdynamic)r!   compile)rI   rJ   _compile_sets     r&   _maybe_compile3ScaleSpaceDetector.__init__.<locals>._maybe_compile   s!    7;|7K5==d3TQTTr(         g?   )extra_levelsrH   rF           )strict_maxima_bonusallow_scale_stepsrG   rE   rD   )super__init__r:   r9   set
ValueErrorr!   _dynamoconfig capture_dynamic_output_shape_opsr   Modulestrr   rH   r   rF   r
   
isinstancer   r   _is_iterative_subpixrG   r   rE   rD   r@   rA   )selfr9   r:   r;   r<   r=   r>   r?   r@   rA   rB   
_all_namesunknownrP   rU   rO   	__class__s                  @r&   rZ   ScaleSpaceDetector.__init__p   s}    	(B
d"%L%5L/L"Z/G #LWIU^_i^j!kll
 EIEMM  A	U		 	U 	U 	U # 41!L+AsB\R'(8+F%-K";7	 0S\`aM*4,.BDYZ+
! %]H= J!*e4 J!*e4$8! %9!r(   c                 v   U R                   R                   SU R                   SU R                   SU R                  R                  5        SU R                  R                  5        SU R                  R                  5        SU R                  R                  5        SU R                  R                  5        S3$ )	Nz(num_features=z
, mr_size=z, scale_pyr=z, resp=z	, subpix=z, ori=z, aff=))
rg   __name__r9   r:   rH   __repr__rF   rG   rE   rD   )rd   s    r&   rl   ScaleSpaceDetector.__repr__   s    ~~&&' ( --. /||n %0023 4II&&() *kk**,- .88$$&' (88$$&'q*		
r(   octave
sigmas_oct	num_featsr)   rotmatr   is_iterative_subpixpx_sizec	           	      	   UR                   n	UR                  n
UR                  5       u  ppnU R                  (       a!  U R	                  XR                  S5      5      nOmU R	                  UR                  SSSSS5      R                  X-  XU5      UR                  S5      5      R                  XXU5      nUR                  SSSSS5      nUSS2SUR                  S   24   nUb  [        UUR                  5      nUU-  n[        U5      u  nnU R                  (       aY  U(       a(  U R                  UUS9u  nnU R                  U* US9u  nnOYU R                  U5      u  nnU R                  U* 5      u  nnO/U(       a  U R                  UUS9u  nnOU R                  U5      u  nnS	USS2SS2S4'   S	USS2SS2S4'   U R                  (       ae  S	WSS2SS2S4'   S	USS2SS2S4'   UU:  U-  n[        R                  " UUU5      n[        R                  " UR                  S5      WU5      nUU-  nOUnUR                  US5      nUR                  US5      nUR                  USS5      R                  SSS5      nUS:X  a  US   R!                  S
S9S   nUS   U   nUS   U   n [#        UUR                  S   5      n!U!S:  a>  [        R$                  " UU!S9u  n"n#U U#   R                  S5      n$U"R                  S5      n"OUR'                  SS5      n"UR'                  SSS5      n$O[        R(                  " U
5      R"                  S-  n%UR+                  U) U%5      n&[#        UU&R                  S5      5      n![        R$                  " U&U!SS9u  n"n'[        R,                  " USU'R                  S5      R/                  SSS5      5      n$U"R                  5       u  nn([1        U$UU5      n$[        R2                  " U R4                  U$SS2SS2S4   R                  UU(SS5      -  U-  U$SS2SS2SS24   R                  UU(SS5      /S5      n)U)SS2SS2SS4   S-  n*U)SS2SS2SS4   n+U)SS2SS2SS4   n,UR                  S   UR                  S   n.n-U+U*[6        -  -
  S:  U+U*[6        -  -   U.S-
  :*  -  U,U*-
  S:  -  U,U*-   U-S-
  :*  -  n/U"U/R9                  X5      -  n"U)R;                  U5        U"U)4$ )uJ   Process one scale-space octave: response → NMS/subpix → top-K → LAF.r   rS   r   rR      N)precomputed_nms_maskrV   T)as_tuplekrz   dim      ?   )devicedtypesizerA   rF   r    permutereshaper   r5   r   r@   rG   r!   wherer2   nonzeromintopk	new_zerosfinfomasked_fillgatherexpandr'   catr:   r   tomul_)0rd   rn   ro   rp   r)   rq   r   rr   rs   devr   r$   CHLHWoct_respscale_sigmasoct_maskmax_nms_maskmin_nms_mask	coord_maxresponse_max	coord_minresponse_mintake_min_mask	cand_mask	mask_flat	resp_flat
coord_flatnms_idx
resp_candscoord_candsk_effresp_flat_best	local_idxmax_coords_bestfillresp_maskedidxsNcurrent_lafshalf_scxcyhw	good_masks0                                                   r&   _process_octave"ScaleSpaceDetector._process_octave   s     mmqQ $$yy)<=Hyy1aA!>!F!FqubUV!WYcYhYhikYlmrrbQH  ''1aA6H!!%8x~~a'8%8"89%8x~~%NH(*H &2(%;"l$$"*.++hUa+*b'	<*.++xiVb+*c'	<*.++h*?'	<*.++xi*@'	< &*kk(Q]k&^#I|&*kk(&;#I| !$Q1W!$Q2X$$$'LAq!%(LAr")L8LHM ;;}lLQLM$;$;A$>	9UI$}4I$I
 NN1b)	 %%a,	^^Aq"-55aA>
6l**D*9!<G"1g.J$Q-0K	7==#34Eqy,1JJzU,K)	"-i"8"B"B1"E!/!9!9!!<!*!4!4Q!:","6"6q!Q"? ;;u%))A-D#//
DAK	;#3#3A#67E#(::kU#J ND#ll:q$..:L:S:STVXZ\]:^_O""$1/zZyyq!Qw7<<Q1aHH6Q1ac	*//1a; 
 aAqj)C/!Q1*%!Q1*%||AQ1&?**a/F_,,A57F{a! F{a!e#% 	 (),,s*BB'"|++r(   imgc                    UR                   nUR                  nU R                  U5      u  pgn[        U R                  R                  [
        R                  5      (       a.  [        U R                  R                  R                  5       5      n	Ok[        U R                  R                  [        5      (       a  U R                  R                  n	O+[        S[        U R                  R                  5       35      e[
        R                  " SXTS9R                  SSSS5      n
U R                  nU R                  R                  (       a  SOSn[        [!        U5      5       Vs/ s H
  oSU-  -  PM     nn[!        U5      n[        U5       Vs/ s H  nU R#                  Xm   X}   X#XXU   5      PM!     nn[
        R$                  " U Vs/ s H  nUS   PM
     snS5      n[
        R$                  " U Vs/ s H  nUS   PM
     snS5      nUR'                  S5      nUU:  a;  UU-
  n[(        R*                  " USU45      n[(        R*                  " USSSSSU45      n[
        R,                  " UUSS	9u  nn[
        R.                  " USUR1                  S
5      R1                  S
5      R3                  S
S
SS5      5      nUU4$ s  snf s  snf s  snf s  snf )NzUExpected the scale pyramid module to have `n_levels` as a torch.Tensor or int.Gotcha rS   )r   r   r   r}         ?r   r   r{   ru   rR   )r   r   rH   rb   n_levelsr!   Tensorintitem	TypeErrortypeeyer    rc   double_imagerangelenr   r   r   r0   padr   r   r2   r   )rd   r   rp   r)   r   r   spr   _r   rq   rr   px_size0ipx_sizesn_octresultsr	responseslafsn_candidatesr   r   s                          r&   detectScaleSpaceDetector.detect8  su    jj YYs+A dnn--u||<<T^^4499;<J//5500Jt~~6678:  1E6;;Aq!QG"77..553316s2w@AQ'@ B
 5\	<
 "   vy)6GZef\g "	 	 <
 IIW5WqtW5q9	yy01!A$0!4 ~~a()#l*Ci!S2I551aAs34D**Y)C	4||D!T^^B%7%A%A"%E%L%LRQSUVXY%Z[$9 A<
 60s   !K&KK3Kc                     U R                  XR                  U5      u  p4U R                  XA5      nU R                  XA5      nXC4$ )a  Three stage local feature detection.

First the location and scale of interest points are determined by detect function.
Then affine shape and orientation.

Args:
    img: image to extract features with shape [BxCxHxW]
    mask: a mask with weights where to apply the response function. The shape must be the same as
      the input image.

Returns:
    lafs: shape [BxNx2x3]. Detected local affine frames.
    responses: shape [BxNx1]. Response function values for corresponding lafs

)r   r9   rD   rE   rd   r   r)   r   r   s        r&   forwardScaleSpaceDetector.forwardj  s@      ++c+<+<dC	xx"xx"r(   )
rc   rD   r@   r:   r9   rE   rF   rH   rA   rG   )
i  g      @NNNNNFFFN)rk   
__module____qualname____firstlineno____doc__r   r#   r   r   r`   boolr   r   ra   rZ   rl   r!   r   r   r   r   r   __static_attributes____classcell__rg   s   @r&   r7   r7   L   s   !J  04+/-1*.*.%*%*27=9=9 =9 #299-	=9
 bii(=9  		*=9 RYY'=9 RYY'=9 #=9 #=9 tT#Y/=9 
=9 =9~

# 

{,{, LL{, 	{,
 u||${, {, {, "{, {, 
u||U\\)	*{,| QU0<<0,/07?7M0	u||U\\)	*0d5<< x/E QVW\WcWcejeqeqWqQr  r(   r7   c                   L    \ rS rSr% Sr\\S'   \\S'   \\S'   \\S'   \\S'   Srg	)
Detector_configi  zConfiguration for the Scale Space Detector.

Attributes:
    nms_size: The size of the Non-Maximum Suppression window.
    pyramid_levels: The number of levels in the image pyramid.
nms_sizepyramid_levels	up_levelsscale_factor_levelss_mult N)	rk   r   r   r   r   r   __annotations__r#   r   r   r(   r&   r   r     s$     MNMr(   r   c                  *    [         R                  5       $ )zReturn default config.)_DEFAULT_DETECTOR_CONFIGcopyr   r(   r&   get_default_detector_configr     s     $((**r(   c                   N  ^  \ rS rSrSr      SS\R                  S\S\\	   S\\R                     S\\R                     S	\
S
\SS4U 4S jjjrSS\R                  S\S\R                  4S jjrS\R                  S\S\\\4   S\\R                  \R                  4   4S jrSS\R                  S\\R                     S\\R                  \R                  4   4S jjrSS\R                  S\\R                     S\\R                  \R                  4   4S jjrSrU =r$ )MultiResolutionDetectori  aQ  Multi-scale feature detector, based on code from KeyNet. Can be used with any response function.

This is based on the original code from paper
"Key.Net: Keypoint Detection by Handcrafted and Learned CNN Filters".
See :cite:`KeyNet2019` for more details.

Args:
    model: response function, such as KeyNet or BlobHessian
    num_features: Number of features to detect.
    conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing`.
    ori_module: for local feature orientation estimation. Default: :class:`~kornia.feature.PassLAF`,
       which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.
    aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,
        which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.

Nmodelr9   r^   r>   r?   compile_modelscore_thresholdr   c                   > [         T	U ]  5         Uc
  [        5       nUS   U l        US   U l        US   U l        US   U l        US   U l        Xpl        [        U R                  U R                  45      nX l
        U(       a5  [        R                  " USS9U l        [        R                  " USS9U l        OXl        Xl        Uc  [        5       U l        OX@l        Uc  [        5       U l        g XPl        g )Nr   r   r   r   r   TrL   )rY   rZ   r   num_pyramid_levelsnum_upscale_levelsr   r:   r   r   r   r9   r!   rN   r   nmsr   rE   rD   )
rd   r   r9   r^   r>   r?   r   r   r   rg   s
            r&   rZ    MultiResolutionDetector.__init__  s     	>02F"()9":"("5#)*?#@ h'z*.$dmmT]]%CD(ud;DJ}}S$7DHJH"))DH!H"))DH!Hr(   	score_mapbordersc                 X    [         R                  " U5      nSUSS2SS2X"* 2X"* 24'   X1-  $ )zCRemove the borders of the image to avoid detections on the corners.r   N)r!   
zeros_like)rd   r   r   r)   s       r&   remove_borders&MultiResolutionDetector.remove_borders  s8    	*9:Q78#WX%556r(   	level_imgnum_kpfactorc           	      
   U R                  U R                  U R                  U5      5      5      nUR                  u    pVnUR	                  S5      n[
        R                  " UR                  5      R                  S-  n	UR                  XR                  :*  U	5      n
[        X(R                  5       5      n[
        R                  " XS9u  p[
        R                  " X-  X-  /SS9nUR                  US   US   /5      nUR	                  SUS5      R                  S5      R!                  5       U-  nSUS   US   -   -  U R"                  -  nUR%                  SUSS4U5      n['        UUUR)                  SUS5      5      nUU4$ )Nru   rS   ry   r   )r|   r   r}   )r   r   r   r   r    r!   r   r   r   r   r   numelr   stack
new_tensorflipr#   r:   new_fullr   r   )rd   r   r   r   det_mapr   _hr   det_flatr   
det_maskedrz   
top_scorestop_flat_idxyxfxxy_projected	scale_valscaler   s                       r&   detect_features_on_single_level7MultiResolutionDetector.detect_features_on_single_level  si    ((4..tzz)/DEFmm1!<<#
 {{8>>*..2))(6J6J*JDQ
()#(::j#> 
 [[,+\-=>AF!!6!9fQi"89wwq!Q',,Q/557"<6!9vay01DLL@	""Aq!Q<;(ui>Q>QRSUVXY>Z[4r(   r   r)   c           
         / nSnU R                   S-  nU R                  U R                  -   S-   n[        U5       HK  nXESXpR                  -
  -  -  -  nU R                  USXpR                  -
  -  -  -  nUR                  U5        MM     U V	s/ s H  n	[        X-  5      PM     nn	UR                  u    pnUnUn/ n/ n[        U R                  5       H  nU[        U5      U R                  -
  S-
  US-   -
     n[        U5      nU R                   SU-   -  n[        UU-  5      [        UU-  5      nn[        U5      [        U5      -  [        U5      [        U5      -  4n[        UUU4SSS9nU R                  UUU5      u  nnUR                  UR                  SS5      5        UR                  U5        M     [        U R                  S-   5       H  nUS:  aS  [        XR                   S	9nUR                  u    n
nn[        U5      [        U5      -  [        U5      [        U5      -  4nOS
n[        X7   5      nUS:  d  U R                  S:  a  [        US US-   U R                  -    5      nU R                  UUU5      u  nnUR                  UR                  SS5      5        UR                  U5        M     [        R                   " US5      n[        R                   " US5      nUR                  S   U R                  :  aP  [        R"                  " UU R                  SS9u  nn[        R$                  " USUS   R'                  SSSS5      5      nUU4$ s  sn	f )NrV   rS   r   ru   r-   F)interpolationr/   r   )r   )r   r   r{   ).NNrR   )r   r   r   r   r9   appendr   r   r   r#   r   r  r    r   sumr!   r   r   r   r   )rd   r   r)   num_features_per_leveltmpfactor_pointslevels	idx_levelnfxr   r   r   img_upcur_imgall_responsesall_lafsnum_points_level	up_factornhnwup_factor_kpts
cur_scorescur_lafsr   r   r   r   s                               r&   r   MultiResolutionDetector.detect  sM   .000!3((4+B+BBQFvIR97N7N+N%OPPC""]rYI`I`=`7a%bbB"))"- ' 9O!O8N1#ag,8N!OYY
1,.')t667I',B(CdF]F](]`a(aenqrer(stB"2w 00Q]CIY'Q]);B#Ahr2E!HuRy4HINFRHJV[\F#'#G#GP`bp#q J  B!78OOH% 8  t66:;I1}!'2J2JK&}}1b"(U2Y.a590DE#"#9#DE1}!8!81!<#&'=>g	APTPgPg@g'h#i #'#G#GQaci#j J  B!78OOH% < IImQ/	yy1%::a=4,,,#jjd6G6GQOOIt<<ao)>)E)Eb"aQR)STD$Y "Ps   Mc                     [        U/ SQ5        U R                  X5      u  p4U R                  XA5      nU R                  XA5      nXC4$ )aV  Three stage local feature detection.

First the location and scale of interest points are determined by detect function.
Then affine shape and orientation.

Args:
    img: image to extract features with shape [1xCxHxW]. KeyNetDetector does not support batch processing,
because the number of detections is different on each image.
    mask: a mask with weights where to apply the response function. The shape must be the same as
      the input image.

Returns:
    lafs: shape [1xNx2x3]. Detected local affine frames.
    responses: shape [1xNx1]. Response function values for corresponding lafs

)1Cr   r   )r	   r   rD   rE   r   s        r&   r   MultiResolutionDetector.forward&  sC    " 	3 45++c0	xx"xx"r(   )rD   r   r:   r   r   r9   r   r   rE   r   r   )i   NNNFrV   )   r   )rk   r   r   r   r   r   r`   r   r   r   r   r#   rZ   r!   r   r   r   r  r   r   r   r   r   s   @r&   r   r     s|   ( !,0*.*.#!$&"yy&" &" )	&"
 RYY'&" RYY'&" &" &" 
&" &"P   s  ELL    /2 <A%,<O 	u||U\\)	* 26%,, 6hu||.D 6PUV[VbVbdidpdpVpPq 6p5<< x/E QVW\WcWcejeqeqWqQr  r(   r   r-  rv   rS   g      6@)r   r   r   r   r   r   )/mathtypingr   r   r   r   r!   torch.nn.functionalr   
functionalr0   typing_extensionsr   kornia.core.checkr	   kornia.geometry.subpixr
   r   r   r   r   kornia.geometry.transformr   r   r   lafr   orientationr   r   r   sinpir   r#   r   r   r   r'   r5   r`   r7   r   r   r   sqrtr   r   r(   r&   <module>r;     s  $  / /     ' 0  D C *   " %$''/B"67 7ell ELL VY ^c^j^j *$ell $$s) $ $q qh	i +_ +fbii fV 99Q<- / r(   