+
    åûj´ ã                   ó`  € ^ RI t ^ RIHtHtHtHt ^ RIt^ RIHu H	t
 ^ RIHtHtHt ^ RIHt ^ RIHtHt ^ RIHt ^ RIHt ^ RIHt R	 R
 ltR R ltR R ltR R ltR R ltR R ltR R lt R R lt!ROR R llt"R R lt#RPR R llt$R R  lt%RQR! R" llt&RRR# R$ llt'R% R& lt(R' R( lt)RSR) R* llt*R+ R, lt+R- R. lt,R/ R0 lt-R1 R2 lt.R3 R4 lt/R5 R6 lt0RTR7 R8 llt1RUR9 R: llt2R; R< lt3R= R> lt4R? R@ lt5RA RB lt6RVRC RD llt7RVRE RF llt8RRRG RH llt9RI RJ lt:RK RL lt;RM RN lt<R# )Wé    N)ÚListÚOptionalÚTupleÚUnion)ÚKORNIA_CHECKÚKORNIA_CHECK_LAFÚKORNIA_CHECK_SHAPE)Ú_copied_literal)Ú_autocast_disabledÚ_convolution_outside_autocast)Úangle_to_rotation_matrix)Útransform_points)Úpyrdownc                óX   € V ^8„  d   QhR\         P                  R\         P                  /# ©é   ÚdtypeÚreturn©Útorchr   )Úformats   "ÚNC:\Ai_Coding\apps\studio\ComfyUI\.venv\Lib\site-packages\kornia\feature\laf.pyÚ__annotate__r       s"   € ÷ ñ œeŸk™kð ¬e¯k©kñ ó    c                óP   € V \         P                  8X  d   \         P                  # V # )a  Return the dtype to multiply two LAF entries in.

A product of two entries of an ordinary LAF can leave the float16 range. It overflows above 65504: the determinant
of any LAF of scale 256 px or more, and the square of a 256 px entry of an elongated LAF of a smaller scale (300 x
20 px has a scale of 77 px). It rounds to zero for entries below about 1.7e-4. float16 therefore works in float32,
which holds every product of two float16 values exactly. bfloat16 has the exponent range of float32 and is left as
it is.
)r   Úfloat16Úfloat32©r   s   &r   Ú_laf_product_dtyper       s   € ð ”—‘ÔÜ�}‰}ÐØ€Lr   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# ©r   ÚLAFr   ©r   ÚTensor)r   s   "r   r   r   .   s"   € ÷ 'ñ '”u—|‘|ð '¬¯©ñ 'r   c                ó„  € \        V 4       RpV P                  \        V P                  4      4      pVR,          VR,          ,          VR,          VR,          ,          ,
          V,           pVP	                  4       P                  4       pVP                  V P                  8w  d   VP                  V P                  4      pV# )aÄ  Read the scale of each LAF, the square root of the absolute determinant of its shape.

``scale = get_laf_scale(laf)`` takes ``(B, N, 2, 3)`` LAFs and returns their scales :math:`\sqrt{|\det A|}` as a
``(B, N, 1, 1)`` tensor, in pixels for LAFs in pixels: the radius of a circular LAF's region, and the geometric
mean of the two semi-axes of an elliptical one. The result broadcasts against the shape ``A``, so use
``scale_laf(laf, 1.0 / scale)`` to normalize an ordinary LAF. For the orientation and centre, use
:func:`get_laf_orientation` and :func:`get_laf_center`.

Convention:
    - See the Convention block on :func:`~kornia.feature.laf_from_center_scale_ori`, which defines the scale.
    - The ``1e-10`` added to the determinant makes frames smaller than about ``1e-4`` px read too large.
    - The determinant of a float16 LAF is formed in float32, so that a LAF whose entry products leave the float16
      range does not overflow; the scale is returned in the LAF dtype.

Args:
    LAF: ``(B, N, 2, 3)``

Returns:
    scale ``(B, N, 1, 1)``

See Also:
    - :func:`scale_laf`: multiplies the scale by a coefficient, keeping the centre.
    - :func:`get_laf_orientation`: the orientation of the same LAFs.
    - :func:`get_laf_center`: the centre of the same LAFs.
    - :func:`laf_from_center_scale_ori`: LAFs of given scales, built from keypoint centres.

Example:
    >>> input = torch.ones(1, 5, 2, 3)  # BxNx2x3
    >>> output = get_laf_scale(input)  # BxNx1x1

g»½×Ùß|Û=©.ºr   é   Nr'   ©.ºr(   r   Nr*   ©.r*   r'   ©.r'   r*   )r   Útor   r   ÚabsÚsqrt)r"   ÚepsÚworkÚoutÚscales   &    r   Úget_laf_scaler4   .   s’   € ô@ �SÔØ
€CØ�6‰6Ô$ S§Y¡YÓ/Ó0€DØ
ˆ}Õ
  ]Õ 3Õ
3°d¸=Õ6IÈDÐQ^ÕL_Õ6_Õ
_ÐbeÕ
e€CØ�G‰G‹I�N‰NÓ€EØ‡z�z�S—Y‘YÔØ—‘˜Ÿ™Ó#ˆØ€Lr   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# ©r   Úlafr   r#   )r   s   "r   r   r   X   s&   € ÷ %Pñ %P”e—l‘lð %P¤u§|¡|ñ %Pr   c                ód  € \        V 4       V P                  \        V P                  4      4      p V R,          V R,          ,          V R,          V R,          ,          ,
          pV P	                  4       P                  RR7      P                  RR7      VP	                  4       ,          V^ 8g  ,          # )am  Check that each LAF is finite and has a finite, nonzero determinant.

``valid = laf_is_valid(laf)`` takes ``(B, N, 2, 3)`` LAFs and returns a boolean ``(B, N)`` mask, true where every
entry is finite and the shape ``A`` has a finite, nonzero determinant, so that it maps the patch onto a region of
nonzero area. It does not check where the LAF lies: for the LAFs whose region lies inside the image, use
:func:`laf_is_inside_image`, and to drop only the padding of a detector's unfilled slots, use
:func:`laf_is_filled` instead.

Convention:
    - A LAF with a negative determinant, a mirrored frame, is valid. The all-zero padding LAF (see
      :func:`~kornia.feature.laf_is_filled`), a rank-1 ``A`` and an ``A`` whose determinant overflows are not.
    - The determinant of a float16 LAF is formed in float32, so the LAF is not judged by an intermediate outside
      the float16 range: one whose entry products overflow float16 (for instance any LAF of scale 256 px or more)
      is valid, and so is one whose determinant is too small for float16. The determinant of a float32, float64
      or bfloat16 LAF is formed in that dtype, where it can overflow.

Args:
    laf: ``(B, N, 2, 3)``.

Returns:
    validity mask ``(B, N)``.

See Also:
    - :func:`laf_is_filled`: rejects only the all-zero padding, and accepts singular and non-finite frames.
    - :func:`laf_is_inside_image`: checks where the region lies, not whether the frame is regular.
    - :func:`KORNIA_CHECK_LAF`: checks only the ``(B, N, 2, 3)`` shape, not the values.

Example:
    >>> laf = torch.eye(2, 3).view(1, 1, 2, 3)
    >>> laf_is_valid(laf)
    tensor([[True]])

©Údim©.r   r   ).r(   r(   ).r(   r   ©.r   r(   éÿÿÿÿ)r   r-   r   r   ÚisfiniteÚall)r7   Údets   & r   Úlaf_is_validrA   X   s…   € ôD �SÔØ
�&‰&Ô# C§I¡IÓ.Ó
/€CØ
ˆi�.˜3˜y�>Õ
)¨C°	­N¸SÀ½^Õ,KÕ
K€CØ�<‰<‹>×Ñ "ÐÓ%×)Ñ)¨bÐ)Ó1°C·L±L³NÕBÀcÈQÁhÕOÐOr   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# r6   r#   )r   s   "r   r   r   €   s"   € ÷ %-ñ %-”u—|‘|ð %-¬¯©ñ %-r   c                óz   € \        V 4       V P                  ^ 4      P                  RR7      P                  RR7      # )aÏ  Check which slots hold a detection rather than the zero-LAF padding.

``filled = laf_is_filled(lafs)`` takes the ``(B, N, 2, 3)`` LAFs of a detector and returns a boolean ``(B, N)``
mask, false for all-zero padded frames: index the LAFs, responses and
descriptors of image ``b`` with ``laf_is_filled(lafs)[b]`` to keep its detections. A filled frame need not be
usable; to also drop singular and non-finite frames, use :func:`laf_is_valid` instead.

Convention:
    - kornia's LAF detectors pad unused slots with an all-zero LAF and a zero response, so that a
      batch is one tensor. Drop those slots before matching: the padding frames are identical to one another, so a
      mutual nearest-neighbour test does not reject them and they match each other at zero distance.
    - Only an all-zero frame is padding. Any other frame is filled: a detection at the image origin, which has a
      zero centre but a nonzero shape, and also a singular or non-finite frame, which
      :func:`~kornia.feature.laf_is_valid` screens out.
    - Occupancy cannot be read off the response instead, because a pluggable signed response may have a genuine
      maximum at exactly zero.

Args:
    laf: ``(B, N, 2, 3)``.

Returns:
    mask of the slots a detection filled ``(B, N)``.

See Also:
    - :func:`laf_is_valid`: rejects singular and non-finite frames as well as the padding.
    - :func:`laf_is_inside_image`: counts the padding as inside the image at the default border, so combine the
      two masks.
    - :class:`LocalFeatureMatcher`: drops the padded slots itself before matching.

Example:
    >>> laf = torch.tensor([[[[2., 0., 5.], [0., 3., 7.]], [[0., 0., 0.], [0., 0., 0.]]]])
    >>> laf_is_filled(laf)
    tensor([[ True, False]])

r9   r=   )r   ÚneÚany©r7   s   &r   Úlaf_is_filledrG   €   s4   € ôH �SÔØ�6‰6�!‹9�=‰=˜Rˆ=Ó ×$Ñ$¨Ð$Ó,Ð,r   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# r!   r#   )r   s   "r   r   r   ¨   s"   € ÷ ñ œŸ™ð ¬¯©ñ r   c                ó*   € \        V 4       V R,          # )aø  Read the centre of each LAF, its keypoint position ``(x, y)``.

``xy = get_laf_center(laf)`` takes ``(B, N, 2, 3)`` LAFs and returns their centres ``c = (x, y)``, the last column
of each LAF, as a ``(B, N, 2)`` tensor in the LAF's units and dtype. The result is a view of ``laf``, not a copy.
To build LAFs from keypoints, use :func:`laf_from_center_scale_ori`.

Convention:
    The centre is ``(x, y)`` in pixels, with pixel centres at integers; see
    :ref:`Local features <local-features-conventions>`.

Args:
    LAF: ``(B, N, 2, 3)``

Returns:
    xy ``(B, N, 2)``

See Also:
    - :func:`laf_from_center_scale_ori`: LAFs built from centres, with optional scales and orientations.
    - :func:`get_laf_scale`: the scale of the same LAFs.
    - :func:`get_laf_orientation`: the orientation of the same LAFs.
    - :func:`laf_to_three_points`: the centre together with the tips of the patch's two axes.

Example:
    >>> input = torch.ones(1, 5, 2, 3)  # BxNx2x3
    >>> output = get_laf_center(input)  # BxNx2

©.r   )r   )r"   s   &r   Úget_laf_centerrK   ¨   s   € ô8 �SÔØˆv�;Ðr   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# r!   r#   )r   s   "r   r   r   È   s"   € ÷ #2ñ #2œUŸ\™\ð #2¬e¯l©lñ #2r   c                ó¬   € \        V 4       \        P                  ! V R,          V R,          4      p\        P                  ! V4      P	                  R4      # )aâ  Read the orientation of each LAF in degrees, from the first row of its shape.

``ori = get_laf_orientation(laf)`` takes ``(B, N, 2, 3)`` LAFs and returns their orientations ``atan2(a12, a11)``
in degrees, within ``[-180, 180]``, as a ``(B, N, 1)`` tensor. It reads only the first row of the shape ``A``,
which for ``A = U R``, an upright factor times the rotation matrix of an angle, gives that angle whatever the shear
of ``U``. For a circular similarity frame ``A = s R``, OpenCV's ``KeyPoint.angle`` is ``(-ori) mod 360``. For a
general affine frame, use ``atan2(a21, a11)`` in degrees modulo 360; an OpenCV keypoint cannot
retain its affine shape or reflection. To change the orientation, use :func:`set_laf_orientation` or
:func:`rotate_laf`.

Convention:
    See the Convention block on :func:`~kornia.feature.laf_from_center_scale_ori`, which defines the orientation.

Args:
    LAF: ``(B, N, 2, 3)``

Returns:
    angle in degrees ``(B, N, 1)``

See Also:
    - :func:`set_laf_orientation`: sets the orientation to given angles.
    - :func:`rotate_laf`: adds angles to the orientation.
    - :func:`make_upright`: removes the rotation, so that the orientation reads 0.
    - :func:`laf_from_center_scale_ori`: LAFs of given orientations, built from keypoint centres.
    - :func:`get_laf_scale`: the scale of the same LAFs.
    - :func:`get_laf_center`: the centre of the same LAFs.

Example:
    >>> input = torch.ones(1, 5, 2, 3)  # BxNx2x3
    >>> output = get_laf_orientation(input)  # BxNx1

r<   r;   r=   )r   r   Úatan2Úrad2degÚ	unsqueeze)r"   Ú	angle_rads   & r   Úget_laf_orientationrR   È   s?   € ôB �SÔÜ—’˜C 	�N¨C°	­NÓ;€IÜ�=Š=˜Ó#×-Ñ-¨bÓ1Ð1r   c                óx   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  /# ©r   r"   Úangles_degreesr   r#   )r   s   "r   r   r   î   s-   € ÷  ñ  ”E—L‘Lð  ´%·,±,ð  Ä5Ç<Á<ñ  r   c                ó<  € \        V 4       V P                  R,          w  r#\        V4      P                  W#,          ^^4      pV P	                  4       p\
        P                  ! V R,          P                  W#,          ^^4      V4      P                  W#^^4      VR&   V# )að  Rotate each LAF's patch frame by an angle in degrees, adding it to the orientation.

``rotated = rotate_laf(laf, angles)`` takes ``(B, N, 2, 3)`` LAFs and angles ``(B, N, 1)`` in degrees and returns
the ``(B, N, 2, 3)`` LAFs whose orientation is the input's plus ``angles``. Only the patch frame turns: the
centre, scale and region, the ellipse ``c + A u`` over unit vectors ``u``, stay the same. To set given
orientations instead, use :func:`set_laf_orientation`.

Convention:
    - The result is ``[A @ R | c]``, with ``R`` the rotation matrix of ``angles_degrees`` from
      :func:`~kornia.geometry.conversions.angle_to_rotation_matrix`. The orientation grows by ``angles_degrees``
      (:func:`~kornia.feature.set_laf_orientation` sets it instead), and the centre and the upright factor that
      :func:`~kornia.feature.make_upright` returns are kept.

Args:
    LAF: ``(B, N, 2, 3)``
    angles_degrees: ``(B, N, 1)`` in degrees.

Returns:
    LAF oriented with angles ``(B, N, 2, 3)``

See Also:
    - :func:`set_laf_orientation`: rotates to given orientations rather than by given angles.
    - :func:`get_laf_orientation`: reads the orientation that this adds to.
    - :class:`LAFOrienter`: rotates each LAF by the angle estimated on its image patch.

ºNr   N©ºNNNrY   rW   rW   )r   Úshaper   ÚviewÚcloner   ÚbmmÚreshape)r"   rU   ÚBÚNÚrotmatÚout_lafs   &&    r   Ú
rotate_lafrc   î   sƒ   € ô6 �SÔØ�9‰9�R�=�D€AÜ% nÓ5×:Ñ:¸1½5À!ÀQÓG€FØ�i‰i‹k€GÜ!ŸIšI c¨,Õ&7×&?Ñ&?ÀÅÀqÈ!Ó&LÈfÓU×]Ñ]Ð^_ÐdeÐghÓi€GˆLÑØ€Nr   c                óx   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  /# rT   r#   )r   s   "r   r   r     s-   € ÷ 1ñ 1œUŸ\™\ð 1¼5¿<¹<ð 1ÌEÏLÉLñ 1r   c                óš   € \        V 4       V P                  R,          w  r#\        V 4      P                  V4      p\	        WV,
          4      # )a¾  Set the orientation of each LAF to an angle in degrees, keeping its region.

``oriented = set_laf_orientation(laf, angles)`` takes ``(B, N, 2, 3)`` LAFs and orientations ``(B, N, 1)`` in
degrees and returns the ``(B, N, 2, 3)`` LAFs rotated to them, as :func:`rotate_laf` rotates: the centre, the
scale and region are kept. With angles of 0, a LAF of positive determinant becomes the upright LAF of
:func:`make_upright`, up to its ``eps``. To add angles to the current orientation, use :func:`rotate_laf`
instead.

Convention:
    See the Convention block on :func:`~kornia.feature.rotate_laf`. This rotates by ``angles_degrees`` minus the
    current orientation, so the orientation reads back as ``angles_degrees`` wrapped into ``[-180, 180]``.

Args:
    LAF: ``(B, N, 2, 3)``
    angles_degrees: ``(B, N, 1)`` in degrees.

Returns:
    LAF oriented with angles ``(B, N, 2, 3)``

See Also:
    - :func:`rotate_laf`: adds angles to the current orientation instead.
    - :func:`get_laf_orientation`: reads the orientation back.
    - :func:`make_upright`: sets the orientation to 0 and drops a reflection too.
    - :func:`laf_from_center_scale_ori`: new LAFs with given orientations, built from their centres.

rW   )r   rZ   rR   Ú
reshape_asrc   )r"   rU   Ú_BÚ_NÚoris   &&   r   Úset_laf_orientationrj     s@   € ô6 �SÔØ�Y‰Y�r�]�F€BÜ
˜cÓ
"×
-Ñ
-¨nÓ
=€CÜ�c¨CÕ/Ó0Ð0r   c                óÄ   € V ^8„  d   QhR\         P                  R\        \         P                  ,          R\        \         P                  ,          R\         P                  /# )r   Úxyr3   ri   r   )r   r$   r   )r   s   "r   r   r   2  sF   € ÷ ?*ñ ?*Ü�‰ð?*Ü%¤e§l¡lÕ3ð?*ÜAIÌ%Ï,É,ÕAWð?*ä
‡\�\ñ?*r   c           	     ó¾  € \        V . RO4       V P                  pV P                  pV P                  R,          w  rVVf   \        P
                  ! WV^^W4R7      pVf   \        P                  ! WV^W4R7      p\        V. RO4       \        V. RO4       \        P                  ! \        VP                  R4      4      V P                  R4      .RR7      p\        Wq4      # )aÎ  Build circular LAFs from keypoint centres, scales and orientations.

``laf = laf_from_center_scale_ori(xy, scale, ori)`` takes keypoint centres ``xy`` ``(B, N, 2)``, scales
``(B, N, 1, 1)`` (1 when omitted) and orientations ``(B, N, 1)`` in degrees (0 when omitted), and returns the
``(B, N, 2, 3)`` LAFs ``[scale * R(ori) | xy]``, whose regions are circles of radius ``scale`` around ``xy``.
This turns the keypoints of a detector that returns no LAFs, such as :class:`DISK` or :class:`XFeat`, into the
LAFs that :class:`LAFDescriptor` and the LAF matchers take, e.g. ``laf_from_center_scale_ori(keypoints[None])``.
For an elliptical region, use :func:`ellipse_to_laf` instead.

Convention:
    - A LAF is a ``(B, N, 2, 3)`` tensor ``[A | c]``, with the centre ``c = (x, y)`` and ``A`` in pixels.
      ``A`` maps the patch frame onto the image: its first column is the image of the patch's x axis and its
      second column that of the patch's y axis. :ref:`Local features <local-features-conventions>` gives the
      pixel frame, the patch that :func:`~kornia.feature.extract_patches_from_pyramid` samples and the
      conversion of OpenCV keypoints.
    - This function returns ``A = scale * R``, with ``R = [[cos, sin], [-sin, cos]]`` of ``ori`` in degrees, the
      matrix of :func:`~kornia.geometry.conversions.angle_to_rotation_matrix`. A positive ``ori`` turns the
      patch's x axis counter-clockwise on screen, with image y pointing down.
    - For any LAF, the scale is :math:`\sqrt{|\det A|}` (:func:`~kornia.feature.get_laf_scale`, which adds
      ``1e-10`` to the determinant) and the orientation is ``atan2(a12, a11)`` in degrees
      (:func:`~kornia.feature.get_laf_orientation`), within ``[-180, 180]``: a LAF made with ``ori = 181`` reads
      back ``-179``. For :math:`\det A > 0`, ``A = U R`` with ``U`` the upright ``A`` that
      :func:`~kornia.feature.make_upright` returns, up to its stabilizers, and ``R`` the rotation matrix of that
      orientation.
    - A negative determinant mirrors the patch frame. Increasing its orientation turns its x axis clockwise on
      screen. With a nonzero scale, this constructor produces a positive determinant.

Args:
    xy: ``(B, N, 2)``.
    scale: ``(B, N, 1, 1)``. If not provided, scale = 1.0 is assumed
    ori: angle in degrees ``(B, N, 1)``. If not provided orientation = 0 is assumed

Returns:
    LAF ``(B, N, 2, 3)``

See Also:
    - :func:`get_laf_center`: reads the centres back.
    - :func:`get_laf_scale`: reads the scales back.
    - :func:`get_laf_orientation`: reads the orientations back, within ``[-180, 180]``.
    - :func:`ellipse_to_laf`: LAFs of elliptical regions, given by their ellipse coefficients.
    - :func:`laf_from_three_points`: LAFs from the images of three patch points.

Example:
    >>> xy = torch.tensor([[[5.0, 7.0]]])
    >>> laf_from_center_scale_ori(xy, torch.full((1, 1, 1, 1), 2.0), torch.tensor([[[30.0]]]))
    tensor([[[[ 1.7321,  1.0000,  5.0000],
              [-1.0000,  1.7321,  7.0000]]]])

rW   ©Údevicer   r9   )r_   r`   Ú2)r_   r`   Ú1rq   )r_   r`   rq   r=   )r	   ro   r   rZ   r   ÚonesÚzerosÚcatr   ÚsqueezerP   Ú	scale_laf)rl   r3   ri   ro   r   r_   r`   Úunscaled_lafs   &&&     r   Úlaf_from_center_scale_orirx   2  s®   € ôh �rš?Ô+Ø�Y‰Y€FØ�H‰H€EØ�8‰8�B�<�D€AØ‚}Ü—
’
˜1  A¨fÔBˆØ
‚{Ü�kŠk˜! ¨&Ô>ˆÜ�uÒ2Ô3Ü�sšOÔ,Ü—9’9Ô6°s·{±{À2³ÓGÈÏÉÐVXÓIYÐZÐ`bÔc€LÜ�\Ó)Ð)r   c                óš   € V ^8„  d   QhR\         P                  R\        \        \         P                  3,          R\         P                  /# )r   r7   Ú
scale_coefr   )r   r$   r   Úfloat)r   s   "r   r   r   t  s<   € ÷ (Mñ (M”5—<‘<ð (M¬U´5¼%¿,¹,Ð3FÕ-Gð (MÌEÏLÉLñ (Mr   c                óò   € \        V\        \        P                  34      '       g   \	        R\        V4       24      h\        V 4       V R,          p\        P                  ! W,          V R,          .^R7      # )a   Multiply the shape of each LAF by a coefficient, keeping its centre.

