+
    åûjã  ã                   óþ  a € R* t*0 t R t^ RIHtHtHt ^ RIt^ RIHu H	t
 ^ RIHt ^ RIHtHtHtHt ^ RIHt . R+Ot]! ^^^ 4      t] ^ k ]3R R lltR R	 ltR
 R lt]P2                  P4                  R R l4       t]P2                  P4                  R R l4       tR R ltR R ltR,R R lltR R lt R-R R llt!R-R R llt"R-R R llt#R-R R llt$R-R  R! llt%R-R" R# llt&R-R$ R% llt'R& R' lt(R.R( R) llt)R# )/a  Dilate, erode, open and close images by a structuring element, and reconstruct them from a seed.

The functions are :func:`dilation`, :func:`erosion`, :func:`opening`, :func:`closing`, :func:`gradient`,
:func:`top_hat`, :func:`bottom_hat` and :func:`reconstruction`.
)ÚFinalÚListÚOptionalN)Útorch_version_lt)ÚKORNIA_CHECKÚKORNIA_CHECK_IS_TENSORÚKORNIA_CHECK_SAME_SHAPEÚKORNIA_CHECK_SHAPE)ÚValueCheckErrorc                óP   € V ^8„  d   QhR\         P                  R\        R\        /# )é   ÚdeviceÚmps_ignores_nanÚreturn)Útorchr   Úbool)Úformats   "ÚXC:\Ai_Coding\apps\studio\ComfyUI\.venv\Lib\site-packages\kornia\morphology\morphology.pyÚ__annotate__r   &   s&   € ÷ 4ñ 4¤§¡ð 4Äð 4Ôdhñ 4ó    c                ó4   € V P                   R8H  ;'       d    T# )aL  Whether ``torch.maximum``/``torch.minimum`` return the non-NaN operand of a pair on ``device``.

MPS does so before PyTorch 2.7 (pytorch/pytorch#143976, fixed by pytorch/pytorch#144086), so the ``shift``
engine tracks NaN itself there. The version flag is a default argument because TorchScript cannot read a
module-level ``bool``.
Úmps)Útype)r   r   s   &&r   Ú_maximum_ignores_nanr   &   s   € ð �;‰;˜%Ñ×3Ð3 OÐ3r   c          
      óž   € V ^8„  d   QhR\         P                  R\         P                  R\        \         P                  ,          R\        RR/# )r   ÚtensorÚkernelÚstructuring_elementÚborder_typer   N)r   ÚTensorr   Ústr)r   s   "r   r   r   0   sE   € ÷ 
ñ 
Ü�L‰Lð
Ü"'§,¡,ð
ÜEMÌeÏlÉlÕE[ð
Üjmð
à	ñ
r   c                 óò  € V P                  4       '       g   \        R V P                   24      h\        V\        P
                  4      '       g   \        R\        V4       24      h\        VP                  4      ^8w  d   \        RVP                  4        24      hVeB   VP                  VP                  8w  d'   \        RVP                   RVP                   R24      hVR	9  d   \        RV R24      hR# )
z2Input image must have a floating-point dtype. Got ú'Kernel type is not a torch.Tensor. Got ú(Kernel size must have 2 dimensions. Got Nz;`structuring_element` shape must match `kernel` shape. Got z and Ú.zUnknown `border_type`: zO. Expected one of ['geodesic', 'constant', 'reflect', 'replicate', 'circular'].)ÚgeodesicÚconstantÚreflectÚ	replicateÚcircular)Úis_floating_pointÚ	TypeErrorÚdtypeÚ
isinstancer   r   r   ÚlenÚshapeÚ
ValueErrorÚdim)r   r   r   r   s   &&&&r   Ú_validate_morphology_inputsr2   0   sõ   € ð ×#Ñ#×%Ò%ÜÐLÈVÏ\É\ÈNÐ[Ó\Ð\Ü�fœeŸl™l×+Ò+ÜÐAÄ$ÀvÃ,ÀÐPÓQÐQÜ
ˆ6�<‰<Ó˜AÔÜÐCÀFÇJÁJÃLÀ>ÐRÓSÐSØÒ&Ð+>×+DÑ+DÈÏÉÔ+TÜðØ&×,Ñ,Ð-¨U°6·<±<°.ÀðCó
ð 	
ð ÐVÔVÜØ% k ]ð 3\ð \ó
ð 	
ñ Wr   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# )r   r   r   )r   r   )r   s   "r   r   r   E   s"   € ÷ 'ñ '¬¯©ð '¼%¿,¹,ñ 'r   c                 ó¾   € V P                  4       w  r\        P                  ! W,          V P                  V P                  R 7      p V P                  W,          ^W4      # )©r,   r   )Úsizer   Úeyer,   r   Úview)r   ÚhÚws   &  r   Ú_neight2channels_like_kernelr;   E   s@   € Ø�;‰;‹=�D€AÜ�YŠY�q•u F§L¡L¸¿¹ÔG€FØ�;‰;�q•u˜a Ó&Ð&r   c                ód   € V ^8„  d   QhR\         P                  R\         P                  R\        /# )r   ÚpaddedÚoffsetsr   ©r   r   r   )r   s   "r   r   r   L   s.   € ÷ dñ d¤§¡ð d¼¿¹ð dÌñ dr   c                 ó  € \         P                  P                  4       '       g%   \         P                  P	                  4       '       d   R # \
        ;QJ d    R W3 4       F  '       d   K   R # 	  R# ! R W3 4       4      # )Fc              3   óŒ   "  € T F:  p\         P                  P                  P                  V4      P                  R J x € K<  	  R # 5i)N)r   ÚautogradÚ
forward_adÚunpack_dualÚtangent)Ú.0Úts   & r   Ú	<genexpr>Ú'_can_reduce_in_place.<locals>.<genexpr>O   s2   é € ÐcÑQbÈAŒu�~‰~×(Ñ(×4Ñ4°QÓ7×?Ñ?À4ÕGÓQbùs   ‚AAT)r   ÚjitÚ
is_tracingÚ_CÚ _are_functorch_transforms_activeÚall)r=   r>   s   &&r   Ú_can_reduce_in_placerO   K   s[   € ä‡y�y×Ñ×Ò¤§¡×!JÑ!J×!LÒ!LÙß‹3ÑcÐRXÑQbÓc�3Œ3ÐcŠ3Ðcˆ3ÑcÐRXÑQbÓcÓcÐcr   c          
      ó|   € V ^8„  d   QhR\         P                  R\         P                  R\        R\        R\        /# )r   ÚwindowsÚneighborhoodÚflatÚrecording_gradr   r?   )r   s   "r   r   r   S   s<   € ÷ 7ñ 7Ü�\‰\ð7Ü).¯©ð7Ü=Að7ÜSWð7ä	ñ7r   c                ór   € V'       d$   V'       g   V P                   P                  R9  d   R# \        W4      # )a  Whether the ``unfold`` engine may reduce a flat window with ``amax``/``amin`` instead of ``max``/``min``.

Both return the same values but differ in derivatives: ``torch.max`` along a dimension routes the gradient or
tangent of a tied window to one cell, while ``amax`` splits it. So the swap needs a call that nothing
differentiates through: no backward graph, no forward-mode tangent, no ``torch.func`` transform and no trace,
which could later replay with gradients. Only CPU and CUDA take it, where ``amax`` propagates NaN like ``max``.
F)ÚcpuÚcuda)r   r   rO   )rQ   rR   rS   rT   s   &&&&r   Ú_unfold_reduces_values_onlyrX   R   s(   € ÷ —> W§^¡^×%8Ñ%8ÀÔ%OÙÜ Ó6Ð6r   c                óÔ   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  R\        R\        R\        R\        R\        R	\         P                  /	# )
r   ÚplanesÚplaner>   ÚiÚjÚheightÚwidthrS   r   )r   r   Úintr   )r   s   "r   r   r   b   sr   € ÷ 2ñ 2Ü�L‰Lð2ä�<‰<ð2ô �\‰\ð2ô ð	2ô
 ð2ô ð2ô ð2ô ð2ô ‡\�\ñ2r   c                óì   € V RW3V,           1WDV,           13,          P                  ^ WV3,          P                  ^4      4      ^ ,          pV'       d   V# W‚W3^,           1WD^,           13,          ,           # )zbOne shifted view of the ``shift`` engine, read from the identity or the image plane of ``planes``..)Úindex_selectr8   )	rZ   r[   r>   r\   r]   r^   r_   rS   Úsources	   &&&&&&&& r   Ú_shift_cellrd   b   sn   € ð �C˜ �Z˜¨°­Y¨Ð6Õ7×DÑDÀQÈÐQRÈdÍ×HXÑHXÐYZÓH[Ó\Ð]^Õ_€FßØˆà˜A A¥˜I q¨q­5 yÐ0Õ1Õ1Ð1r   c                óö   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  R\        R\        R\        R\        R\        R	\        \
        ,          R