``scaled = scale_laf(laf, k)`` takes ``(B, N, 2, 3)`` LAFs and a coefficient ``k``, a float or a tensor such as one
coefficient per LAF in ``(B, N, 1, 1)``, and returns the ``(B, N, 2, 3)`` LAFs ``[k A | c]``, whose regions are
scaled by ``|k|`` about the same centres. A descriptor then sees a larger or smaller area around each keypoint, as
with the ``scaling_coef`` of :class:`LocalFeature`. To read the scale, use :func:`get_laf_scale`.

Convention:
    - The result is ``[k A | c]`` for ``k = scale_coef``, a product taken elementwise: the centre is kept. With one
      coefficient per LAF, the scale is multiplied by ``|k|``, and a negative ``k`` also turns the frame by 180
      degrees.
    - ``scale_coef`` is a ``float`` or a tensor that broadcasts against ``(B, N, 2, 2)``, such as one
      coefficient per LAF in a ``(B, N, 1, 1)`` tensor; an ``int`` is rejected.

Args:
    laf: ``(B, N, 2, 3)``
    scale_coef: broadcastable torch.Tensor or float.

Returns:
    LAF ``(B, N, 2, 3)``

Raises:
    TypeError: if ``scale_coef`` is neither a ``float`` nor a tensor.

See Also:
    - :func:`get_laf_scale`: reads the scale that this multiplies.
    - :func:`laf_from_center_scale_ori`: new LAFs of given scales, built from their centres.
    - :class:`LocalFeature`: applies this with its ``scaling_coef`` to the detector's LAFs before describing them.

Example:
    >>> input = torch.ones(1, 5, 2, 3)  # BxNx2x3
    >>> scale = 0.5
    >>> output = scale_laf(input, scale)  # BxNx2x3

z0scale_coef should be float or torch.Tensor. Got r9   rX   )rY   rY   rY   :r   NN)Ú
isinstancer{   r   r$   Ú	TypeErrorÚtyper   rt   )r7   rz   Úcenterless_lafs   && r   rv   rv   t  se   € ôH �j¤5¬%¯,©,Ð"7×8Ò8ÜÐJÌ4ÐPZÓK[ÐJ\Ð]Ó^Ð^Ü�SÔØ˜Õ&€NÜ�9Š9�jÕ1°3°{Õ3CÐDÈ!ÔLÐLr   c                ód   € V ^8„  d   QhR\         P                  R\        R\         P                  /# )r   r7   r0   r   )r   r$   r{   )r   s   "r   r   r   Ÿ  s.   € ÷ Gñ G”e—l‘lð G¬ð G¼%¿,¹,ñ Gr   c                ó&  € \        V 4       V P                  pV P                  \        V4      4      p \	        V 4      R,          p\
        P                  ! ^^V P                  V P                  R7      P                  V 4      pT p\
        P                  ! W0V4      p \        V 4      pTp\
        P                  ! V R,          ^,          V R,          ^,          ,           4      V,           p\
        P                  ! W†,          P                  4       \
        P                  ! V4      .^R7      p	\
        P                  ! V R,          V R,          ,          V R,          V R,          ,          ,           W†,          ,          Wh,          P                  4       .^R7      p
\
        P                  ! \
        P                  ! Wš.^R7      V R,          .^R7      p\        W·4      p\
        P                  ! W<V4      pV P                  V8w  d   VP                  V4      pV# )	at	  Remove the rotation and reflection of LAFs, keeping their regions, centres and scales.

``upright = make_upright(laf)`` takes ``(B, N, 2, 3)`` LAFs and returns the ``(B, N, 2, 3)`` LAFs of the same
regions and centres with an orientation of 0 and no reflection: the shape ``A`` becomes the lower-triangular ``U``
of the Convention block. To set another orientation, use :func:`set_laf_orientation`; to
re-estimate the shape from the image instead, use :class:`LAFAffineShapeEstimator`.

Convention:
    - The result is ``[U | c]``: the centre is kept, and ``U`` is the lower-triangular matrix with a positive
      diagonal and :math:`U U^\top = A A^\top`. The region, the ellipse ``c + A u`` over the unit vectors ``u``,
      and the scale are therefore kept, and the orientation becomes 0.
    - For :math:`\det A > 0`, ``A = U R`` with ``R`` the rotation matrix of the LAF's orientation, as in
      :func:`~kornia.feature.laf_from_center_scale_ori`. For :math:`\det A < 0` the reflection is dropped too:
      ``U`` has the determinant :math:`|\det A|`.
    - The equalities above hold up to two stabilizers: ``U`` is built from the norm of the first row of ``A``
      plus ``eps``, and from the scale of :func:`~kornia.feature.get_laf_scale`, which adds ``1e-10`` to the
      determinant. Both are negligible for a LAF in pixels, but a tiny frame such as ``A = diag(1e-12, 1)`` keeps
      neither its region nor its scale. The centre and the zero orientation are exact.
    - The all-zero LAF that pads an unfilled detector slot (see :func:`~kornia.feature.laf_is_filled`) is
      returned unchanged, so the padding stays recognizable.
    - A float16 LAF is rectified in float32, so that a LAF whose entry products leave the float16 range does not
      overflow; the result is returned in the LAF dtype.

Args:
    laf: ``(B, N, 2, 3)``
    eps: for safe division.

Returns:
    laf: ``(B, N, 2, 3)``

See Also:
    - :func:`set_laf_orientation`: with angles of 0, the same LAFs for a positive determinant, but a reflection
      is kept.
    - :class:`LAFAffineShapeEstimator`: re-estimates the shape from the image patch; with
      ``preserve_orientation=False`` its output is upright too.
    - :func:`ellipse_to_laf`: the same upright LAF, built from the coefficients of the region's ellipse.

Example:
    >>> input = torch.ones(1, 5, 2, 3)  # BxNx2x3
    >>> output = make_upright(input)  #  BxNx2x3

rn   r9   ).NNr,   r&   r)   r+   ).rY   ºr   é   N)r   r   r-   r   rG   r   Úeyero   Ú	expand_asÚwherer4   r/   rt   Ú
contiguousÚ
zeros_likerv   )r7   r0   r   Úfilledr…   Úpaddingr@   r3   Úb2a2Úlaf1_ellÚlaf2_ellÚlaf_unit_scaleÚuprightr2   s   &&            r   Úmake_uprightr‘   Ÿ  s™  € ôV �SÔØ�I‰I€EØ
�&‰&Ô# EÓ*Ó
+€Cô ˜3Ó Õ0€FÜ
�)Š)�A�q §¡°3·9±9Ô
=×
GÑ
GÈÓ
L€CØ€GÜ
�+Š+�f 3Ó
'€CÜ
˜Ó
€CØ€Eô �:Š:�c˜-Õ(¨AÕ-°°MÕ0BÀaÕ0GÕGÓHÈ3ÕN€DÜ�yŠy˜4�:×1Ñ1Ó3´U×5EÒ5EÀcÓ5JÐKÐQRÔS€HÜ�yŠyà�-Õ  3 }Õ#5Õ5¸¸MÕ8JÈSÐQ^ÕM_Õ8_Õ_ÐdhÕdnÕoØ�Z×#Ñ#Ó%ð	
ð ô€Hô —Y’Y¤§	¢	¨8Ð*>ÀAÔ FÈÈKÕHXÐYÐ_`Ôa€NÜ˜Ó.€Gä
�+Š+�f wÓ
/€CØ
‡y�y�EÔØ�f‰f�U‹mˆØ€Jr   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# )r   Úellsr   r#   )r   s   "r   r   r   é  s&   € ÷ ?Añ ?AœŸ™ð ?A¬%¯,©,ñ ?Ar   c           	     ó  € \        V . RO4       V P                  w  rpV R,          pV R,          pV R,          pVP                  4       pWW,          pWHV,          ,
          P                  4       p	RV	,          p
RV,          pV) Wy,          ,          p\        P                  ! V
\        P
                  ! V
4      WË.RR7      P                  W^^4      p\        P                  ! WÐR,          P                  W^^4      .^R7      # )	ao	  Convert ellipses in the Oxford ``[x, y, a, b, c]`` format to upright LAFs.

``laf = ellipse_to_laf(ells)`` takes ``(B, N, 5)`` ellipses ``[x, y, a, b, c]``, as the Oxford affine-region files
write them, and returns the upright ``(B, N, 2, 3)`` LAFs of those regions: centred on ``(x, y)``, with an
orientation of 0. To draw the region of a LAF, use :func:`laf_to_boundary_points`.

Convention:
    - An ellipse ``[x, y, a, b, c]`` is the region :math:`a u^2 + 2 b u v + c v^2 \le 1` in the coordinates
      ``(u, v)`` relative to its centre ``(x, y)``, as in the Oxford affine-region files. ``(x, y)`` becomes the
      LAF centre unchanged.
    - ``A`` is the lower-triangular matrix with a positive diagonal and ``A @ A.T == inverse([[a, b], [b, c]])``:
      the Cholesky factor of the inverse ellipse matrix, as VLFeat's ``vl_frame2oell.m`` builds it, not the
      symmetric inverse square root (the two differ by a rotation). Either one maps the unit circle onto the
      ellipse; the lower-triangular one is what :func:`~kornia.feature.make_upright` returns, up to its
      stabilizers, for any LAF of that region.
    - The conversion checks only the shape ``(B, N, 5)``; it does not check the ellipse values and does not
      raise on them. An ellipse that is degenerate or indefinite (``a``, ``c`` or ``a * c - b * b`` not positive)
      is not a bounded region; its LAF has ``inf`` or ``nan`` entries, or huge finite ones where rounding leaves
      ``a - b * b / c`` barely positive. Rounding also works the other way: a nearly singular valid ellipse can
      give ``inf`` or ``nan``. :func:`~kornia.feature.laf_is_valid` screens out the ``inf`` and ``nan`` results,
      which an ``isnan`` test misses for ``inf``; the huge finite ones pass it, so check the ellipse itself where
      that matters.

See also https://github.com/vlfeat/vlfeat/blob/master/toolbox/sift/vl_frame2oell.m

Args:
    ells: torch.Tensor ``(B, N, 5)`` of ellipses in Oxford format [x y a b c].

Returns:
    LAF ``(B, N, 2, 3)``

See Also:
    - :func:`laf_to_boundary_points`: points on the outline of a LAF's region, to draw it.
    - :func:`make_upright`: the same upright LAF, from any LAF of the region.
    - :func:`laf_from_center_scale_ori`: circular LAFs from keypoint centres, scales and orientations.

Example:
    >>> input = torch.ones(1, 10, 5)  # BxNx5
    >>> output = ellipse_to_laf(input)  #  BxNx2x3

ç      ð?r9   )r_   r`   Ú5).rƒ   ).:r„   é   N).:r—   é   Nr=   ©.rW   )r	   rZ   r/   r   Ústackr‰   r[   rt   )r“   r_   r`   Ú_ÚaÚbÚcÚsqrt_cÚb_scaledÚ
sqrt_schurÚinv11Úinv22Úinv21ÚAs   &             r   Úellipse_to_lafr¦   é  sÞ   € ôT �tš_Ô-Ø�j‰j�G€Aˆ!ð 	ˆX�€AØˆX�€AØˆX�€AØ�V‰V‹X€FØ�z€HØ Õ)Õ)×/Ñ/Ó1€JØ�*Õ€EØ�&�L€EØˆI˜Õ,Õ-€EÜ�Š�UœE×,Ò,¨UÓ3°UÐBÈÔK×PÑPÐQRÐWXÐZ[Ó\€AÜ�9Š9�a˜g�×+Ñ+¨A°!°QÓ7Ð8¸aÔ@Ð@r   c                ód   € V ^8„  d   QhR\         P                  R\        R\         P                  /# )r   r"   Ún_ptsr   ©r   r$   Úint)r   s   "r   r   r   +  s.   € ÷ -Wñ -W¤§¡ð -W´Sð -WÄ%Ç,Á,ñ -Wr   c           
     óÖ  € \        V 4       V P                  4       w  r# p\        P                  ! V P                  \        P
                  4      p\        P                  ! ^ ^\        P                  ,          V^,
          VR7      p\        P                  ! \        P                  ! V4      P                  R4      \        P                  ! V4      P                  R4      \        P                  ! V^,
          ^VR7      .^R7      p\        P                  ! \        P                  ! . ROVR7      P                  ^^4      V.^ R7      pVP!                  V P"                  V P                  R7      P%                  4       P                  ^ 4      P'                  W#,          ^V4      p\        P(                  ! V P                  R^^4      V4      P+                  ^ ^^4      P-                  W#V^4      # )a…  Sample points on the outline of each LAF's region, after its centre, to draw it.

``pts = laf_to_boundary_points(laf, n_pts)`` takes ``(B, N, 2, 3)`` LAFs and returns ``(B, N, n_pts, 2)`` points
``(x, y)`` in the LAF's units: the centre, then ``n_pts - 1`` points around the ellipse ``c + A u`` over the unit
vectors ``u``. Drawn as one line, the points of a LAF show its region and a radius from the centre to the tip of
the patch's y axis. For the centre and the tips of both axes only, use :func:`laf_to_three_points`.

Convention:
    - The first point is the centre ``c``. The other ``n_pts - 1`` points are ``c + A @ (sin t, cos t)`` for ``t``
      from 0 to :math:`2 \pi` in equal steps: they start and end at ``c + A[:, 1]``, the tip of the patch's y
      axis, and so close the outline of the region.

Args:
    LAF: ``(B, N, 2, 3)``
    n_pts: number of points to output, the centre included.

Returns:
    torch.Tensor of boundary points LAF: ``(B, N, n_pts, 2)``

See Also:
    - :func:`laf_to_three_points`: only the centre and the tips of the patch's two axes.
    - :func:`ellipse_to_laf`: the LAF of an ellipse given by its coefficients.

r   r9   rn   r=   )ç        r¬   r•   )r   Úsizer   Úpromote_typesr   r   ÚlinspaceÚmathÚpirt   ÚsinrP   Úcosrr   Útensorr[   r-   ro   ÚtÚexpandr]   Úpermuter^   )r"   r¨   r_   r`   r›   ÚbuildÚanglesÚptss   &&      r   Úlaf_to_boundary_pointsr»   +  sd  € ô2 �SÔØ—‘“�J€Aˆ!ˆQô ×Ò §	¡	¬5¯=©=Ó9€EÜ�^Š^˜A˜q¤4§7¡7�{¨E°A­I¸UÔC€FÜ
�)Š)Ü	�Š�6Ó	×	$Ñ	$ RÓ	(¬%¯)ª)°FÓ*;×*EÑ*EÀbÓ*IÌ5Ï:Ê:ÐV[Ð^_ÕV_ÐabÐjoÔKpÐqÐwxô€Cô �)Š)”U—\’\¢/¸Ô?×DÑDÀQÈÓJÈCÐPÐVWÔ
X€Cð �&‰&˜Ÿ
™
¨#¯)©)ˆ&Ó
4×
6Ñ
6Ó
8×
BÑ
BÀ1Ó
E×
LÑ
LÈQÍUÐTUÐW\Ó
]€Cô �9Š9�S—X‘X˜b ! QÓ'¨Ó-×5Ñ5°a¸¸AÓ>×FÑFÀqÈUÐTUÓVÐVr   c          
      óÊ   € V ^8„  d   QhR\         P                  R\        R\        \        \        \
        ,          ,          \        \        \
        ,          ,          3,          /# )r   r"   Úimg_idxr   )r   r$   rª   r   r   r{   )r   s   "r   r   r   [  sF   € ÷ >ñ >œUŸ\™\ð >´Cð >ÄÄdÌ4ÔPUÍ;ÕFWÔY]Ô^bÔchÕ^iÕYjÐFjÕ@kñ >r   c                ó  € \        V 4       \        WV^,            4      ^ ,          pVP                  4       P                  ^^ ^4      P	                  4       pVR,          P                  4       VR,          P                  4       3# )aþ  Return list for drawing LAFs (local features).