\         P                  /
# )r   r=   r>   r   r^   r_   rS   ÚdilateÚinplaceÚreduction_valuer   )r   r   r`   r   r   Úfloat)r   s   "r   r   r   t   sŒ   € ÷ añ aÜ�L‰Lðaä�\‰\ðaô �L‰Lðaô ð	aô
 ðaô ðaô ðaô ðaô œe•_ðaô ‡\�\ñar   c	                óP  € VP                   w  rš\        P                  ! 4       ;'       d!    V P                  ;'       g    VP                  p\	        V P
                  4      pVe
   V'       EdÏ   V R^ V1^ V13,          VR,          ,           pVe7   \        P                  ! VR,          ^ 8g  V\        P                  ! WØ4      4      pV'       d   \        P                  ! V4      MRp\        V
4       EF%  p\        V	4       EF  pV^ 8X  d
   V^ 8X  d   K  V RVVV,           1WÿV,           13,          VVV^,           1Wÿ^,           13,          ,           pVe   VP                  VVV3,          ^ 8H  V4       Ve   V\        P                  ! V4      ,          pV'       d?   V'       d   \        P                  ! VVVR7       KÀ  \        P                  ! VVVR7       KÛ  V'       d   \        P                  ! VV4      M\        P                  ! VV4      pEK  	  EK(  	  Ve   VP                  V\        R4      4      pV# \        P                  ! V P                   VP                   4      pV P#                  VR7      p \        P$                  ! \        P                  ! W4      V 34      pV^ 8g  pVP#                  \        P&                  4      p\        P                  ! VV\        P(                  ! V4      4      p\+        VVV^ ^ W4V4      pV'       d   \        P                  ! V4      MRp\        V
4       FÒ  p\        V	4       FÀ  pV^ 8X  d
   V^ 8X  d   K  \+        VVVVWóWE4      pVe   V\        P                  ! V4      ,          pV'       d?   V'       d   \        P                  ! VVVR7       Ko  \        P                  ! VVVR7       KŠ  V'       d   \        P                  ! VV4      M\        P                  ! VV4      pKÂ  	  KÔ  	  Ve   VP                  V\        R4      4      pV# )a=  Running max (``dilate``) or min over the ``k_h * k_w`` shifted views of ``padded`` plus their offsets.

The ``shift`` engine: output pixel ``(y, x)`` reduces ``padded[y + i, x + j] + offsets[i, j]`` over the
kernel positions, the same max-plus expression ``unfold`` evaluates, without materialising the window
tensor. ``torch.compile`` fuses the loop. A cell where ``kernel`` is zero takes ``reduction_value``, the
reduction identity; ``None`` leaves the offset unchanged.
``flat`` says that every offset is zero (a floating-point image and no ``structuring_element``), so the
addition is skipped; a ``-0.0`` pixel then stays ``-0.0``, where adding a ``+0.0`` offset made it ``+0.0``.

Forward-only, a floating-point image reads each cell from a two-plane buffer, plane 0 filled with the
identity and plane 1 holding ``padded`` in the compute dtype, through ``index_select`` on
``kernel[i, j] != 0``. That is a plain copy per cell, where a ``masked_fill_`` or ``where`` with a
broadcast scalar mask is not vectorised on CPU and cost three adds per cell; the select is exact for
every input, ``nan`` and infinities included, and stays data-independent, so the loop compiles and
exports as before. Under autograd the excluded cells are masked instead (see the note in the body).

Forward-only this holds that buffer, one output-sized intermediate and one shifted view whatever the
kernel area, so peak memory is flat in ``k_h k_w`` where ``unfold`` and ``convolution`` grow with it (at
15 x 15, B=8 x 3 x 256^2 float32 on CPU, 69 MiB of peak RSS growth against 1380 MiB for ``unfold``).
Under autograd the opposite is true: every ``torch.maximum`` saves both operands, so ``2 (k_h k_w - 1)``
output-sized tensors stay alive until backward (2717 MiB against 1627 MiB for ``unfold`` in that cell on
CUDA). :func:`_resolve_engine` accounts for both regimes.
N.)ÚoutÚnan©r,   )ºé    é   Nrn   )ro   ro   )r/   r   Úis_grad_enabledÚrequires_gradr   r   ÚwhereÚ	full_likeÚisnanÚrangeÚmasked_fill_ÚmaximumÚminimumÚmasked_fillri   Úpromote_typesr,   ÚtoÚstackÚlongÚ
zeros_likerd   )r=   r>   r   r^   r_   rS   rf   rg   rh   ÚkhÚkwÚ	recordingÚpropagate_nanÚoutputÚnan_maskr]   r\   ÚshiftedÚcompute_dtyperZ   Úincludedr[   s   &&&&&&&&&             r   Ú_shift_reducer‰   t   s;  € ðD �]‰]�F€Bô
 ×%Ò%Ó'×[Ð[¨V×-AÑ-A×-ZÐ-ZÀW×EZÑEZ€Iä(¨¯©Ó7€MØÒ§) )ð ˜˜Q˜v˜X q¨ wÐ.Õ/°'¸(Õ2CÕCˆØÒ&Ü—[’[ ¨¥°Ñ!2°F¼E¿OºOÈFÓ<dÓeˆFß*7”5—;’;˜vÔ&¸Tˆô
 �r—ˆAÜ˜2—Y�Ø˜”6˜a 1œfÙØ   a¨!¨f­* n°a¸e½)°mÐ!CÕDÀwÈqÐSTÐWXÕSXÈyÐZ[ÐbcÕ^cÐZcÐOcÕGdÕd�Ø"Ò.Ø×(Ñ(¨°°1°­¸Ñ):¸OÔLØÒ'Ø'¬%¯+ª+°gÓ*>Õ>�HßßBH”E—M’M &¨'°v×>ÌeÏmÊmÐ\bÐdkÐqw×Nxç?EœUŸ]š]¨6°7Ô;Ì5Ï=Ê=ÐY_ÐahÓKi“Fô ñ ð ÒØ×'Ñ'¨´%¸³,Ó?ˆFØˆô ×'Ò'¨¯©°g·m±mÓD€MØ�Y‰Y˜]ˆYÓ+€FÜ�[Š[œ%Ÿ/š/¨&ÓBÀFÐKÓL€Fð ˜‰{€HØ�K‰KœŸ
™
Ó#€EÜ�kŠk˜( G¬U×-=Ò-=¸gÓ-FÓG€Gä˜ ¨°°A°vÀdÓK€Fß&3Œu�{Š{˜6Ô"¸€Hä�2ŽYˆÜ�r–ˆAØ�AŒv˜!˜qœ&ÙÜ! &¨%°¸!¸QÈÓTˆGØÒ#Ø#¤e§k¢k°'Ó&:Õ:�ßß>D”—’˜f g°6×:Ì%Ï-Ê-ÐX^Ð`gÐms×Jtç;AœŸš v¨wÔ7ÄuÇ}Â}ÐU[Ð]dÓGe’ó ñ ð ÒØ×#Ñ# H¬e°E«lÓ;ˆØ€Mr   c          
      ó’   € V ^8„  d   QhR\         R\        P                  R\        R\        \        P
                  ,          R\         /# )r   Úenginer   rT   r,   r   )r    r   r   r   r   r,   )r   s   "r   r   r   Ø   sD   € ÷ -ñ -Üð-ÜŸ™ð-Ü7;ð-ÜLTÔUZ×U`ÑU`ÕLað-äñ-r   c                ó  € V R8X  d€   VP                   P                  R8X  d   R# Vf   VP                  pV\        P                  \        P
                  39   pVP                   P                  R8X  d   V'       d   V'       d   R# R# V # )aå  Map ``engine="auto"`` to the preferred engine for ``tensor``; leave other values unchanged.

``recording_grad`` says whether this call will build a backward graph, which changes the ranking.
``dtype`` is the dtype the max-plus terms are computed in; it defaults to ``tensor.dtype`` and is
wider when the kernel or the structuring element promotes the computation, which is what the
dtype rule below has to see. For finite inputs, the two engines selected by ``auto`` (``unfold``
and ``shift``) return equal forward output, so switching between them never changes a value; only
the sign of a zero can differ, because a backend's ``max``/``min`` may return either tied operand, and
because forward-only ``shift`` skips adding the zero offsets of a call without ``structuring_element``,
which turn a ``-0.0`` pixel into ``+0.0`` in the ``unfold`` dilation.

Benchmarks in :mod:`benchmarks.morphology.engines` (x86 CPU, an RTX 4090 and an Apple M1,
``dilation``, B x 3 x 256 x 256) give three CPU/CUDA regimes:

- CUDA: ``unfold`` is the broadly faster engine forward (23 of 24 cells) and forward + backward
  (21 of 24), so it is always the CUDA choice.
- CPU without a backward graph: ``shift`` wins every cell, by 4-13x in float32 and 12-20x in half
  precision, and its peak memory is flat in the kernel area instead of growing with it.
- CPU with a backward graph: the running max saves ``2 (k_h k_w - 1)`` intermediates, so ``shift``
  loses to ``unfold`` in float32 (up to 2.5x at 15 x 15) and float64 (up to 3.4x), while still
  winning 11 of 12 half-precision cells.

MPS keeps ``shift`` in both cases, measured on an Apple M1: ``unfold`` is not the fastest engine
in any of the 16 forward + backward cells, and ``shift`` beats it there by 2.6-10x, so the CPU
float32 grad branch deliberately does not extend to Metal. ``convolution`` is faster than
``shift`` at small kernels on MPS but collapses at 15 x 15 (2854 ms against 354 ms at B=8), which
is why it is not the choice either.

The grad branch is a backward-pass speed rule, not a derivative-preserving one: forward-mode AD
(``torch.func.jvp``, ``torch.autograd.forward_ad``) records no backward graph, so it takes
``shift`` off CUDA like any forward-only call, and its tangent at tied maxima is the ``shift``
one.
ÚautorW   ÚunfoldrV   Úshift)r   r   r,   r   Úfloat32Úfloat64)r‹   r   rT   r,   Úis_float32_or_64s   &&&& r   Ú_resolve_enginer“   Ø   sj   € ðH �ÔØ�=‰=×Ñ Ô'ÙØŠ=Ø—L‘LˆEØ ¤U§]¡]´E·M±MÐ$BÑBÐØ�=‰=×Ñ Ô&¯>×>NÙÙØ€Mr   c                óz   € V ^8„  d   QhR\         P                  R\        \         P                  ,          R\        /# )r   r   r   r   )r   r   r   r   )r   s   "r   r   r     s4   € ÷ Qñ Qœ%Ÿ,™,ð Q¼XÄeÇlÁlÕ=Sð QÔX\ñ Qr   c                ó”   € \         P                  ! 4       '       g   R# V P                  '       d   R# VRJ;'       d    VP                  # )ay  Whether an op over these inputs will build a backward graph.

``torch.no_grad()`` leaves ``requires_grad`` set on the inputs but records nothing, so grad mode has
to be checked too: inference on a tensor that happens to require grad should take the forward-only
engine. The structuring element counts because ``dilation`` and ``erosion`` differentiate through
the neighborhood they build from it. The kernel does not: it enters only through the ``kernel == 0``
mask, so a kernel that requires grad still produces an output that does not. Forward-mode AD
(``torch.func.jvp``) is invisible here by design; see :func:`_resolve_engine`.
FTN)r   rq   rr   )r   r   s   &&r   Ú_records_gradr–     s?   € ô × Ò ×"Ò"ÙØ××ÐÙØ dÐ*×PÐPÐ/B×/PÑ/PÐPr   c                ó  € V ^8„  d   QhR\         P                  R\         P                  R\        \         P                  ,          R\        \        \        ,          ,          R\
        R\        R\        R\
        R	\         P                  /	# ©