Args:
    LAF: ``(B, N, 2, 3)``
    img_idx: the index of the image whose LAFs are drawn.

Returns:
    the lists ``x`` and ``y`` of the boundary points of ``laf_to_boundary_points`` for that image, each 50 lists
    of ``N`` coordinates, so that ``plt.plot(x, y)`` draws one line per LAF.

Examples:
    x, y = get_laf_pts_to_draw(LAF, img_idx)
    plt.figure()
    plt.imshow(kornia.image.tensor_to_image(img[img_idx]))
    plt.plot(x, y, 'r')
    plt.show()

©.r   ©.r(   )r   r»   Údetachr·   ÚcpuÚtolist)r"   r½   rº   Úpts_nps   &&  r   Úget_laf_pts_to_drawrÅ   [  sl   € ô( �SÔÜ
  ¨w¸­{Ð!;Ó
<¸QÕ
?€CØ�Z‰Z‹\×!Ñ! ! Q¨Ó*×.Ñ.Ó0€FØ�6�N×!Ñ!Ó# V¨F¥^×%:Ñ%:Ó%<Ð=Ð=r   c                óx   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  /# ©r   r"   Úimagesr   r#   )r   s   "r   r   r   u  s-   € ÷ &%ñ &%œŸ™ð &%¬u¯|©|ð &%ÄÇÁñ &%r   c           	     ót  € \        V 4       VP                  4       w   r#p\        \        V^,
          ^4      4      p\        \        V^,
          ^4      4      p\	        We4      p\
        P                  ! ^^^^V P                  V P                  R7      V,          pWXR&   WhR&   VP                  V 4      V ,          # )al  Convert LAFs from the frame of normalize_laf back to the pixels of an image.

``laf = denormalize_laf(nlaf, images)`` takes ``(B, N, 2, 3)`` LAFs in the frame of :func:`normalize_laf` and an
image tensor ``(B, CH, H, W)``, read for its height and width only, and returns the ``(B, N, 2, 3)`` LAFs in that
image's pixels: the centre multiplied by ``(max(W - 1, 1), max(H - 1, 1))`` and ``A`` by the smaller of the two.
A singleton axis (``H == 1`` or ``W == 1``) has no spatial extent and counts as one pixel, so the conversion stays
finite and round-trips with :func:`normalize_laf`. An image of another size than the one the LAFs were normalized
on moves them to its resolution.

Convention:
    See the Convention block on :func:`~kornia.feature.normalize_laf`, which this inverts.

Args:
    LAF: ``(B, N, 2, 3)``
    images: ``(B, CH, H, W)``

Returns:
    the denormalized LAF: ``(B, N, 2, 3)``, scale in pixels

See Also:
    - :func:`normalize_laf`: the inverse, from pixels to this frame.
    - :func:`extract_patches_from_pyramid`: takes LAFs in the normalized frame with
      ``normalize_lafs_before_extraction=False``.

©r   ro   ©r   r   r   r   ©r   r   r(   r   ©
r   r­   r{   ÚmaxÚminr   rr   r   ro   r†   ©	r"   rÈ   r›   ÚhÚwÚwfÚhfÚmin_sizeÚcoefs	   &&       r   Údenormalize_lafr×   u  s™   € ô4 �SÔØ—‘“�J€A€qˆQô
 
Œs�1�q•5˜!‹}Ó	€BÜ	Œs�1�q•5˜!‹}Ó	€BÜ�2‹{€HÜ�:Š:�a˜˜A˜q¨¯	©	¸#¿*¹*ÔEÈÕP€DØˆÑØˆÑØ�>‰>˜#Ó Õ$Ð$r   c                óx   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  /# rÇ   r#   )r   s   "r   r   r   ž  s-   € ÷ )%ñ )%”u—|‘|ð )%¬U¯\©\ð )%¼e¿l¹lñ )%r   c           	     ó”  € \        V 4       VP                  4       w   r#p\        \        V^,
          ^4      4      p\        \        V^,
          ^4      4      p\	        We4      p\
        P                  ! ^^^^V P                  V P                  R7      V,          pRV,          VR&   RV,          VR&   VP                  V 4      V ,          # )as  Normalize pixel LAFs by the image size: centre to [0, 1], shape by min(W - 1, H - 1).

``nlaf = normalize_laf(laf, images)`` takes ``(B, N, 2, 3)`` LAFs in pixels and an image tensor ``(B, CH, H, W)``,
read for its height and width only, and returns the ``(B, N, 2, 3)`` LAFs with the centre divided by
``(max(W - 1, 1), max(H - 1, 1))`` and ``A`` by the smaller of the two. A singleton axis (``H == 1`` or ``W == 1``)
has no spatial extent and counts as one pixel, so the conversion stays finite instead of dividing by zero.
:func:`denormalize_laf` on an image of another size then moves the LAFs to that resolution.

Convention:
    - The centre becomes ``(x / max(W - 1, 1), y / max(H - 1, 1))``, which lies in ``[0, 1]`` for
      ``0 <= x <= W - 1`` and ``0 <= y <= H - 1``. ``A`` is divided by the smaller of the two denominators as a
      whole, not per axis, and can exceed 1.
    - Taken to an image of another size with :func:`~kornia.feature.denormalize_laf`, ``x`` becomes
      ``x max(W' - 1, 1) / max(W - 1, 1)``, which maps corner to corner when neither width is 1. A resize with
      ``align_corners=False``, the default of :func:`~kornia.geometry.transform.resize` in bilinear mode, maps
      pixel ``x`` to ``(x + 0.5) W' / W - 0.5`` instead, so the two disagree away from the image centre.

Args:
    LAF: ``(B, N, 2, 3)``
    images: ``(B, CH, H, W)``

Returns:
    the normalized LAF: ``(B, N, 2, 3)``

See Also:
    - :func:`denormalize_laf`: the inverse, back to the pixels of an image of any size.
    - :func:`extract_patches_from_pyramid`: takes LAFs in this frame with
      ``normalize_lafs_before_extraction=False``.

rÊ   r•   rË   rÌ   rÍ   rÐ   s	   &&       r   Únormalize_lafrÚ   ž  s¥   € ô> �SÔØ—‘“�J€A€qˆQô 
Œs�1�q•5˜!‹}Ó	€BÜ	Œs�1�q•5˜!‹}Ó	€BÜ�2‹{€HÜ�:Š:�a˜˜A˜q¨¯	©	¸#¿*¹*ÔEÈÕP€DØ˜R•x€DˆÑØ˜R•x€DˆÑØ�>‰>˜#Ó Õ$Ð$r   c                ó„   € V ^8„  d   QhR\         P                  R\         P                  R\        R\         P                  /# )r   Úimgr"   ÚPSr   r©   )r   s   "r   r   r   Ê  s8   € ÷ ñ ´·±ð ÄEÇLÁLð ÔVYð Ôch×coÑcoñ r   c                óÔ  € \        V4       VP                  4       w  r4 pV P                  4       w  rVrx\        W4      p	\        V	P	                  W4,          ^^4      W4,          WbV.4      p
RV
R,          P                  4       ,          R,           \        V4      ,          R,
          V
R&   RV
R,          P                  4       ,          R,           \        V4      ,          R,
          V
R&   V
# )aH  Generate affine grid.

Args:
    img: image torch.Tensor of shape ``(B, CH, H, W)``.
    LAF: laf with shape ``(B, N, 2, 3)``.
    PS: patch size to be extracted.

Returns:
    grid ``(B*N, PS, PS, 2)``. In a caller's autocast region it keeps the LAF's dtype, and a float32 LAF is
    computed in float32, outside TorchScript.

ç       @r•   ).rY   r   ).rY   r(   )r   r­   r×   Ú_affine_grid_outside_autocastr[   r\   r{   )rÜ   r"   rÝ   r_   r`   r›   ÚchrÑ   rÒ   Ú
LAF_renormÚgrids   &&&        r   Ú'generate_patch_grid_from_normalized_LAFrä   Ê  sÀ   € ô �SÔØ—‘“�J€Aˆ!ˆQØ—(‘(“*�K€Aˆ1ô ! Ó*€Jä(¨¯©¸½ÀÀ1Ó)EÈÍÈrÐWYÐGZÓ[€Dð ˜T )�_×2Ñ2Ó4Õ4°sÕ:¼eÀA»hÕFÈÕL€Dˆ�OØ˜T )�_×2Ñ2Ó4Õ4°sÕ:¼eÀA»hÕFÈÕL€Dˆ�OØ€Kr   c                óz   € V ^8„  d   QhR\         P                  R\        \        ,          R\         P                  /# )r   Úthetar­   r   ©r   r$   r   rª   )r   s   "r   r   r   ç  s-   € ÷ 
?ñ 
?¬¯©ð 
?¼TÄ#½Yð 
?Ì5Ï<É<ñ 
?r   c                ó6  € \         P                  P                  4       '       d   \        P                  ! WRR7      # \        V P                  P                  4      ;_uu_ 4        \        P                  ! WRR7      uuRRR4       #   + '       g   i     R# ; i)a„  Return ``F.affine_grid(theta, size, align_corners=False)`` outside a caller's autocast region.

Autocast would run the grid's matrix product in half precision and the patch would be sampled there, 0.54 off on a
``[0, 1]`` image in bfloat16 at 256 px, and would still come back in the image dtype (#6601). TorchScript has no
context managers; a scripted call keeps the caller's precision.
F)Úalign_cornersN)r   ÚjitÚis_scriptingÚFÚaffine_gridr   ro   r   )ræ   r­   s   &&r   rà   rà   ç  sZ   € ô ‡y�y×Ñ×ÒÜ�}Š}˜U¸Ô>Ð>Ü	˜EŸL™L×-Ñ-×	.Õ	.Ü�}Š}˜U¸Ô>÷ 
/×	.×	.Ó	.ús   Á$BÂB	c                óp   € V ^8„  d   QhR\         P                  R\        R\        R\         P                  /# )r   rã   rÑ   rÒ   r   r©   )r   s   "r   r   r   ô  s0   € ÷ 'ñ '¤u§|¡|ð '¼ð 'Äð 'ÌÏÉñ 'r   c                óP  € V R,          P                  RR\        V4      ,          ,           RR\        V4      ,          ,
          4      pV R,          P                  RR\        V4      ,          ,           RR\        V4      ,          ,
          4      p\        P                  ! W4.RR7      # )aé  Clamp a normalized sampling grid to the outermost pixel centers.

MPS does not implement ``padding_mode="border"`` for :func:`torch.nn.functional.grid_sample`,
so the border behavior has to be emulated with zero padding plus a clamped grid. Clamping to
:math:`\pm 1` is *not* equivalent: with ``align_corners=False`` that is the outer **edge** of
the border pixel, i.e. pixel index :math:`-0.5`, where bilinear sampling blends the border
pixel with the zero padding and returns roughly half its value. The outermost pixel **center**
sits at :math:`\pm (1 - 1/\text{size})`, and clamping there reproduces ``padding_mode="border"``
exactly.

Args:
    grid: sampling grid ``(..., 2)`` with any leading batch dimensions, last dimension ordered
        ``(x, y)``. Only 2-D sampling is handled; a 3-D grid would need a third bound from the
        depth of the sampled volume.
    h: height of the sampled image.
    w: width of the sampled image.

Returns:
    the clamped grid, same shape as ``grid``.

r•   r9   r¿   ç      ð¿rÀ   r=   )Úclampr{   r   rš   )rã   rÑ   rÒ   ÚxÚys   &&&  r   Ú_clamp_grid_to_pixel_centersrô   ô  sw   € ð, 	ˆV�×Ñ˜4 #¬¨a«¥.Õ0°#¸¼eÀA»h½Õ2FÓG€AØˆV�×Ñ˜4 #¬¨a«¥.Õ0°#¸¼eÀA»h½Õ2FÓG€AÜ�;Š;˜�v 2Ô&Ð&r   c          
      ó�   € V ^8„  d   QhR\         P                  R\         P                  R\        R\        R\         P                  /# ©r   rÜ   rã   rÑ   rÒ   r   r©   )r   s   "r   r   r     sE   € ÷ Pñ PœeŸl™lð P´%·,±,ð PÄ3ð PÌ3ð PÔSX×S_ÑS_ñ Pr   c                ó²   € V P                   P                  R8X  d%   \        P                  ! V \	        WV4      RRR7      # \        P                  ! WRRR7      # )uÞ  Run ``grid_sample`` with border padding, robust across devices.

MPS does not implement ``padding_mode="border"``; it is emulated with a clamped grid plus
zero padding (see :func:`_clamp_grid_to_pixel_centers`). ``img`` and ``grid`` share a dtype:
the extractors upcast reduced-precision inputs to float32 once, before their chunk loops.
That upcast is deliberate on every torch version, not only the torch <= 2.9 builds whose
float16/bfloat16 CPU kernel reads out of bounds at the border â€” half-precision sampling
coordinates also quantize to whole pixels on large images. It is a real trade on CUDA, where
the native half kernels are fine: float16 ``extract_patches_simple`` pays roughly a 2x
slowdown at high N for the accuracy.
Úmpsrs   F)Úpadding_moderé   Úborder)ro   r   rì   Úgrid_samplerô   )rÜ   rã   rÑ   rÒ   s   &&&&r   Ú_grid_sample_patchesrü     sF   € ð ‡z�z‡�˜%ÔÜ�}Š}˜SÔ">¸tÈÓ"JÐY`ÐpuÔvÐvÜ�=Š=˜°ÈÔOÐOr   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# r   r   )r   s   "r   r   r      s&   € ÷ Pñ P”u—{‘{ð P¤u§{¡{ñ Pr   c                óp   € V \         P                  \         P                  39   d   \         P                  # T # )z9Return the sampling-grid dtype for an image or LAF dtype.)r   r   Úbfloat16r   r   s   &r   Ú_grid_dtyper      s%   € à!¤e§m¡m´U·^±^Ð%DÔDŒ5�=‰=ÐOÈ%ÐOr   c                óx   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  /# )r   Úimage_dtypeÚ	laf_dtyper   r   )r   s   "r   r   r   %  s2   € ÷ Dñ D¤e§k¡kð D¼e¿k¹kð DÌeÏkÉkñ Dr   c                ó@   € \        \        P                  ! W4      4      # )zJReturn a grid dtype that never discards image or LAF coordinate precision.)r   r   r®   )r  r  s   &&r   Ú_promoted_grid_dtyper  %  s   € ä”u×*Ò*¨;ÓBÓCÐCr   c                óD   € V ^8„  d   QhR\         P                  R\        /# r   )r   r   rª   )r   s   "r   r   r   *  s   € ÷ ;ñ ;œEŸK™Kð ;¬Cñ ;r   c                óF   € \        V 4      \        P                  8X  d   ^# ^# )z@Bytes per element after applying the sampling-grid dtype policy.)r   r   Úfloat64r   s   &r   Ú_grid_elem_bytesr	  *  s   € ä˜EÓ"¤e§m¡mÔ3ˆ1Ð:¸Ð:r   c                ól   € V ^8„  d   QhR\         R\         R\         R\         R\         R\         R\         /# )r   r_   r`   rá   rÝ   Ú	elem_sizeÚbudgetr   )rª   )r   s   "r   r   r   /  s>   € ÷ -ñ -œð -¤ð -¬ð -´#ð -Ä#ð -Ìsð -Ôjmñ -r   c                óˆ   € W,          V,          \        ^V4      ,          V,          p\        V\        ^WV,          4      4      # )a%  Largest LAF count whose folded grid and sampled chunk each fit the byte budget.