r   r   r   r   Úoriginr   Úborder_valueÚmax_valr‹   r   ©r   r   r   r   r`   r    ri   )r   s   "r   r   r     s‹   € ÷ @"ñ @"Ü�L‰Lð@"ä�L‰Lð@"ô "¤%§,¡,Õ/ð@"ô ”Tœ#•YÕð	@"ô
 ð@"ô ð@"ô ð@"ô ð@"ô ‡\�\ñ@"r   c                óÒ  € \        V \        P                  4      '       g   \        R\	        V 4       24      h\        V P                  4      ^8w  d   \        RV P                  4        24      h\        WW$4       VP                  w  r‰Vf   V^,          V	^,          .pVfG   VP                  4       '       g   V P                  MVP                  p
\        P                  ! WR7      pMVP                  4       p\        P                  ! V P                  VP                  4      p\        W4      p\!        WpWÜ4      pW“^,          ,
          ^,
          V^,          Wƒ^ ,          ,
          ^,
          V^ ,          .pVR8H  pVR8X  d%   \"        P$                  ! WR\'        R4      ) R7      pM8VR8X  d   \"        P$                  ! WWER7      pM\"        P$                  ! WVR	7      p\'        R4      ) pVR
8X  Ed(   VP)                  ^V^4      P)                  ^V	^4      pVP+                  R4      P-                  ^^^^W‰4      ^ 8H  pRp\        P.                  P1                  4       '       g   \3        VW²RJ V4      pV'       d@   \        P4                  ! VVV4      P7                  R4      P9                  V4      R,           pEMVVP+                  R4      ,           pVP;                  VV4       \        P<                  ! V^4      w  pp\        P<                  ! V^4      w  ppEM¿VR8X  Ed	   V P?                  4       w  ppppVP                  RR w  ppVP9                  VR7      p\A        V4      P9                  VR7      pVPC                  V^ 8H  R4      p\        P                  ! V4      pVP                  4       '       d«   VPC                  V\'        R4      8H  R4      pVPC                  V\'        R4      ) 8H  R4      pVPC                  \        PD                  ! V4      R4      pVPC                  V^ 8g  R4      p\"        PF                  ! VP-                  VV,          ^VV4      V^ R7      p\"        PF                  ! VP-                  VV,          ^VV4      V^ VP-                  R4      P+                  ^ 4      P9                  VR7      R7      pVP                  4       '       d\   VPC                  V^8H  \'        R4      4      pVPC                  V^8H  \'        R4      ) 4      pVPC                  V^8H  \'        R4      4      pVPC                  VPI                  R4      P+                  ^ 4      P-                  ^R^^4      ^ 8H  V4      pV'       dz   \        PJ                  ! ^^VV3VP                  VPL                  R7      p\"        P$                  ! VVRRR7      p\"        PF                  ! VV^ R7      pVPC                  V^ 8H  V4      pVP=                  ^R7      PN                  pVP-                  VVVV4      pM¯VR8X  dš   VP+                  R4      pRp \        P.                  P1                  4       '       g   V'       * ;'       d    \Q        VV4      p \S        VVVP+                  R4      V P                  R,          V P                  R,          VRJ RV V4	      pM\U        RV R24      hVPW                  V 4      # )a~  Dilate an image: the maximum over each pixel's neighborhood, with the kernel reflected.

``out = dilation(tensor, kernel)`` takes a floating-point image ``(B, C, H, W)`` and a ``(k_h, k_w)`` kernel whose
non-zero cells mark the neighborhood. It returns the ``(B, C, H, W)`` image whose every pixel is the maximum of
``tensor`` over the neighborhood placed at it.

.. image:: _static/img/dilation.png

Convention:
    - ``dilation`` reflects the kernel: it is the Minkowski dilation
      :math:`\delta_B f(x) = \max_{b \in B} f(x - b)`, as in ``scipy.ndimage``; :func:`erosion` does not
      reflect. :doc:`Conventions & Pitfalls </get-started/conventions>` maps the kernels and the border modes
      onto scipy, scikit-image and OpenCV.
    - Under ``geodesic`` a window with no kernel cell inside the image is empty and returns the reduction
      identity, ``-inf`` here and ``+inf`` in :func:`erosion`, as scipy and scikit-image do; so does every
      window of a kernel with no non-zero cell. The composite operations inherit these infinities.

Args:
    tensor: floating-point image ``(B, C, H, W)``; another dtype raises ``TypeError``, another rank ``ValueError``.
    kernel: ``(k_h, k_w)`` mask laid over the image's ``(H, W)`` axes. Its non-zero cells form the neighborhood
        and their values are ignored; a floating-point kernel sets the dtype of the result (see Returns). For a
        full window pass ``torch.ones(k_h, k_w)``. Another rank raises ``ValueError``.
    structuring_element: non-flat structuring element of ``kernel``'s shape, added to the neighbor values before
        the maximum. Another shape raises ``ValueError``. Default: ``None``, a flat element.
    origin: ``[row, col]`` cell of ``kernel`` placed on the output pixel. Default: ``None``, which uses
        ``[k_h // 2, k_w // 2]`` for odd and even sizes alike (``[1, 1]`` for a :math:`2 \times 2` kernel).
    border_type: ``"geodesic"`` (default) leaves the pixels outside the image out of the window; ``"constant"``,
        ``"reflect"``, ``"replicate"`` and ``"circular"`` pad with :func:`torch.nn.functional.pad`. ``"reflect"``
        needs the pad the kernel asks for to stay below the image size and ``"circular"`` to stay at most equal to
        it; both raise ``RuntimeError`` otherwise. Any other value raises ``ValueError``.
    border_value: fill value for ``border_type="constant"``; the other modes ignore it. Default: ``0.0``.
    max_val: no effect; excluded kernel cells and ``geodesic`` padding use the reduction identity
        :math:`\mp\infty`. Retained for backward compatibility.
    engine: ``"auto"`` (default), ``"unfold"``, ``"shift"`` or ``"convolution"``; another value raises
        ``NotImplementedError``. ``"unfold"`` and ``"shift"`` compute the same max-plus expression and, for finite
        inputs, return equal output up to the sign of a zero. ``"auto"`` picks ``"unfold"`` on CUDA and
        ``"shift"`` elsewhere, except that a CPU call which computes in float32 or float64 (the image dtype widened
        as described under Returns) and records a backward graph takes ``"unfold"``, where ``"shift"`` is slower.
        ``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a ``conv2d`` that
        computes float32 in reduced precision, as on macOS CPU, rounds the output. Forward-only, ``"shift"`` needs
        no ``k_h k_w``-sized intermediate. Under autograd it saves ``2 (k_h k_w - 1)`` output-sized tensors
        for backward, more memory than ``"unfold"``.

Returns:
    Dilated image ``(B, C, H, W)``. Its dtype is the image dtype promoted with that of ``structuring_element``,
    or, without one, with that of a floating-point ``kernel``: a float16 image with the float32
    ``torch.ones(3, 3)`` returns float32, and with a bool kernel or a float16 one it stays float16.

See Also:
    - :func:`erosion`: the minimum over the neighborhood, with the kernel not reflected.
    - :func:`closing`: a dilation followed by an erosion, which fills dark details and keeps the rest.
    - :func:`gradient`: the dilation minus the erosion, an edge-strength map.
    - :func:`reconstruction`: repeats a dilation clipped to a mask until the result stops changing.

.. note::
   See a working example `here <https://www.kornia.org/tutorials/nbs/morphology_101.html>`__.