The sampling grid and its pointwise intermediates scale with :math:`B \cdot N \cdot PS^2`,
so extraction is chunked along N to bound peak memory, in the spirit of
:func:`kornia.core.utils.batched_forward`. Both the two-coordinate folded grid and the
channel-scaled ``grid_sample`` result are individually kept within the budget; pointwise remap
temporaries can still make the real peak a multiple of it. At least one LAF per chunk; when
everything fits the budget the loop degenerates to the single-call fast path. The default
budget is a defaulted argument rather than a module constant because TorchScript cannot close
over module-level ints; tests monkeypatch this function to force multi-chunk sampling on small
inputs.
)rÎ   rÏ   )r_   r`   rá   rÝ   r  r  Úper_lafs   &&&&&& r   Ú_grid_chunk_lafsr  /  s6   € ð �f�r�kœC  2›JÕ&¨Õ2€GÜˆq”#�a˜Õ*Ó+Ó,Ð,r   c                ó<   € V ^8„  d   QhR\         R\         R\        /# )r   Úatlas_bytesr  r   )rª   Úbool)r   s   "r   r   r   @  s!   € ÷ !ñ !¤Sð !´#ð !Ìdñ !r   c                ó
   € W8*  # )a  Return whether a packed pyramid atlas fits its default memory budget.

The budget is a defaulted argument because TorchScript cannot close over module-level integer
constants. Keeping the policy in a helper also gives tests a narrow seam for forcing either
extraction path.
© )r  r  s   &&r   Ú_pyramid_atlas_fitsr  @  s   € ð Ñ Ð r   c          
      ó�   € V ^8„  d   QhR\         P                  R\         P                  R\        R\        R\         P                  /# rö   r©   )r   s   "r   r   r   J  sB   € ÷ añ aœŸ™ð a¬U¯\©\ð a¼cð aÄcð aÌeÏlÉlñ ar   c                ó  € VP                  ^ 4      VP                  ^4      VP                  ^4      repV P                  ^4      pVP                  WEV,          V^4      p\        WW#4      P                  WGWVV4      P                  ^ ^^^^4      # )a  Sample one patch per LAF with a single ``grid_sample`` call.

The per-LAF grids ``(B, N, PS, PS, 2)`` are folded to ``(B, N * PS, PS, 2)`` so
one call covers the whole batch, without a Python loop over B or a ``(B*N, CH, H, W)`` input
copy. ``grid`` must already live on ``img``'s device: the extractors move a cross-device LAF
to the image's device up front, so the grid is built there.

Returns:
    patches ``(B, N, CH, PS, PS)`` as a permuted view; assigning it or calling
    ``.contiguous()`` makes the copy.
)r­   r[   rü   r·   )	rÜ   rã   rÑ   rÒ   r_   r`   rÝ   rá   Úfoldeds	   &&&&     r   Ú_sample_patchesr  J  s~   € ð �y‰y˜‹|˜TŸY™Y q›\¨4¯9©9°Q«<ˆ"€AØ	�‰�!‹€BØ�Y‰Y�q˜b�& " aÓ(€FÜ ¨QÓ2×7Ñ7¸¸qÀbÓI×QÑQÐRSÐUVÐXYÐ[\Ð^_Ó`Ð`r   c          
      ó¦   € V ^8„  d   QhR\         P                  R\        R\        R\        \         P                  \         P                  3,          /# )r   ÚnlafrÑ   rÒ   r   )r   r$   rª   r   )r   s   "r   r   r   \  sA   € ÷ ñ œeŸl™lð ¬sð ´sð ¼uÄUÇ\Á\ÔSX×S_ÑS_ÐE_Õ?`ñ r   c                ó:  € \        \        V^,
          ^4      4      \        \        V^,
          ^4      4      rC\        W44      p\        RV,          \        V4      ,          RV,          \        V4      ,          .V P                  V P
                  R7      p\        W4.V P                  V P
                  R7      p\        \        V4      \        V4      .V P                  V P
                  R7      pRV R,          ,          V,          R,           V,          R,
          p	Wi3# )aO  Return the scale ``k`` and translation ``t`` that map a normalized LAF's patch grid to sampling coordinates.

``grid = affine_grid(A, align_corners=False) * k + t`` addresses, for ``grid_sample(align_corners=False)``, the
input pixels the LAF describes: pixel :math:`x` of the :math:`(h, w)` input sits at :math:`(2x + 1) / w - 1`.
``pyrdown`` resizes to ``floor(side / 2)`` with ``align_corners=False``, so input pixel :math:`x` is pixel
:math:`(x + 0.5) w_l / w - 0.5` of level :math:`l` -- which that level's ``grid_sample`` addresses at the same
:math:`(2x + 1) / w - 1`. One grid therefore serves every pyramid level.

Args:
    nlaf: normalized LAFs ``(B, N, 2, 3)`` (``normalize_laf``'s frame).
    h: input height.
    w: input width.

Returns:
    ``k`` of shape ``(2,)`` and ``t`` of shape ``(B, N, 2)``, in ``nlaf``'s dtype and device.
rß   rn   r•   ).rY   r   )r{   rÎ   rÏ   r
   ro   r   )
r  rÑ   rÒ   rÓ   rÔ   rÕ   Úkr3   Úextentrµ   s
   &&&       r   Ú_pyramid_grid_framer  \  sÓ   € ô$ ”3�q˜1•u˜a“=Ó!¤5¬¨Q°­U°A«Ó#7ˆÜ�2‹{€Hô
 	˜˜x�¬%°«(Õ2°C¸(µNÄUÈ1ÃXÕ4MÐNÐW[×WbÑWbÐjn×jtÑjtÔu€AÜ˜R˜H¨T¯[©[ÀÇ
Á
ÔK€EÜœe A›h¬¨a«Ð1¸$¿+¹+ÈTÏZÉZÔX€FØ	ˆt�I�Õ	 Õ	&¨Õ	,°Õ6¸Õ<€AØˆ4€Kr   c                óè   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  R\        \        ,          R\        \        ,          R\        R\         P                  /# )r   rÜ   r  Úpyr_idxÚheightsÚwidthsrÝ   r   rç   )r   s   "r   r   r   {  sf   € ÷ <ñ <Ü	�‰ð<ä
�,‰,ð<ô �\‰\ð<ô ”#�Yð	<ô
 ”�Ið<ô 	ð<ô ‡\�\ñ<r   c                ó0  € VP                   R,          w  rgV P                   ^,          p\        V P                  VP                  4      p	VP                  V	8w  d   VP                  V	4      MTp
\        P
                  ! WgW…WPP                  V P                  R7      p\        WgW…\        V	4      4      pV P                  V
P                  8w  d   V P                  V
P                  4      MT pV
R,          p\        W£^ ,          V^ ,          4      w  pp\        P                  ! ^ W‘P                  R7      pWÇ8X  dz   \        P                  ! V\        P
                  ! Wg^^W‘P                  R7      .RR7      p\        VP                  Wg,          ^^4      Wg,          W…V.4      P                  WgWU^4      p\        \        W44      4       EF¹  w  pw  ppV^ 8”  d<   \!        VP                  P"                  4      ;_uu_ 4        \%        V4      pRRR4       \'        ^ W|4       EF\  p\)        VV,           V4      pVV,
          pWÇ8X  d   TpMˆ\        P                  ! VRVV13,          \        P
                  ! VV^^W‘P                  R7      .RR7      p\        VP                  VV,          ^^4      VV,          W…V.4      P                  VVWU^4      pVRVV13,          P                  VV^^^4      pVV,          V,           p\+        VVVV4      P                  V P                  4      pVRVV13,          V8H  P                  VVV,
          ^^^4      p\        P,                  ! VVVRVV13,          4      VRVV13&   EK_  	  EK¼  	  V#   + '       g   i     EL…; i)aÂ  Sample each pyramid level separately when a single atlas would be too large.

Patches accumulate on the image's device and dtype, like the atlas path: the callers move a
cross-device LAF to the image's device before the level index is derived, and
reduced-precision levels are upcast once, before the loops, so no full level is re-cast per
chunk. Out-of-range level indices (the -1 marking a non-finite LAF) match no level and keep
their zero patch.
rW   rÊ   r9   NrY   r™   r=   )rZ   r  r   r-   r   rs   ro   r  r	  r  Úemptyrt   rà   r[   Ú	enumerateÚzipr   r   r   ÚrangerÏ   r  r‡   )rÜ   r  r!  r"  r#  rÝ   r_   r`   rá   Ú
grid_dtypeÚgrid_lafr2   ÚchunkÚcur_imgÚlaf_ar  rµ   Úbase_grid_allræ   Ú	level_idxÚh_lÚw_lÚstÚenÚncÚ	base_gridÚtranslationrã   ÚpatchesÚmasks   &&&&&&                        r   Ú'_extract_patches_from_pyramid_levelwiser9  {  s  € ð  �:‰:�b�>�D€AØ	�‰�1�€BÜ% c§i¡i°·±Ó<€JØ&*§j¡j°JÔ&>ˆt�w‰w�zÔ"ÀD€HÜ
�+Š+�a˜B B¯i©iÀÇ
Á
Ô
K€CÜ˜Q 2Ô+;¸JÓ+GÓH€EØ(+¯	©	°X·^±^Ô(Cˆc�f‰f�X—^‘^Ô$È€GØ�WÕ€EÜ˜x°­°V¸AµYÓ?�D€A€qô —K’K ¨¿K¹KÔH€MØ„zÜ—	’	˜5¤%§+¢+¨a°A°qÀ
×S^ÑS^Ô"_Ð`ÐfhÔiˆÜ5°e·j±jÀÅÈÈ1Ó6MÐPQÕPUÐWYÐ_aÐObÓc×hÑhØ�"˜!ó
ˆô "+¬3¨wÓ+?×!@Ñˆ	‘:�C˜Ø�qŒ=ô /¨w¯~©~×/BÑ/B×CÕCÜ! 'Ó*�÷ Dä˜˜1×$ˆBÜ�R˜%•Z Ó#ˆBØ�b•ˆBØŒzØ)‘	äŸ	š	Ø˜1˜b ˜e˜8•_¤e§k¢k°!°R¸¸AÀZ×XcÑXcÔ&dÐeÐkmô�ô :¸%¿*¹*ÀQÈÅVÈQÐPQÓ:RÐUVÐY[ÕU[Ð]_ÐegÐThÓi×nÑnØ�r˜2 1ó�	ð ˜A˜r "˜u˜H�+×*Ñ*¨1¨b°!°Q¸Ó:ˆKØ˜q•= ;Õ.ˆDÜ% g¨t°S¸#Ó>×AÑAÀ#Ç)Á)ÓLˆGØ˜A˜r "˜u˜HÕ%¨Ñ2×8Ñ8¸¸BÀ½GÀQÈÈ1ÓMˆDÜ!ŸKšK¨¨g°s¸1¸bÀ¸e¸8µ}ÓEˆC��2�b�5�ŒMô! %ñ "Að. €J÷' D×CÐCús   Ç<NÎNc                óœ   € V ^8„  d   QhR\         P                  R\         P                  R\        R\        R\        R\         P                  /# )r   rÜ   r7   r_   r`   rÝ   r   r©   )r   s   "r   r   r   º  sM   € ÷ ^ñ ^œŸ™ð ^¬5¯<©<ð ^¼Cð ^ÄCð ^ÌSð ^ÔUZ×UaÑUañ ^r   c           
     ó`  € V P                  4       R,          P                  4       VP                  4       R,          P                  4       P                  V P                  4      ,           p\        P
                  ! W#V P                  ^,          WDV P                  V P                  R7      V,           # )a%  Zero patches ``(B, N, CH, PS, PS)`` of an empty batch or an empty LAF set, linked to ``img`` and ``laf``.

The sum of a zero-width slice is a zero that autograd traces back to both inputs, so a loss on the
patches backpropagates (a zero gradient) instead of raising on a tensor with no graph.
:Nr   Nrn   )ÚflattenÚsumr-   r   r   rs   rZ   ro   )rÜ   r7   r_   r`   rÝ   Úlinks   &&&&& r   Ú_empty_patchesr?  º  sr   € ð �;‰;‹=˜Õ× Ñ Ó" S§[¡[£]°2Õ%6×%:Ñ%:Ó%<×%?Ñ%?ÀÇ	Á	Ó%JÕJ€DÜ�;Š;�q˜SŸY™Y q�\¨2¸#¿*¹*ÈCÏIÉIÔVÐY]Õ]Ð]r   c          
      ó�   € V ^8„  d   QhR\         P                  R\         P                  R\        R\        R\         P                  /# ©r   rÜ   r7   rÝ   Ú normalize_lafs_before_extractionr   ©r   r$   rª   r  )r   s   "r   r   r   Ä  sG   € ÷ >Cñ >CÜ	�‰ð>CÜ!ŸL™Lð>CÜ.1ð>CÜZ^ð>Cä
‡\�\ñ>Cr   c           
     ó€  € \        V4       \        V P                  ^ 4      VP                  ^ 4      8H  R4       VP                  V P                  R7      p\        V P                  VP                  4      pVP                  V8w  d   VP                  V4      MTpV'       d   \        W4      MTpV P                  4       w  rgr‰VP                  4       w  r« pV
^ 8X  g   V^ 8X  d   \        WW«V4      # \        P                  ! V4      P                  RR7      P                  RR7      ( pVP                  VP                  W«^^4      R4      pV P                  V8w  d   V P                  V4      MT p\        P                  ! W«WrW P                  V P                  R7      p\        W«Wr\!        V4      4      p\#        ^ W¿4       FZ  p\%        VV,           V4      p\'        WRVV13,          V4      P                  V
VV,
          W"^4      p\)        VVW‰4      VRVV13&   K\  	  VP+                  VP                  W«^^^4      R4      # )a®  Sample a patch per LAF from the full-resolution image only, without anti-aliasing.

``patches = extract_patches_simple(img, laf, PS)`` takes images ``(B, CH, H, W)`` and their LAFs ``(B, N, 2, 3)``
in pixels and returns one ``PS x PS`` patch per LAF, ``(B, N, CH, PS, PS)`` in the image dtype, sampled
bilinearly from ``img`` at the positions that :func:`extract_patches_from_pyramid` samples. For LAFs of a scale
below ``PS`` the two return the same patches up to rounding; a larger LAF is not smoothed first, so its patch
aliases. For patches to describe, orient or adapt, use :func:`extract_patches_from_pyramid` instead, as
:class:`LAFDescriptor`, :class:`LAFOrienter` and the affine shape estimators do.

Convention:
    See the Convention block on :func:`~kornia.feature.extract_patches_from_pyramid`. This function samples the
    same positions, always from ``img`` itself: a LAF larger than the patch is not smoothed first, so it aliases.

Args:
    img: images, LAFs are detected in  ``(B, CH, H, W)``.
    laf: ``(B, N, 2, 3)``.
    PS: patch size.
    normalize_lafs_before_extraction: if True, lafs are normalized to image size; if False, ``laf`` must already
        be in the frame that :func:`~kornia.feature.normalize_laf` gives for ``img``.

Returns:
    patches with shape ``(B, N, CH, PS,PS)``.

See Also:
    - :func:`extract_patches_from_pyramid`: samples each LAF from a pyramid level chosen by its scale to limit
      aliasing.

ú)img and laf must have the same batch size©ro   r9   r¬   rn   rY   r=   )r   r   r­   r-   ro   r  r   rÚ   r?  r   r>   r?   Úmasked_fillr[   r%  r  r	  r(  rÏ   rä   r  Úmasked_fill_)rÜ   r7   rÝ   rB  r)  r  r›   rá   rÑ   rÒ   r_   r`   Úinvalid_lafsÚ
sample_imgr2   r+  r2  r3  rã   s   &&&&               r   Úextract_patches_simplerK  Ä  sì  € ô> �SÔÜ�—‘˜!“ §¡¨£Ñ+Ð-XÔYð �&‰&˜Ÿ
™
ˆ&Ó
#€CÜ% c§i¡i°·±Ó;€JØ #§	¡	¨ZÔ 7ˆ#�&‰&�Ô
¸S€Cß&FŒ=˜Ô"ÈC€DØ—(‘(“*�K€Aˆ1Ø—‘“�J€Aˆ!ˆQØˆA„v��a”Ü˜c¨¨bÓ1Ð1ô —N’N 4Ó(×,Ñ,°Ð,Ó4×8Ñ8¸RÐ8Ó@Ð@€LØ×Ñ˜L×-Ñ-¨a°A°qÓ9¸3Ó?€Dð (+§y¡y°JÔ'>�—‘˜
Ô#ÀC€JÜ
�+Š+�a˜B B¯z©zÀÇÁÔ
K€CÜ˜Q 2Ô+;¸JÓ+GÓH€EÜ�A�qÖ ˆÜ��e•˜QÓˆÜ6°sÀÀBÀrÀEÀ½NÈBÓO×TÑTÐUVÐXZÐ]_ÕX_ÐacÐijÓkˆÜ'¨
°D¸!Ó?ˆˆAˆr�"ˆuˆH‹ñ !ð ×Ñ˜L×-Ñ-¨a°A°q¸!Ó<¸cÓBÐBr   c          
      ó�   € V ^8„  d   QhR\         P                  R\         P                  R\        R\        R\         P                  /# rA  rC  )r   s   "r   r   r     sN   € ÷ pDñ pDÜ	�‰ðpDÜ!ŸL™LðpDÜ.1ðpDÜZ^ðpDä
‡\�\ñpDr   c                óÒ  € \        V4       \        V P                  ^ 4      VP                  ^ 4      8H  R4       VP                  V P                  R7      p\        V P                  VP                  4      pVP                  V8w  d   VP                  V4      MTpV'       d   \        W4      MTpVP                  4       w  rg pV P                  4       w  r‰r«V^ 8X  g   V^ 8X  d   \        WWgV4      # \        W«4      V,          pV
.pV.p\        ^\        ^V4      4       Fy  p\        VR,          VR,          4      ^8:  d    MYVR,          ^,          pVR,          ^,          p\        VV4      V8  d    M&VP                  V4       VP                  V4       K{  	  \        P                  ! V4      P                  RR7      P                  RR7      ( pVP!                  VP#                  Wg^^4      R4      pR\%        \'        WP4      4      ,          \)        V4      ,          pVP+                  4       P-                  R\)        \/        V4      ^,
          4      R7      P1                  4       P3                  R4      P3                  R4      pVP!                  VR4      p\/        V4      ^8X  d   \5        WVWÞV4      # V
^,           pV Uu. uF  pV^,           NK  	  pp\7        V4      pWi,          V,          V,          pV\9        V4      ,          pV P                  V8w  d.   VWi,          V
,          V,          \9        V4      ,          ,          p\;        V4      '       g   \5        WVWÞV4      # V P                  V8w  d   V P                  V4      MT pVP=                  WiVV4      pTp^ p\?        \A        WÞ4      4       F”  w  pw  ppV^ 8”  d<   \C        VP                  PD                  4      ;_uu_ 4        \G        V4      pRRR4       \H        PJ                  ! VRRR	7      VR
R
RV^,           1VVV,           ^,           13&   VV^,           ,          pK–  	  VR,          P                  V4      p\M        VP                  V4      W«4      w  pp ^ p. p!\A        WÞ4       EF#  w  ppV!P                  RR\)        V4      ,          ,           RR\)        V4      ,          ,           RR\)        V4      ,          ,
          RR\)        V4      ,          ,
          \)        V4      \)        V4      ,          \)        V4      \)        V4      ,          \)        V4      R\)        V^,           4      ,          ,           \)        V4      ,          R,
          \)        V4      R,           \)        V4      ,          R,
          34       VV^,           ,          pEK&  	  \O        V!VP                  VR7      P#                  R^^4      p"\        PP                  ! WgW’W P                  V P                  R7      p#\S        WgW’\9        V4      4      p$VP-                  ^ R7      p%\        ^ VV$4       EF]  p&\        V&V$,           V4      p'V'V&,
          p(\        PT                  ! VR
V&V'13,          \        PV                  ! VV(^^WEP                  R7      .RR7      p)\Y        V)P#                  VV(,          ^^4      VV(,          W’V.4      P#                  VV(W"^4      p*V"V%R
V&V'13,          ,          P#                  VV(^^^^4      P[                  R4      w  p+p,p-p.V*V,          p*V*V R
V&V'13,          P#                  VV(^^^4      ,           p*V*P]                  V+4      p*V*P_                  V,4      p*V*V-,          p*V*V.,           p*\a        VV*VV4      V#R
V&V'13&   EK`  	  V#Pc                  V^ 8  P#                  Wg^^^4      R4      # u upi   + '       g   i     ELå; i)at  Sample a patch per LAF from the image pyramid level that matches its scale.

``patches = extract_patches_from_pyramid(img, laf, PS)`` takes images ``(B, CH, H, W)`` and their LAFs
``(B, N, 2, 3)`` in pixels and returns one ``PS x PS`` patch per LAF, ``(B, N, CH, PS, PS)`` in the image dtype:
the square ``c + A [-1, 1]^2`` resampled from the level of a Gaussian pyramid of ``img`` that matches the LAF's
scale, which limits aliasing. It is the sampler of :func:`get_laf_descriptors`,
:class:`LAFOrienter` and the affine shape estimators. With ``normalize_lafs_before_extraction=False``, ``laf`` is
read in the frame of :func:`normalize_laf`. To sample the full-resolution image only, use
:func:`extract_patches_simple`.

Convention:
    - Cell ``(i, j)`` of a ``PS x PS`` patch samples the image at ``c + A @ (u_j, u_i)``, with
      ``u_k = (2 k + 1) / PS - 1`` and the LAF ``[A | c]`` in pixels, pixel centres at integers. Row 0 is on the
      patch's ``-y`` side, the top for an upright LAF, the columns run along the patch's x axis, and the cells
      tile the square ``c + A [-1, 1]^2``. For an odd ``PS``, a LAF with ``A = (PS / 2) I`` centred on a pixel
      returns the image crop around that pixel.
    - The pyramid level is ``floor(log2(2 s / PS))`` for the scale ``s = sqrt(|det A|)``, clamped to the levels
      that exist: :func:`~kornia.geometry.transform.pyrdown` builds them while the shorter side stays at least
      ``PS``, so a larger LAF is sampled from the coarsest level that can still provide a full patch. Level 0,
      the image itself, always exists: an image whose shorter side is below ``PS`` has only that level, so even a
      large LAF is sampled from it. The level uses the geometric-mean scale, so a highly anisotropic LAF can
      still alias along its long axis. A level samples the same image positions as level 0, in its own pixels.
    - A cell outside the image reads the nearest border pixel of the level it samples.
    - A caller's autocast region does not change the sampling grid or the pyramid, outside TorchScript. Under
      ``torch.compile`` on MPS it still changes the pyramid: a convolution under the guard raises there, so
      :func:`~kornia.geometry.transform.pyrdown` runs in the region's dtype.
    - The patches have the image's dtype. The sampling runs in the promoted dtype of the image and the LAF, and
      in at least ``float32``. A LAF with a non-finite entry gives a zero patch.

Args:
    img: images, LAFs are detected in  ``(B, CH, H, W)``.
    laf: ``(B, N, 2, 3)``.
    PS: patch size.
    normalize_lafs_before_extraction: if True, lafs are normalized to image size; if False, ``laf`` must already
        be in the frame that :func:`~kornia.feature.normalize_laf` gives for ``img``.

Returns:
    patches with shape ``(B, N, CH, PS,PS)``.

See Also:
    - :func:`extract_patches_simple`: the same positions, always sampled from the full-resolution image.
    - :func:`get_laf_descriptors`: describes the patches that this samples with a patch descriptor.
    - :func:`laf_is_inside_image`: keeps the LAFs whose region lies inside the image, though the corners of
      their patches can reach beyond it.

rE  rF  r9   r¬   rß   )rÏ   rÎ   NÚ	replicate)ÚmoderY   r•   rn   )rÏ   rÊ   r=   )r(   r(   r(   r(   r™   rð   éþÿÿÿ)2r   r   r­   r-   ro   r  r   rÚ   r?  rÏ   r(  rÎ   Úappendr   r>   r?   rG  r[   r4   r×   r{   Úlog2rñ   ÚlenÚlongru   r9  r=  r	  r  Ú	new_zerosr&  r'  r   r   r   rì   Úpadr  r
   r%  r  rt   rs   rà   ÚunbindÚmaximumÚminimumr  rH  )/rÜ   r7   rÝ   rB  r)  r  r_   r`   r›   rá   rÑ   rÒ   Ú	max_levelr"  r#  r0  r1  rI  r3   r!  Úatlas_hÚpacked_widthsÚatlas_wÚatlas_elementsr  rJ  Úatlasr,  Úxoffr/  r-  r  rµ   Ú	constantsÚlevel_constantsr2   r+  Úsafe_pyr_idxr2  r3  r4  ræ   rã   ÚloÚhiÚlevel_scaleÚlevel_offsets/   &&&&                                           r   Úextract_patches_from_pyramidrh    sÁ  € ôb �SÔÜ�—‘˜!“ §¡¨£Ñ+Ð-XÔYð �&‰&˜Ÿ
™
ˆ&Ó
#€CÜ% c§i¡i°·±Ó;€JØ #§	¡	¨ZÔ 7ˆ#�&‰&�Ô
¸S€Cß&FŒ=˜Ô"ÈC€DØ—‘“�J€Aˆ!ˆQØ—(‘(“*�K€Aˆ1ØˆA„v��a”Ü˜c¨¨bÓ1Ð1ä�A“	˜R•€Ið ˆc€GØˆS€FÜ�1”c˜!˜YÓ'Ö(ˆô ˆw�r�{˜F 2�JÓ'¨1Ô,ÙØ�b�k˜QÕˆØ�R�j˜A�oˆÜˆs�C‹=˜2ÔÙØ�‰�sÔØ�‰�cÖñ )ô  —N’N 4Ó(×,Ñ,°Ð,Ó4×8Ñ8¸RÐ8Ó@Ð@€LØ×Ñ˜L×-Ñ-¨a°A°qÓ9¸3Ó?€DØ”-¤°Ó :Ó;Õ;¼eÀB»iÕG€EØ�j‰j‹l× Ñ  S¬e´C¸³LÀ1Õ4DÓ.EÐ ÓF×KÑKÓM×UÑUÐVXÓY×aÑaÐbdÓe€GØ×!Ñ! ,°Ó3€Gô ˆ7ƒ|�qÔÜ6°sÀ'È7Ð\^Ó_Ð_ð
 �!�e€GÙ(.Ó/© �S˜1—W�W©€MÐ/Ü�-Ó €Gð •V˜gÕ%¨Õ/€NØ Ô#3°JÓ#?Õ?€KØ
‡y�y�JÔØ�q•v •z A•~Ô(8¸Ó(DÕDÕDˆÜ˜{×+Ò+Ü6°sÀ'È7Ð\^Ó_Ð_Ø'*§y¡y°JÔ'>�—‘˜
Ô#ÀC€JØ× Ñ  ¨°Ó9€EØ€GØ€DÜ!*¬3¨wÓ+?Ö!@Ñˆ	‘:�C˜Ø�qŒ=ô /¨w¯~©~×/BÑ/B×CÕCÜ! 'Ó*�÷ Dä89¿º¸gÀ|ÐZeÔ8fˆˆa��I�c˜A•g�I˜t d¨S¥j°1¥nÐ4Ð4Ñ5Ø��a•�Šñ "Að ��M×Ñ˜ZÓ(€EÜ˜tŸw™w zÓ2°AÓ9�D€A€qð €DØ€IÜ˜×(‰ˆˆSØ×Ñà�sœU 3›ZÕ'Õ'Ø�sœU 3›ZÕ'Õ'Ø�cœE #›JÕ&Õ&Ø�cœE #›JÕ&Õ&Ü�c“
œU 7›^Õ+Ü�c“
œU 7›^Õ+Ü�s“˜c¤E¨$°­(£OÕ3Õ3´u¸W³~ÕEÈÕKÜ�s“˜cÕ!¤U¨7£^Õ3°cÕ9ð	ô	
ð 	��a•�‹ñ )ô & i¸¿¹È:ÔV×[Ñ[Ð\^Ð`aÐcdÓe€Oô
 �+Š+�a˜B B¯z©zÀÇÁÔ
K€CÜ˜Q 2Ô+;¸JÓ+GÓH€Eð —=‘= Q�=Ó'€LÜ�A�q˜%× ˆÜ��e•˜QÓˆØ�"�WˆÜ—	’	˜5  B r E �?¬E¯KªK¸¸2¸qÀ!È:×^iÑ^iÔ,jÐkÐqsÔtˆÜ,¨U¯Z©Z¸¸B½ÀÀ1Ó-EÈÈBÍÐPRÐXZÐG[Ó\×aÑaÐbcÐegÐikÐqrÓsˆØ,;¸LÈÈBÈrÈEÈÕ<RÕ,S×,XÑ,XÐYZÐ\^Ð`aÐcdÐfgÐijÓ,k×,rÑ,rÐsuÓ,vÑ)ˆˆB�˜\Ø�a�xˆØ�a˜˜2˜b˜5˜•k×&Ñ& q¨"¨a°°AÓ6Õ6ˆØ�|‰|˜BÓˆØ�|‰|˜BÓˆØ�kÕ!ˆØ�lÕ"ˆÜ'¨¨t°W¸gÓFˆˆAˆr�"ˆuˆHŒñ !ð ×Ñ˜W q™[×.Ñ.¨q°Q¸¸1Ó=¸sÓCÐCùò[ 0÷, D×CÐCús   Ë_Ï-_ß_&c                ó„   € V ^8„  d   QhR\         P                  R\         P                  R\        R\         P                  /# )r   r7   rÈ   rú   r   r©   )r   s   "r   r   r   ¸  s=   € ÷ (kñ (kœUŸ\™\ð (k´5·<±<ð (kÌð (kÔUZ×UaÑUañ (kr   c                ó²  € \        V 4       VP                  4       w   r4p\        P                  P	                  V R,          RR7      pV R,          V,
          pV R,          V,           p\        V^,
          4      V,
          p	\        V^,
          4      V,
          p
VR,          V8¬  VR,          V	8*  ,          VR,          V8¬  ,          VR,          V
8*  ,          # )a`  Check which LAFs have their elliptical region fully inside the image, within a border.

``inside = laf_is_inside_image(laf, images, border)`` takes ``(B, N, 2, 3)`` LAFs in pixels and an image tensor
``(B, CH, H, W)``, read for its height and width only, and returns a boolean ``(B, N)`` mask, true where the
elliptical region of the LAF lies at least ``border`` pixels inside the outer pixel centres. The patch of
:func:`extract_patches_from_pyramid` covers the square ``c + A [-1, 1]^2``, which reaches beyond the region, so a
LAF that is inside can still have patch cells that read the image border.

Convention:
    - The region of a LAF ``[A | c]`` is the ellipse ``c + A u`` over the unit vectors ``u``. Along image axis
      ``i`` (0 for x, 1 for y) it spans exactly ``c_i - r_i`` to ``c_i + r_i``, where ``r_i`` is the Euclidean
      norm of row ``i`` of ``A``. A LAF is inside when both spans lie in ``border <= x <= w - 1 - border`` and
      ``border <= y <= h - 1 - border``, so a region that touches the last valid pixel coordinate is inside.
    - The all-zero padding LAF is a point at the origin, so it counts as inside for ``border <= 0``, the default
      included; combine the mask with :func:`~kornia.feature.laf_is_filled` to drop the padding.

Args:
    laf:  ``(B, N, 2, 3)``.
    images: images, lafs are detected in ``(B, CH, H, W)``.
    border: additional border.

Returns:
    mask with shape ``(B, N)``.

See Also:
    - :func:`laf_is_filled`: tells detections from the padding, which this counts as inside.
    - :func:`laf_is_valid`: checks that the frame is finite and regular, wherever it lies.

r9   r™   r=   rJ   r¿   rÀ   )r   r­   r   ÚlinalgÚvector_normr{   )r7   rÈ   rú   r›   rÑ   rÒ   r  rd  re  Úx_maxÚy_maxs   &&&        r   Úlaf_is_inside_imagero  ¸  s¹   € ô< �SÔØ—‘“�J€A€qˆQä�\‰\×%Ñ% c¨'¥l¸Ð%Ó;€FØ	ˆV��vÕ	€BØ	ˆV��vÕ	€Bô �!�a•%‹L˜6Õ!€EÜ�!�a•%‹L˜6Õ!€EØˆv�J˜&Ñ  R¨¥Z°5Ñ%8Õ9¸RÀ½ZÈ6Ñ=QÕRÐVXÐY_ÕV`ÐdiÑViÕjÐjr   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# r6   r#   )r   s   "r   r   r   ã  s&   € ÷ dñ dœUŸ\™\ð d¬e¯l©lñ dr   c                ó°   € \        V 4       \        P                  ! V R,          V R,          ,           V R,          V R,          ,           V R,          .RR7      # )aR  Convert LAFs to three points: the tips of the patch's x and y axes, then the centre.

``pts = laf_to_three_points(laf)`` takes ``(B, N, 2, 3)`` LAFs and returns ``(B, N, 2, 3)`` tensors whose columns
are the image points ``c + A[:, 0]``, ``c + A[:, 1]`` and ``c``. Mapping the three columns through a point
transformation and converting them back with :func:`laf_from_three_points` transforms the LAFs, as
:func:`perspective_transform_lafs` does for a homography.

Convention:
    - The columns of the result are the points ``c + A[:, 0]``, ``c + A[:, 1]`` and ``c``, in that order: the
      images of the patch points ``(1, 0)``, ``(0, 1)`` and ``(0, 0)``, at the frame's scale rather than of unit
      length. :func:`~kornia.feature.laf_from_three_points` is the inverse.

Args:
    laf:  ``(B, N, 2, 3)``.

Returns:
    threepts ``(B, N, 2, 3)``.

See Also:
    - :func:`laf_from_three_points`: the inverse.
    - :func:`perspective_transform_lafs`: maps these three points through a homography and converts them back.
    - :func:`laf_to_boundary_points`: points on the whole outline of the region.

r9   rJ   r¿   rÀ   r=   )r   r   rš   rF   s   &r   Úlaf_to_three_pointsrr  ã  sD   € ô2 �SÔÜ�;Š;˜˜F� c¨&¥kÕ1°3°vµ;ÀÀVÅÕ3LÈcÐRXÍkÐZÐ`bÔcÐcr   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# )r   Úthreeptsr   r#   )r   s   "r   r   r      s"   € ÷ ñ ¤E§L¡Lð ´U·\±\ñ r   c                ó¶   € \        V . RO4       \        P                  ! V R,          V R,          ,
          V R,          V R,          ,
          V R,          .RR7      # )a£  Build LAFs from three points each: the tips of the patch's x and y axes, then the centre.

``laf = laf_from_three_points(pts)`` takes ``(B, N, 2, 3)`` tensors whose columns are three points ``p0``, ``p1``
and ``c`` and returns the ``(B, N, 2, 3)`` LAFs ``[p0 - c, p1 - c | c]``, whose patch x and y axes end at ``p0``
and ``p1``. Collinear points give a singular shape ``A``. For LAFs from centres, scales and orientations, use
:func:`laf_from_center_scale_ori` instead.

Convention:
    See the Convention block on :func:`~kornia.feature.laf_to_three_points`, which this inverts: the columns of
    ``threepts`` are the images of the patch points ``(1, 0)``, ``(0, 1)`` and ``(0, 0)``, in that order.

Args:
    threepts: ``(B, N, 2, 3)``.

Returns:
    laf ``(B, N, 2, 3)``.

See Also:
    - :func:`laf_to_three_points`: the inverse.
    - :func:`laf_from_center_scale_ori`: circular LAFs from centres, scales and orientations.

r9   )r_   r`   rp   Ú3r¿   rJ   rÀ   r=   )r	   r   rš   )rt  s   &r   Úlaf_from_three_pointsrw     sR   € ô. �xÒ!5Ô6Ü�;Š;Ø	�&Õ	˜H VÕ,Õ	,¨h°vÕ.>ÀÈ&ÕAQÕ.QÐS[Ð\bÕScÐdÐjlôð r   c                óx   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  /# )r   Útrans_01Úlafs_1r   r#   )r   s   "r   r   r     s5   € ÷ X-ñ X-¬¯©ð X-¼u¿|¹|ð X-ÔPU×P\ÑP\ñ X-r   c                óš  € \        V4       \        P                  ! V 4      '       g   \        R4      hV P                  VP                  8X  g   \        R4      hV P
                  ^ ,          VP
                  ^ ,          8X  g   \        R4      hV P
                  R,          ^8X  d   V P
                  R,          ^8X  g   \        R4      hVP                  4       w  r# p\        V4      pVP                  ^ ^^^4      P                  W#^,          ^4      p\        W4      pVP                  W#^^4      P                  ^ ^^^4      p\        V4      # )a·
  Map the LAFs of one image into another through a homography, by mapping three points of each.

``lafs_0 = perspective_transform_lafs(trans_01, lafs_1)`` takes ``(B, 3, 3)`` homographies from the pixels of
image 1 to those of image 0 and ``(B, N, 2, 3)`` LAFs of image 1, and returns the ``(B, N, 2, 3)`` LAFs of the
same regions in image 0: the centres mapped exactly and the shapes approximated through the mapped tips of the
patch axes. To map points, such as the LAF centres alone, use :func:`~kornia.geometry.linalg.transform_points`.

Convention:
    - ``trans_01`` maps pixels of frame 1 to pixels of frame 0, as in
      :func:`~kornia.geometry.linalg.transform_points`, and the centre maps through it exactly. The new ``A``
      is the chord through the mapped tips of the patch axes: the three points of
      :func:`~kornia.feature.laf_to_three_points` are transformed and turned back into a LAF. For an affine
      ``trans_01`` this equals the Jacobian of ``trans_01`` at the centre times ``A``; for a perspective one the
      two differ, the more so the larger the LAF.

Args:
    trans_01: torch.Tensor for perspective transformations of shape ``(B, 3, 3)``.
    lafs_1: torch.Tensor of lafs of shape ``(B, N, 2, 3)``.

Returns:
    the transformed LAFs in frame 0, of shape ``(B, N, 2, 3)``.

Raises:
    TypeError: if ``trans_01`` is not a tensor or is on another device than ``lafs_1``.
    ValueError: if the batch sizes differ or ``trans_01`` is not ``3 x 3``.

See Also:
    - :func:`~kornia.geometry.linalg.transform_points`: maps points through the same homographies.
    - :func:`laf_to_three_points`: the three points of each LAF that this maps.

Examples:
    >>> rng = torch.manual_seed(0)
    >>> lafs_1 = torch.rand(2, 4, 2, 3)  # BxNx2x3
    >>> lafs_1
    tensor([[[[0.4963, 0.7682, 0.0885],
              [0.1320, 0.3074, 0.6341]],
    <BLANKLINE>
             [[0.4901, 0.8964, 0.4556],
              [0.6323, 0.3489, 0.4017]],
    <BLANKLINE>
             [[0.0223, 0.1689, 0.2939],
              [0.5185, 0.6977, 0.8000]],
    <BLANKLINE>
             [[0.1610, 0.2823, 0.6816],
              [0.9152, 0.3971, 0.8742]]],
    <BLANKLINE>
    <BLANKLINE>
            [[[0.4194, 0.5529, 0.9527],
              [0.0362, 0.1852, 0.3734]],
    <BLANKLINE>
             [[0.3051, 0.9320, 0.1759],
              [0.2698, 0.1507, 0.0317]],
    <BLANKLINE>
             [[0.2081, 0.9298, 0.7231],
              [0.7423, 0.5263, 0.2437]],
    <BLANKLINE>
             [[0.5846, 0.0332, 0.1387],
              [0.2422, 0.8155, 0.7932]]]])
    >>> trans_01 = torch.eye(3).repeat(2, 1, 1)  # Bx3x3
    >>> trans_01.shape
    torch.Size([2, 3, 3])
    >>> lafs_0 = perspective_transform_lafs(trans_01, lafs_1)  # BxNx2x3

z Input type is not a torch.Tensorz'torch.Tensor must be in the same devicez2Input batch size must be the same for both tensorsz#Transformation should be homographyr=   rP  )r   r   Ú	is_tensorr~   ro   rZ   Ú
ValueErrorr­   rr  r·   r^   r   r[   rw  )	ry  rz  ÚbsÚnr›   Ú
threepts_1Úpoints_1Úpoints_0Ú
threepts_0s	   &&       r   Úperspective_transform_lafsr„    s  € ôB �VÔÜ�?Š?˜8×$Ò$ÜÐ:Ó;Ð;à�?‰?˜fŸm™mÔ+ÜÐAÓBÐBà�>‰>˜!Õ §¡¨Q¥Ô/ÜÐMÓNÐNà�^‰^˜BÕ 1Ô$°·±¸rÕ0BÀaÔ0GÜÐ>Ó?Ð?à—+‘+“-�K€Bˆ1ˆaä$ VÓ,€JØ×!Ñ! ! Q¨¨1Ó-×5Ñ5°b¸a½%ÀÓC€Hô   Ó3€Hð —‘˜r a¨Ó+×3Ñ3°A°q¸!¸QÓ?€JÜ  Ó,Ð,r   )NN)g•Ö&è.>)é2   )r   )é    )i   )i   )r†  T)=r°   Útypingr   r   r   r   r   Útorch.nn.functionalÚnnÚ
functionalrì   Úkornia.core.checkr   r   r	   Úkornia.core.opsr
   Úkornia.core.utilsr   r   Úkornia.geometry.conversionsr   Úkornia.geometry.linalgr   Úkornia.geometry.transformr   r   r4   rA   rG   rK   rR   rc   rj   rx   rv   r‘   r¦   r»   rÅ   r×   rÚ   rä   rà   rô   rü   r   r  r	  r  r  r  r  r9  r?  rK  rh  ro  rr  rw  r„  r  r   r   Ú<module>r‘     sÿ   ðó$ ß /Ó /ã ß Ð ç PÑ PÝ +ß OÝ @Ý 3Ý -õõ'õT%PõP%-õPõ@#2õL õF1÷B?*õD(M÷VGõT?A÷D-W÷`>õ4&%õR)%÷Xõ:
?õ'õ6Põ"Põ
Dõ
;÷
-÷"!õaõ$õ><õ~^÷>C÷BpD÷f(kõVdõ:÷:X-r   