Example:
    >>> tensor = torch.rand(1, 3, 5, 5)
    >>> kernel = torch.ones(3, 3)
    >>> dilated_img = dilation(tensor, kernel)

ú&Input type is not a torch.Tensor. Got ú'Input size must have 4 dimensions. Got Nrm   r%   r&   Úinf©ÚmodeÚvalue©r¢   rŽ   Fç        Úconvolutionç      ð?ç       @ç      @©Úpadding©r«   Úbiasrl   r5   ©r1   r�   Túengine ú; is unknown, use 'auto', 'convolution', 'shift' or 'unfold')ro   rp   éþÿÿÿéÿÿÿÿ©r±   r²   ),r-   r   r   r+   r   r.   r/   r0   r1   r2   r*   r,   r   Úcloner{   r–   r“   ÚFÚpadri   rŽ   Úflipr8   rJ   Úis_scriptingrX   rs   Úamaxr|   rw   Úmaxr6   r;   rz   ru   Úconv2dÚreshapeÚonesr   ÚvaluesrO   r‰   ÚNotImplementedErrorÚview_as)!r   r   r   r™   r   rš   r›   r‹   Úse_hÚse_wÚnb_dtyperR   r‡   rT   Úpad_eÚis_geodesicr„   Úreduction_minÚexcludedÚvalues_onlyÚ_ÚBÚCÚHÚWÚh_padÚw_padÚreshape_kernelÚconv_neighborhoodÚspecialÚvalidr>   rg   s!   &&&&&&&&                         r   ÚdilationrÔ     sÛ  € ôR �fœeŸl™l×+Ò+ÜÐ@ÄÀfÃÀÐOÓPÐPä
ˆ6�<‰<Ó˜AÔÜÐBÀ6Ç:Á:Ã<À.ÐQÓRÐRä Ð0CÔQð —‘�J€DØ‚~Ø˜!•)˜T Q�YÐ'ˆð Ò"ð (.×'?Ñ'?×'AÒ'A�6—<’<ÀvÇ|Á|ˆÜ×'Ò'¨Ô?‰à*×0Ñ0Ó2ˆô ×'Ò'¨¯©°l×6HÑ6HÓI€MÜ" 6Ó?€NÜ˜V¨^ÓK€Fð  a�yÕ(¨1Õ,¨f°Q­i¸ÀqÅ	Õ9IÈAÕ9MÈvÐVWÍyÐY€EØ Ñ+€KØ�jÔ Ü Ÿušu V¸ÌEÐRWËLÈ=ÔY‰Ø	˜
Ô	"Ü—’�v¨;ÔK‰ä—’�v¨;Ô7ˆä! %›L˜=€MØ�ÕØ—‘˜q $¨Ó*×1Ñ1°!°T¸1Ó=ˆØ—;‘;˜vÓ&×+Ñ+¨A¨q°!°Q¸ÓCÀqÑHˆØˆÜ�y‰y×%Ñ%×'Ò'Ü5°f¸lÐcgÐLgÐiwÓxˆKßô
 —[’[ ¨=¸&ÓA×FÑFÀxÓP×SÑSÐTaÓbÐehÕhŠFà˜l×/Ñ/°Ó7Õ7ˆFØ×Ñ ¨-Ô8ÜŸ	š	 &¨!Ó,‰IˆF�AÜŸ	š	 &¨!Ó,‰IˆF’AØ	�=Õ	 Ø—[‘[“]‰
ˆˆ1ˆa�Ø—|‘| B CÐ(‰ˆˆuØ—‘ �Ó/ˆÜ5°fÓ=×@Ñ@À}Ð@ÓUˆØ(×4Ñ4°V¸q±[À#ÓFÐô ×"Ò" 6Ó*ˆØ×#Ñ#×%Ò%Ø×)Ñ)¨&´E¸%³LÑ*@À#ÓFˆGØ×)Ñ)¨&´U¸5³\°MÑ*AÀ3ÓGˆGØ×)Ñ)¬%¯+ª+°fÓ*=¸sÓCˆGØ×'Ñ'¨°1©°cÓ:ˆFÜ—h’h˜wŸ|™|¨A°­E°1°e¸UÓCÀ^Ð]^Ô_ˆGÜ—’Ø�K‰K˜˜A�˜q %¨Ó/ØØØ"×'Ñ'¨Ó+×0Ñ0°Ó3×6Ñ6¸]Ð6ÓKô	
ˆð ×#Ñ#×%Ò%Ø×'Ñ'¨°1©´e¸E³lÓCˆFØ×'Ñ'¨°1©´u¸U³|°mÓDˆFØ×'Ñ'¨°1©´e¸E³lÓCˆFà×#Ñ#Ø�N‰N˜2Ó×#Ñ# AÓ&×+Ñ+¨A¨r°1°aÓ8¸AÑ=Øó
ˆ÷
 Ü—J’J  1 a¨˜|°6·<±<ÈÏÉÔVˆEÜ—E’E˜% ¨Z¸sÔCˆEÜ—H’H˜U N¸AÔ>ˆEØ×'Ñ'¨°©
°MÓBˆFà—‘ �Ó"×)Ñ)ˆØ—‘˜Q  1 aÓ(‰Ø	�7Ô	Ø×#Ñ# FÓ+ˆØˆÜ�y‰y×%Ñ%×'Ò'Ø(Ô(×RÐRÔ-AÀ&È'Ó-RˆGÜØØØ�K‰K˜ÓØ�L‰L˜ÕØ�L‰L˜ÕØ 4Ð'ØØØó

‰ô " G¨F¨8Ð3nÐ"oÓpÐpØ�>‰>˜&Ó!Ð!r   c                ó  € V ^8„  d   QhR\         P                  R\         P                  R\        \         P                  ,          R\        \        \        ,          ,          R\
        R\        R\        R\
        R	\         P                  /	# r˜   rœ   )r   s   "r   r   r   Ü  s‹   € ÷ jñ jÜ�L‰Lðjä�L‰Lðjô "¤%§,¡,Õ/ðjô ”Tœ#•YÕð	jô
 ðjô ðjô ðjô ðjô ‡\�\ñjr   c                ó4  € \        V \        P                  4      '       g   \        R\	        V 4       24      h\        V P                  4      ^8w  d   \        RV P                  4        24      h\        WW$4       VP                  w  r‰Vf   V^,          V	^,          .pVfG   VP                  4       '       g   V P                  MVP                  p
\        P                  ! WR7      pMVP                  4       p\        P                  ! V P                  VP                  4      p\        W4      p\!        WpWÜ4      pV^,          W“^,          ,
          ^,
          V^ ,          Wƒ^ ,          ,
          ^,
          .pVR8H  pVR8X  d$   \"        P$                  ! WR\'        R4      R7      pM8VR8X  d   \"        P$                  ! WWER7      pM\"        P$                  ! WVR	7      p\'        R4      pVR
8X  Ed   VP)                  ^V^4      P)                  ^V	^4      pVP+                  ^^^^W‰4      ^ 8H  pRp\        P,                  P/                  4       '       g   \1        VW²RJ V4      pV'       d9   \        P2                  ! VVV4      P5                  R4      P7                  V4      pV# VVP7                  VR7      ,
          pVP9                  VV4       \        P:                  ! V^4      w  pp\        P:                  ! V^4      w  pp V# VR8X  Edí   V P=                  4       w  ppppVP                  RR w  ppVP7                  VR7      p\?        V4      P7                  VR7      pVPA                  V^ 8H  R4      p\        P                  ! V4      pVP                  4       '       d«   VPA                  V\'        R4      8H  R4      pVPA                  V\'        R4      ) 8H  R4      pVPA                  \        PB                  ! V4      R4      pVPA                  V^ 8g  R4      p\"        PD                  ! VP+                  VV,          ^VV4      V^ R7      p\"        PD                  ! VP+                  VV,          ^VV4      V^ VP+                  R4      P7                  VR7      ) R7      pVP                  4       '       d\   VPA                  V^8H  \'        R4      4      pVPA                  V^8H  \'        R4      ) 4      pVPA                  V^8H  \'        R4      4      pVPA                  VPG                  R4      P+                  ^R^^4      ^ 8H  V4      pV'       dz   \        PH                  ! ^^VV3VP                  VPJ                  R7      p\"        P$                  ! VVRRR7      p\"        PD                  ! VV^ R7      pVPA                  V^ 8H  V4      pVP;                  ^R7      PL                  pVP+                  VVVV4      pV# VR8X  dŽ   VP7                  VR7      ) pRp \        P,                  P/                  4       '       g   V'       * ;'       d    \O        VV4      p \Q        VVVV P                  R,          V P                  R,          VRJ RV V4	      pV# \S        RV R24      h)a  Erode an image: the minimum over each pixel's neighborhood, without reflecting the kernel.

``out = erosion(tensor, kernel)`` takes the inputs of :func:`dilation` and returns the ``(B, C, H, W)`` image whose
every pixel is the minimum of ``tensor`` over the neighborhood placed at it.

.. image:: _static/img/erosion.png

Convention:
    As :func:`dilation`, except that ``erosion`` does **not** reflect the kernel: it is the Minkowski
    erosion :math:`\varepsilon_B f(x) = \min_{b \in B} f(x + b)`, as in ``scipy.ndimage`` and OpenCV.

Args:
    tensor: floating-point image ``(B, C, H, W)``; another dtype raises ``TypeError``, another rank ``ValueError``.
    kernel: ``(k_h, k_w)`` mask of the neighborhood, as in :func:`dilation`.
    structuring_element: non-flat structuring element of ``kernel``'s shape, subtracted from the neighbor values
        before the minimum. Default: ``None``, a flat element.
    origin: ``[row, col]`` cell of ``kernel`` placed on the output pixel, as in :func:`dilation`.
    border_type: border handling, as in :func:`dilation`. Default: ``"geodesic"``.
    border_value: fill value for ``border_type="constant"``. Default: ``0.0``.
    max_val: no effect, as in :func:`dilation`.
    engine: computation engine, as in :func:`dilation`. Default: ``"auto"``.

Returns:
    Eroded image ``(B, C, H, W)``, in the dtype :func:`dilation` returns for the same inputs.

See Also:
    - :func:`dilation`: the maximum over the neighborhood, with the kernel reflected.
    - :func:`opening`: an erosion followed by a dilation, which removes bright details and keeps the rest.
    - :func:`gradient`: the dilation minus the erosion, an edge-strength map.
    - :func:`reconstruction`: with ``method="erosion"``, repeats an erosion bounded by a mask until the result
      stops changing.

.. note::
   See a working example `here <https://www.kornia.org/tutorials/nbs/morphology_101.html>`__.

Example:
    >>> tensor = torch.rand(1, 3, 5, 5)
    >>> kernel = torch.ones(5, 5)
    >>> output = erosion(tensor, kernel)

rž   rŸ   Nrm   r%   r&   r    r¡   r¤   rŽ   Fr¦   r¥   r§   r¨   r©   rª   r¬   rl   r5   r®   r�   r¯   r°   r±   r²   r³   )*r-   r   r   r+   r   r.   r/   r0   r1   r2   r*   r,   r   r´   r{   r–   r“   rµ   r¶   ri   rŽ   r8   rJ   r¸   rX   rs   Úaminr|   rw   Úminr6   r;   rz   ru   r»   r¼   r½   r   r¾   rO   r‰   r¿   )!r   r   r   r™   r   rš   r›   r‹   rÁ   rÂ   rÃ   rR   r‡   rT   rÄ   rÅ   r„   Úreduction_maxrÇ   rÈ   rÉ   rÊ   rË   rÌ   rÍ   ÚHpadÚWpadrÐ   rÑ   rÒ   rÓ   r>   rg   s!   &&&&&&&&                         r   ÚerosionrÜ   Ü  sÅ  € ôf �fœeŸl™l×+Ò+ÜÐ@ÄÀfÃÀÐOÓPÐPä
ˆ6�<‰<Ó˜AÔÜÐBÀ6Ç:Á:Ã<À.ÐQÓRÐRä Ð0CÔQð —‘�J€DØ‚~Ø˜!•)˜T Q�YÐ'ˆð Ò"ð (.×'?Ñ'?×'AÒ'A�6—<’<ÀvÇ|Á|ˆÜ×'Ò'¨Ô?‰à*×0Ñ0Ó2ˆô ×'Ò'¨¯©°l×6HÑ6HÓI€MÜ" 6Ó?€NÜ˜V¨^ÓK€Fð ˜q�	 4°­)Õ#3°aÕ#7¸À½ÀDÐRSÍ9ÕDTÐWXÕDXÐY€EØ Ñ+€KØ�jÔ Ü Ÿušu V¸Ì5ÐQVË<ÔX‰Ø	˜
Ô	"Ü—’�v¨;ÔK‰ä—’�v¨;Ô7ˆä  ›<€MØ�ÕØ—‘˜q $¨Ó*×1Ñ1°!°T¸1Ó=ˆØ—;‘;˜q ! Q¨¨4Ó6¸!Ñ;ˆØˆÜ�y‰y×%Ñ%×'Ò'Ü5°f¸lÐcgÐLgÐiwÓxˆKßä—[’[ ¨=¸&ÓA×FÑFÀxÓP×SÑSÐTaÓbˆFðP €MðK ˜lŸo™o°M˜oÓBÕBˆFØ×Ñ ¨-Ô8ÜŸ	š	 &¨!Ó,‰IˆF�AÜŸ	š	 &¨!Ó,‰IˆF‘AðD €MðC 
�=Õ	 Ø—[‘[“]‰
ˆˆ1ˆa�Ø—\‘\ " #Ð&‰
ˆˆdØ—‘ �Ó/ˆÜ5°fÓ=×@Ñ@À}Ð@ÓUˆØ(×4Ñ4°V¸q±[À#ÓFÐô ×"Ò" 6Ó*ˆØ×#Ñ#×%Ò%Ø×)Ñ)¨&´E¸%³LÑ*@À#ÓFˆGØ×)Ñ)¨&´U¸5³\°MÑ*AÀ3ÓGˆGØ×)Ñ)¬%¯+ª+°fÓ*=¸sÓCˆGØ×'Ñ'¨°1©°cÓ:ˆFÜ—h’h˜wŸ|™|¨A°­E°1°d¸DÓAÀ>Ð[\Ô]ˆGÜ—’Ø�K‰K˜˜A�˜q $¨Ó-ØØØ#×(Ñ(¨Ó,×/Ñ/°mÐ/ÓDÐDô	
ˆð ×#Ñ#×%Ò%Ø×'Ñ'¨°1©´e¸E³lÓCˆFØ×'Ñ'¨°1©´u¸U³|°mÓDˆFØ×'Ñ'¨°1©´e¸E³lÓCˆFà×#Ñ#Ø�N‰N˜2Ó×#Ñ# A r¨1¨aÓ0°AÑ5Øó
ˆ÷
 Ü—J’J  1 a¨˜|°6·<±<ÈÏÉÔVˆEÜ—E’E˜% ¨Z¸sÔCˆEÜ—H’H˜U N¸AÔ>ˆEØ×'Ñ'¨°©
°MÓBˆFà—‘ �Ó"×)Ñ)ˆØ—‘˜Q  1 aÓ(ˆð, €Mð+ 
�7Ô	ð  —?‘?¨�?Ó7Ð7ˆØˆÜ�y‰y×%Ñ%×'Ò'Ø(Ô(×RÐRÔ-AÀ&È'Ó-RˆGÜØØØØ�L‰L˜ÕØ�L‰L˜ÕØ 4Ð'ØØØó

ˆð €Mô " G¨F¨8Ð3nÐ"oÓpÐpr   c                ó  € V ^8„  d   QhR\         P                  R\         P                  R\        \         P                  ,          R\        \        \        ,          ,          R\
        R\        R\        R\
        R	\         P                  /	# r˜   rœ   )r   s   "r   r   r   ‰  s‹   € ÷ Rñ RÜ�L‰LðRä�L‰LðRô "¤%§,¡,Õ/ðRô ”Tœ#•YÕð	Rô
 ðRô ðRô ðRô ðRô ‡\�\ñRr   c                óþ  € \        V \        P                  4      '       g   \        R\	        V 4       24      h\        V P                  4      ^8w  d   \        RV P                  4        24      h\        V\        P                  4      '       g   \        R\	        V4       24      h\        VP                  4      ^8w  d   \        RVP                  4        24      h\        \        V VVVVVVVR7      VVVVVVVR7      # )a+  Open an image: erode, then dilate, to remove the bright details the kernel does not fit in.

``out = opening(tensor, kernel)`` is ``dilation(erosion(tensor, kernel), kernel)`` with the same arguments in both
halves, and returns a ``(B, C, H, W)`` image.

.. image:: _static/img/opening.png

Convention:
    As only :func:`dilation` reflects the kernel, ``opening`` is a morphological opening (anti-extensive and
    idempotent) for an asymmetric kernel too, under ``geodesic`` or ``circular``; a non-flat
    ``structuring_element`` or ``engine="convolution"`` holds both properties only to roundoff, and ``constant``,
    ``reflect`` and ``replicate`` can break them.

Args:
    tensor: floating-point image ``(B, C, H, W)``; another dtype raises ``TypeError``, another rank ``ValueError``.
    kernel: ``(k_h, k_w)`` mask of the neighborhood, as in :func:`dilation`.
    structuring_element: non-flat structuring element, as in :func:`dilation`.
    origin: ``[row, col]`` cell of ``kernel`` placed on the output pixel, as in :func:`dilation`.
    border_type: border handling, as in :func:`dilation`. Default: ``"geodesic"``.
    border_value: fill value for ``border_type="constant"``. Default: ``0.0``.
    max_val: no effect, as in :func:`dilation`.
    engine: computation engine, as in :func:`dilation`. Default: ``"auto"``.

Returns:
    Opened image ``(B, C, H, W)``, in the dtype :func:`dilation` returns for the same inputs.

See Also:
    - :func:`closing`: the dual, which fills the dark details instead.
    - :func:`top_hat`: the image minus its opening, the removed bright details alone.
    - :func:`erosion`: the first half alone, which also shrinks the shapes that are kept.
    - :func:`reconstruction`: opening by reconstruction, ``reconstruction(erosion(x, kernel), x)``; thin parts of
      a kept shape survive, unlike in opening.

.. note::
   See a working example `here <https://www.kornia.org/tutorials/nbs/morphology_101.html>`__.

Example:
    >>> tensor = torch.rand(1, 3, 5, 5)
    >>> kernel = torch.ones(3, 3)
    >>> opened_img = opening(tensor, kernel)

rž   rŸ   r"   r#   ©r   r   r™   r   rš   r›   r‹   )r-   r   r   r+   r   r.   r/   r0   r1   rÔ   rÜ   ©r   r   r   r™   r   rš   r›   r‹   s   &&&&&&&&r   Úopeningrá   ‰  sí   € ôh �fœeŸl™l×+Ò+ÜÐ@ÄÀfÃÀÐOÓPÐPä
ˆ6�<‰<Ó˜AÔÜÐBÀ6Ç:Á:Ã<À.ÐQÓRÐRä�fœeŸl™l×+Ò+ÜÐAÄ$ÀvÃ,ÀÐPÓQÐQä
ˆ6�<‰<Ó˜AÔÜÐCÀFÇJÁJÃLÀ>ÐRÓSÐSäÜØØØ 3ØØ#Ø%ØØô		
ð Ø/ØØØ!ØØô#ð r   c                ó  € V ^8„  d   QhR\         P                  R\         P                  R\        \         P                  ,          R\        \        \        ,          ,          R\
        R\        R\        R\
        R	\         P                  /	# r˜   rœ   )r   s   "r   r   r   Þ  s‹   € ÷ Pñ PÜ�L‰LðPä�L‰LðPô "¤%§,¡,Õ/ðPô ”Tœ#•YÕð	Pô
 ðPô ðPô ðPô ðPô ‡\�\ñPr   c                óþ  € \        V \        P                  4      '       g   \        R\	        V 4       24      h\        V P                  4      ^8w  d   \        RV P                  4        24      h\        V\        P                  4      '       g   \        R\	        V4       24      h\        VP                  4      ^8w  d   \        RVP                  4        24      h\        \        V VVVVVVVR7      VVVVVVVR7      # )a…  Close an image: dilate, then erode, to fill the dark details the kernel does not fit in.

``out = closing(tensor, kernel)`` is ``erosion(dilation(tensor, kernel), kernel)`` with the same arguments in both
halves, and returns a ``(B, C, H, W)`` image.

.. image:: _static/img/closing.png

Convention:
    As only :func:`dilation` reflects the kernel, ``closing`` is a morphological closing (extensive and
    idempotent) for an asymmetric kernel too, under ``geodesic`` or ``circular``; a non-flat
    ``structuring_element`` or ``engine="convolution"`` holds both properties only to roundoff, and ``constant``,
    ``reflect`` and ``replicate`` can break them.

Args:
    tensor: floating-point image ``(B, C, H, W)``; another dtype raises ``TypeError``, another rank ``ValueError``.
    kernel: ``(k_h, k_w)`` mask of the neighborhood, as in :func:`dilation`.
    structuring_element: non-flat structuring element, as in :func:`dilation`.
    origin: ``[row, col]`` cell of ``kernel`` placed on the output pixel, as in :func:`dilation`.
    border_type: border handling, as in :func:`dilation`. Default: ``"geodesic"``.
    border_value: fill value for ``border_type="constant"``. Default: ``0.0``.
    max_val: no effect, as in :func:`dilation`.
    engine: computation engine, as in :func:`dilation`. Default: ``"auto"``.

Returns:
    Closed image ``(B, C, H, W)``, in the dtype :func:`dilation` returns for the same inputs.

See Also:
    - :func:`opening`: the dual, which removes the bright details instead.
    - :func:`bottom_hat`: the closing minus the image, the filled dark details alone.
    - :func:`dilation`: the first half alone, which also grows the shapes that are kept.

.. note::
   See a working example `here <https://www.kornia.org/tutorials/nbs/morphology_101.html>`__.

Example:
    >>> tensor = torch.rand(1, 3, 5, 5)
    >>> kernel = torch.ones(3, 3)
    >>> closed_img = closing(tensor, kernel)

rž   rŸ   r"   r#   rß   )r-   r   r   r+   r   r.   r/   r0   r1   rÜ   rÔ   rà   s   &&&&&&&&r   Úclosingrä   Þ  sí   € ôd �fœeŸl™l×+Ò+ÜÐ@ÄÀfÃÀÐOÓPÐPä
ˆ6�<‰<Ó˜AÔÜÐBÀ6Ç:Á:Ã<À.ÐQÓRÐRä�fœeŸl™l×+Ò+ÜÐAÄ$ÀvÃ,ÀÐPÓQÐQä
ˆ6�<‰<Ó˜AÔÜÐCÀFÇJÁJÃLÀ>ÐRÓSÐSäÜØØØ 3ØØ#Ø%ØØô		
ð Ø/ØØØ!ØØô#ð r   c                ó  € V ^8„  d   QhR\         P                  R\         P                  R\        \         P                  ,          R\        \        \        ,          ,          R\
        R\        R\        R\
        R	\         P                  /	# r˜   rœ   )r   s   "r   r   r   2  s‹   € ÷ Bñ BÜ�L‰LðBä�L‰LðBô "¤%§,¡,Õ/ðBô ”Tœ#•YÕð	Bô
 ðBô ðBô ðBô ðBô ‡\�\ñBr   c                óX   € \        V VVVVVVVR7      \        V VVVVVVVR7      ,
          # )a¢  Compute the morphological gradient, the dilation minus the erosion, as an edge-strength map.

``out = gradient(tensor, kernel)`` returns ``dilation(tensor, kernel) - erosion(tensor, kernel)`` with the same
arguments, a ``(B, C, H, W)`` edge-strength map that is large where the image changes. Under a non-``geodesic``
border, with inputs that keep the image dtype (see :func:`dilation`), it equals
``scipy.ndimage.morphological_gradient`` with the matching mode and ``cval=border_value``. For a flat kernel
(no ``structuring_element``) symmetric about its origin it is the value range over each neighborhood.

.. image:: _static/img/gradient.png

Args:
    tensor: floating-point image ``(B, C, H, W)``; another dtype raises ``TypeError``, another rank ``ValueError``.
    kernel: ``(k_h, k_w)`` mask of the neighborhood, as in :func:`dilation`.
    structuring_element: non-flat structuring element, as in :func:`dilation`.
    origin: ``[row, col]`` cell of ``kernel`` placed on the output pixel, as in :func:`dilation`.
    border_type: border handling, as in :func:`dilation`. Default: ``"geodesic"``.
    border_value: fill value for ``border_type="constant"``. Default: ``0.0``.
    max_val: no effect, as in :func:`dilation`.
    engine: computation engine, as in :func:`dilation`. Default: ``"auto"``.

Returns:
    Gradient image ``(B, C, H, W)``, in the dtype :func:`dilation` returns for the same inputs.

See Also:
    - :func:`dilation`: the maximum over the neighborhood, the first term.
    - :func:`erosion`: the minimum over the neighborhood, the second term.
    - :func:`~kornia.filters.sobel`: the magnitude of the Sobel derivatives, from linear filters instead of a
      maximum and a minimum.

.. note::
   See a working example `here <https://www.kornia.org/tutorials/nbs/morphology_101.html>`__.

Example:
    >>> tensor = torch.rand(1, 3, 5, 5)
    >>> kernel = torch.ones(3, 3)
    >>> gradient_img = gradient(tensor, kernel)

rß   ©rÔ   rÜ   rà   s   &&&&&&&&r   Úgradientrè   2  sQ   € ô` ØØØ/ØØØ!ØØô	ô 	ØØØ/ØØØ!ØØô		õð r   c                ó  € V ^8„  d   QhR\         P                  R\         P                  R\        \         P                  ,          R\        \        \        ,          ,          R\
        R\        R\        R\
        R	\         P                  /	# r˜   rœ   )r   s   "r   r   r   w  s‹   € ÷ Hñ HÜ�L‰LðHä�L‰LðHô "¤%§,¡,Õ/ðHô ”Tœ#•YÕð	Hô
 ðHô ðHô ðHô ðHô ‡\�\ñHr   c                óê  € \        V \        P                  4      '       g   \        R\	        V 4       24      h\        V P                  4      ^8w  d   \        RV P                  4        24      h\        V\        P                  4      '       g   \        R\	        V4       24      h\        VP                  4      ^8w  d   \        RVP                  4        24      hV \        V VVVVVVVR7      ,
          # )a&  Extract the bright details the kernel does not fit in: the image minus its opening.

``out = top_hat(tensor, kernel)`` returns ``tensor - opening(tensor, kernel)`` with the same arguments, the
``(B, C, H, W)`` white top-hat: the bright details :func:`opening` removes, on a zero background.

.. image:: _static/img/top_hat.png

Convention:
    Under every ``border_type`` except ``geodesic``, for inputs that keep the image dtype (see
    :func:`dilation`), with the mode mapped as in :doc:`Conventions & Pitfalls </get-started/conventions>` and
    ``cval=border_value``, it equals ``scipy.ndimage.white_tophat``. OpenCV's ``MORPH_TOPHAT``, at its
    default border (kornia's ``geodesic``), ``BORDER_REPLICATE`` or ``BORDER_REFLECT_101``, equals it only for
    a flat kernel (no ``structuring_element``) symmetric about its origin: OpenCV takes no structuring element,
    and ``cv2.dilate`` does not reflect the kernel.

Args:
    tensor: floating-point image ``(B, C, H, W)``; another dtype raises ``TypeError``, another rank ``ValueError``.
    kernel: ``(k_h, k_w)`` mask of the neighborhood, as in :func:`dilation`.
    structuring_element: non-flat structuring element, as in :func:`dilation`.
    origin: ``[row, col]`` cell of ``kernel`` placed on the output pixel, as in :func:`dilation`.
    border_type: border handling, as in :func:`dilation`. Default: ``"geodesic"``.
    border_value: fill value for ``border_type="constant"``. Default: ``0.0``.
    max_val: no effect, as in :func:`dilation`.
    engine: computation engine, as in :func:`dilation`. Default: ``"auto"``.

Returns:
    Top hat transformed image ``(B, C, H, W)``, in the dtype :func:`dilation` returns for the same inputs.

See Also:
    - :func:`bottom_hat`: the closing minus the image, the dark details.
    - :func:`opening`: the image with these details removed.

.. note::
   See a working example `here <https://www.kornia.org/tutorials/nbs/morphology_101.html>`__.

Example:
    >>> tensor = torch.rand(1, 3, 5, 5)
    >>> kernel = torch.ones(3, 3)
    >>> top_hat_img = top_hat(tensor, kernel)

rž   rŸ   r"   r#   rß   )
r-   r   r   r+   r   r.   r/   r0   r1   rá   rà   s   &&&&&&&&r   Útop_hatrë   w  sÕ   € ôf �fœeŸl™l×+Ò+ÜÐ@ÄÀfÃÀÐOÓPÐPä
ˆ6�<‰<Ó˜AÔÜÐBÀ6Ç:Á:Ã<À.ÐQÓRÐRä�fœeŸl™l×+Ò+ÜÐAÄ$ÀvÃ,ÀÐPÓQÐQä
ˆ6�<‰<Ó˜AÔÜÐCÀFÇJÁJÃLÀ>ÐRÓSÐSà”GØØØ/ØØØ!ØØô	õ 	ð 	r   c                ó  € V ^8„  d   QhR\         P                  R\         P                  R\        \         P                  ,          R\        \        \        ,          ,          R\
        R\        R\        R\
        R	\         P                  /	# r˜   rœ   )r   s   "r   r   r   Â  s‹   € ÷ Kñ KÜ�L‰LðKä�L‰LðKô "¤%§,¡,Õ/ðKô ”Tœ#•YÕð	Kô
 ðKô ðKô ðKô ðKô ‡\�\ñKr   c                óê  € \        V \        P                  4      '       g   \        R\	        V 4       24      h\        V P                  4      ^8w  d   \        RV P                  4        24      h\        V\        P                  4      '       g   \        R\	        V4       24      h\        VP                  4      ^8w  d   \        RVP                  4        24      h\        V VVVVVVVR7      V ,
          # )aO  Extract the dark details the kernel does not fit in: the closing of the image minus the image.

``out = bottom_hat(tensor, kernel)`` returns ``closing(tensor, kernel) - tensor`` with the same arguments, the
``(B, C, H, W)`` black top-hat: the dark details :func:`closing` fills, as positive values on a zero background.

.. image:: _static/img/bottom_hat.png

Convention:
    Under every ``border_type`` except ``geodesic``, for inputs that keep the image dtype (see
    :func:`dilation`), with the mode mapped as in :doc:`Conventions & Pitfalls </get-started/conventions>` and
    ``cval=border_value``, it equals ``scipy.ndimage.black_tophat``. OpenCV's ``MORPH_BLACKHAT``, at its
    default border (kornia's ``geodesic``), ``BORDER_REPLICATE`` or ``BORDER_REFLECT_101``, equals it only for
    a flat kernel (no ``structuring_element``) symmetric about its origin: OpenCV takes no structuring element,
    and ``cv2.dilate`` does not reflect the kernel.

Args:
    tensor: floating-point image ``(B, C, H, W)``; another dtype raises ``TypeError``, another rank ``ValueError``.
    kernel: ``(k_h, k_w)`` mask of the neighborhood, as in :func:`dilation`.
    structuring_element: non-flat structuring element, as in :func:`dilation`.
    origin: ``[row, col]`` cell of ``kernel`` placed on the output pixel, as in :func:`dilation`.
    border_type: border handling, as in :func:`dilation`. Default: ``"geodesic"``.
    border_value: fill value for ``border_type="constant"``. Default: ``0.0``.
    max_val: no effect, as in :func:`dilation`.
    engine: computation engine, as in :func:`dilation`. Default: ``"auto"``.

Returns:
    Bottom hat transformed image ``(B, C, H, W)``, in the dtype :func:`dilation` returns for the same inputs.

See Also:
    - :func:`top_hat`: the image minus its opening, the bright details.
    - :func:`closing`: the image with these details filled.

.. note::
   See a working example `here <https://www.kornia.org/tutorials/nbs/morphology_101.html>`__.

Example:
    >>> tensor = torch.rand(1, 3, 5, 5)
    >>> kernel = torch.ones(3, 3)
    >>> bottom_hat_img = bottom_hat(tensor, kernel)

rž   rŸ   r"   r#   rß   )
r-   r   r   r+   r   r.   r/   r0   r1   rä   rà   s   &&&&&&&&r   Ú
bottom_hatrî   Â  sÚ   € ôf �fœeŸl™l×+Ò+ÜÐ@ÄÀfÃÀÐOÓPÐPä
ˆ6�<‰<Ó˜AÔÜÐBÀ6Ç:Á:Ã<À.ÐQÓRÐRä�fœeŸl™l×+Ò+ÜÐAÄ$ÀvÃ,ÀÐPÓQÐQä
ˆ6�<‰<Ó˜AÔÜÐCÀFÇJÁJÃLÀ>ÐRÓSÐSô 	ØØØ 3ØØ#Ø%ØØô		
ð õ
	ðr   c                óÒ   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  R\        \        ,          R\        R\        R\         P                  /# )r   ÚseedÚmaskr   Ú	num_itersÚcheck_everyr‹   r   )r   r   r   r`   r    )r   s   "r   r   r     sb   € ÷ ñ Ü
�,‰,ðä
�,‰,ðô �L‰Lðô œ�}ð	ô
 ðô ðô ‡\�\ñr   c           	      ó`  € \         P                  ! W4      pVe7   \        V4       F%  p\         P                  ! \        WbVR7      V4      pK'  	  V# RpV'       dT   Tp	\        V4       F%  p\         P                  ! \        WbVR7      V4      pK'  	  \	        Wi8„  P                  4       4      pK[  V# )N)r‹   T)r   ry   rv   rÔ   r   Úany)
rð   rñ   r   rò   ró   r‹   r„   rÉ   ÚchangedÚpreviouss
   &&&&&&    r   Ú_reconstruct_uprø     s“   € ô �]Š]˜4Ó&€FàÒÜ�yÖ!ˆAÜ—]’]¤8¨FÀ6Ô#JÈDÓQŠFñ "àˆð €Gß
ØˆÜ�{Ö#ˆAÜ—]’]¤8¨FÀ6Ô#JÈDÓQŠFñ $ä˜Ñ)×.Ñ.Ó0Ó1Šà€Mr   c                óô   € V ^8„  d   QhR\         P                  R\         P                  R\        \         P                  ,          R\        R\        \        ,          R\        R\        R\         P                  /# )	r   rð   rñ   r   Úmethodrò   ró   r‹   r   )r   r   r   r    r`   )r   s   "r   r   r   *  s…   € ÷ kOñ kOÜ
�,‰,ðkOä
�,‰,ðkOô ”U—\‘\Õ"ðkOô ð	kOô
 œ�}ðkOô ðkOô ðkOô ‡\�\ñkOr   c                ól  € \        V 4       \        V4       \        V . RO4       \        W4       \        V P	                  4       RV P
                   R24       \        VP	                  4       RVP
                   R24       \        VR9   RV R24       VR8X  d   \        R4      h\        VR9   R	V R
24       \        VRJ ;'       g    V^ 8¬  RV R24       \        V^8¬  RV R24       Vf3   \        P                  ! ^^V P                  \        P                  R7      p\        V4       \        VRR.4       VP                  w  rx\        V^,          ^8H  ;'       d    V^,          ^8H  RV RV R24       V^ 8g  pRW'^,          V^,          3&   VR8X  d   \        V ) V) W$WV4      ) # \        WW$WV4      # )a©  Reconstruct an image from a seed: dilate it inside a mask until it stops changing.

``out = reconstruction(seed, mask)`` takes two floating-point images ``(B, C, H, W)`` and returns the
``(B, C, H, W)`` image grown from :math:`\min(\text{seed}, \text{mask})` by repeated geodesic dilations
:math:`\min(\delta_B(x), \text{mask})`, until the result stops changing. ``method="erosion"`` is the dual,
:math:`-\text{reconstruction}(-\text{seed}, -\text{mask})`, which lowers a seed toward the mask from above.
``reconstruction(erosion(x, kernel), x)`` is opening by reconstruction: it removes the shapes :func:`opening`
removes and restores the whole of each shape that survives the erosion, thin parts included. The shapes are
connected through ``reconstruction``'s own ``kernel``, a :math:`3 \times 3` square by default; for an erosion
``kernel`` with gaps, such as ``[[1, 0, 1, 0, 1]]``, pass the same ``kernel`` to ``reconstruction``.

Convention:
    - Matches ``skimage.morphology.reconstruction``: the default ``kernel`` is a :math:`3 \times 3` square,
      its center cell is always part of the neighborhood, and both methods spread a pixel's value to the
      kernel's offsets, as :func:`dilation` does. scikit-image's ``dilation`` spreads the other way, but its
      ``reconstruction`` agrees. The image border is ``geodesic``. Unlike scikit-image, a ``seed`` above
      ``mask`` (below it for ``"erosion"``) is clipped to ``mask`` instead of raising.
    - Under autograd every step keeps its intermediates, so memory grows with the number of steps.
    - Reference: L. Vincent, "Morphological grayscale reconstruction in image analysis: applications and
      efficient algorithms", IEEE TIP 1993.

Args:
    seed: floating-point starting image ``(B, C, H, W)``.
    mask: floating-point image bounding the reconstruction, of the same shape as ``seed``.
    kernel: offsets from the center that a pixel's value spreads to in one step, ``(k_h, k_w)`` with odd sizes.
        Non-zero cells mark an offset; their magnitude and dtype are ignored. Default: ``None``, which uses a
        :math:`3 \times 3` square.
    method: ``"dilation"`` (default) or ``"erosion"``.
    num_iters: number of steps to run. Default: ``None``, which runs until the result stops changing.
        That can take far more steps than :math:`\max(H, W)` when ``mask`` has winding paths. A fixed
        count always runs that many steps, even past convergence; ``0`` returns
        :math:`\min(\text{seed}, \text{mask})` for ``"dilation"`` and :math:`\max(\text{seed}, \text{mask})`
        for ``"erosion"``. It has no data-dependent exit, so ``torch.compile`` captures it as one graph, but the
        loop is unrolled and compile time grows with the count.
    check_every: number of steps between convergence checks when ``num_iters`` is ``None``. Each check syncs
        the device with the host, and steps past convergence are wasted, so a larger value suits inputs that
        take many steps. For inputs without NaN, the output does not depend on it. Default: ``4``.
    engine: ``"unfold"``, ``"shift"`` or ``"auto"`` (default), passed to :func:`dilation`. ``"convolution"``
        is rejected: it is not exact on every backend, and an inexact step can keep the loop from converging.

Returns:
    Reconstructed image ``(B, C, H, W)`` in the promoted dtype of ``seed`` and ``mask``.

Raises:
    TypeCheckError: if ``seed``, ``mask`` or ``kernel`` is not a tensor.
    ShapeError: if ``seed`` is not 4-dimensional, ``mask`` has another shape, or ``kernel`` is not
        2-dimensional.
    ValueCheckError: if ``engine`` is ``"convolution"``, also with checks disabled.
    BaseError: if ``seed`` or ``mask`` is not floating point, a ``kernel`` size is even, ``method`` or
        ``engine`` is not one of the values above, ``num_iters`` is negative, or ``check_every`` is not
        positive.

See Also:
    - :func:`dilation`: one step without the mask; ``reconstruction`` repeats it, clipped to ``mask``.
    - :func:`erosion`: the seed of opening by reconstruction.
    - :func:`opening`: also removes the thin parts of the shapes it keeps.

Example:
    >>> mask = torch.rand(1, 3, 5, 5)
    >>> seed = mask * 0.5
    >>> output = reconstruction(seed, mask)

z-`seed` must have a floating-point dtype. Got r$   z-`mask` must have a floating-point dtype. Got rÜ   zUnknown `method`: z#. Expected 'dilation' or 'erosion'.r¦   zOUnsupported `engine`: convolution. Expected one of ['auto', 'unfold', 'shift'].zUnsupported `engine`: z.. Expected one of ['auto', 'unfold', 'shift'].Nz&`num_iters` must be non-negative. Got z$`check_every` must be positive. Got )r   r,   ÚKHÚKWzKernel sizes must be odd. Got z x T)rÊ   rË   rÌ   rÍ   rç   )r�   rŽ   r�   )r   r	   r   r   r*   r,   r
   r   r½   r   r   r/   rø   )	rð   rñ   r   rú   rò   ró   r‹   rÁ   rÂ   s	   &&&&&&&  r   Úreconstructionrþ   *  sÐ  € ôP ˜4Ô Ü˜4Ô Ü�tÒ1Ô2Ü˜DÔ'Ü�×'Ñ'Ó)Ð-ZÐ[_×[eÑ[eÐZfÐfgÐ+hÔiÜ�×'Ñ'Ó)Ð-ZÐ[_×[eÑ[eÐZfÐfgÐ+hÔiÜ�Ð2Ñ2Ð6HÈÈÐPsÐ4tÔuð �ÔÜÐoÓpÐpÜØÐ-Ñ-Ø
   Ð(VÐWôô �˜dÐ"×4Ð4 i°1¡nÐ8^Ð_hÐ^iÐijÐ6kÔlÜ� Ñ!Ð%IÈ+ÈÐVWÐ#XÔYà‚~Ü—’˜A˜q¨¯©¼E¿J¹JÔGˆä˜6Ô"Ü�v  d˜|Ô,Ø—‘�J€DÜ�˜•˜Q‘×0Ð0 4¨!¥8¨q¡=Ð4RÐSWÐRXÐX[Ð\`Ð[aÐabÐ2cÔdð
 �q‰[€FØ#'€F�1�9�d˜a•iÐÑ à�ÔÜ  ¨ u¨fÀÓUÐUÐUä˜4 v¸+ÓNÐNr   c                óV   € V ^8„  d   Qh/ ^ \         9   d   \        \        ,          ;R&   # )r   Ú_MPS_MAXIMUM_IGNORES_NAN)Ú__conditional_annotations__r   r   )r   s   "r   r   r      s#   € ÷ ñ ÷" BÒ Aœ%¤�+Ñ Aò#r   )rî   rä   rÔ   rÜ   rè   rá   rþ   rë   )FN)NNr%   r¥   g     ˆÃ@r�   )NrÔ   Né   r�   )+r  Ú__doc__Útypingr   r   r   r   Útorch.nn.functionalÚnnÚ
functionalrµ   Úkornia.core._compatr   Úkornia.core.checkr   r   r   r	   Úkornia.core.exceptionsr
   Ú__all__r   r   r2   r;   rJ   ÚunusedrO   rX   rd   r‰   r“   r–   rÔ   rÜ   rá   rä   rè   rë   rî   rø   rþ   r   )r  s   @r   Ú<module>r     sï   øðö$÷ )Ñ (ã ß Ð å 0ß oÓ oÝ 2â
n€á(8¸¸A¸qÓ(AÐ Ó Að H`÷ 4õ
õ*'ð ‡�×Ñôdó ðdð ‡�×Ñô7ó ð7õ2õ$a÷H-õ`Q÷"@"÷Fj÷ZR÷jP÷hB÷JH÷VKõ\÷4kOñ kOr   