+
    ÿäûjÁO  ã                  óú   € R t ^ RIHt ^ RIHtHtHt ^ RIt^ RIHt ^ RI	H
t
 ^ RIHt ^ RIHt ^ RIHt ^ R	IHtHtHtHt ^ R
IHt ^ RIHt ^ RIHt ^ RIHt ^ RIHtH t  RR.t! ! R R]]4      t" ! R R4      t#R# )aA  Detect edges in RGB images with a network, resized back to each image's size.

Which class to use:

- Edge probabilities from the pretrained DexiNed network, with the input conversion it was trained on:
  :class:`EdgeDetectorBuilder`.
- Your own edge network with its own pre- and post-processing: :class:`EdgeDetector`.
)Úannotations)ÚAnyÚOptionalÚUnionN)Únn)Úgrayscale_to_rgb)ÚRgbToBgr)ÚPILImage)Úonnx)ÚONNXExportMixinÚ_has_forward_hooksÚ_preserved_rngÚ_returns_per_image_outputs)Ú	Normalize)Úresize)Ú	ModelBase)ÚDexiNed)ÚResizePostProcessorÚResizePreProcessorÚEdgeDetectorÚEdgeDetectorBuilderc                  óþ   a € ] tR t^0t$ RtRtR]R&   RtR]R&   RR V 3R	 lllt]	R
 R l4       t
]P                  ! 4       R R l4       tR R ltR R 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 ltRtV ;t# )!r   aê  Run an edge network on RGB images and resize its maps back to each image's size.

``edges = EdgeDetector(model, pre_processor, post_processor)(images)`` runs ``pre_processor``, ``model`` and
``post_processor`` on a ``(B, 3, H, W)`` tensor or a list of ``(3, H, W)`` images and returns what the
post-processor returns. With a ``ResizePostProcessor``, that is a list with one ``(1, C, H, W)`` map per image, at
that image's size (``C = 1`` for DexiNed).

Args:
    model: The edge detection model.
    pre_processor: Pre-processing module (e.g., ResizePreProcessor).
    post_processor: Post-processing module (e.g., ResizePostProcessor).
    name: Optional name for the detector, used in the file names of ``save`` and ``to_onnx``.

See Also:
    - :class:`~kornia.contrib.edge_detection.EdgeDetectorBuilder`: builds this wrapper around the pretrained
      DexiNed network.
    - :func:`~kornia.filters.canny`: edges from image gradients with hysteresis thresholds, without a network or
      a download.

Example:
    >>> detector = EdgeDetectorBuilder.build("dexined", pretrained=True, image_size=352)
    >>> img = torch.rand(1, 3, 320, 320)  # RGB in [0, 1]
    >>> out = detector(img)  # a list with one (1, 1, 320, 320) edge probability map per image

Úedge_detectionÚstrÚnameFÚboolÚ_exporting_to_onnxc          
     ó,   € V ^8„  d   QhRRRRRRRRRR/# )	é   Úmodelztorch.nn.ModuleÚpre_processorÚpost_processorr   úOptional[str]ÚreturnÚNone© )Úformats   "ÚYC:\Ai_Coding\apps\studio\ComfyUI\.venv\Lib\site-packages\kornia\contrib\edge_detection.pyÚ__annotate__ÚEdgeDetector.__annotate__O   s<   € ÷ ñ àðð 'ðð (ð	ð
 ðð 
ñó    c                ó~   <€ \         SV `  4        VP                  4       V n        W n        W0n        Ve	   W@n        R# R# )zýInitialize EdgeDetector.

Args:
    model: The edge detection model.
    pre_processor: Pre-processing module (e.g., ResizePreProcessor).
    post_processor: Post-processing module (e.g., ResizePostProcessor).
    name: Optional name for the detector.

N)ÚsuperÚ__init__Úevalr   r    r!   r   )Úselfr   r    r!   r   Ú	__class__s   &&&&&€r'   r-   ÚEdgeDetector.__init__O   s9   ø€ ô  	‰ÑÔØ—Z‘Z“\ˆŒ
Ø*ÔØ,ÔØÒØŽIñ r*   c               ó    € V ^8„  d   QhRRRR/# )r   Úconfigr   r#   r   r%   )r&   s   "r'   r(   r)   g   s   € ÷ 
ñ 
˜Cð 
 Lñ 
r*   c                ó   € \        R4      h)zíRaise ``NotImplementedError``: build with :meth:`~kornia.contrib.edge_detection.EdgeDetectorBuilder.build`.

Args:
    config: Configuration object (not used, kept for interface compatibility).

Raises:
    NotImplementedError: Always.

ztEdgeDetector.from_config() is not implemented. Use EdgeDetectorBuilder.build() or instantiate EdgeDetector directly.)ÚNotImplementedError)r3   s   &r'   Úfrom_configÚEdgeDetector.from_configf   s   € ô "ðTó
ð 	
r*   c               ó    € V ^8„  d   QhRRRR/# )r   Úimagesú'Union[torch.Tensor, list[torch.Tensor]]r#   r%   )r&   s   "r'   r(   r)   w   s   € ÷ &<ñ &<ÐEð &<ÐJqñ &<r*   c                óò  € V P                   '       g%   \        P                  P                  4       '       dŽ   \	        V\        P
                  4      '       dn   V P                  4       '       dX   V P                  4       pVP                  RR w  r4V P                  V P                  V4      ^ ,          4      p\        WSV3VR7      # V P                  V4      w  rV P                  V4      pV P                  WV4      # )aâ  Forward pass of the edge detection model.

Args:
    images: If list of RGB images. Each image is a torch.Tensor with shape ``(3, H, W)``.
        If torch.Tensor, a torch.Tensor with shape ``(B, 3, H, W)``. For a detector from
        :py:class:`~kornia.contrib.edge_detection.EdgeDetectorBuilder`, the pixel values are in
        :math:`[0, 1]`.

Returns:
    With a ``ResizePostProcessor``, a list with one output of shape ``(1, C, H, W)`` per input image,
    resized back to that image's size. For a detector from
    :py:class:`~kornia.contrib.edge_detection.EdgeDetectorBuilder`, it holds edge probabilities in
    :math:`[0, 1]`. Under an ONNX export with a ``ResizePostProcessor``, one
    ``(B, C, H, W)`` tensor at the input's size instead, see :meth:`to_onnx`.

Raises:
    ValueError: Under an ONNX export through :meth:`to_onnx`, or a direct one on the TorchScript exporter or,
        from torch 2.9, the dynamo exporter, if the ``ResizePostProcessor`` resizes with ``"area"``.

N)Úinterpolationéþÿÿÿ)r   Útorchr
   Úis_in_onnx_exportÚ
isinstanceÚTensorÚ_resizes_back_on_exportÚ_export_interpolationÚshaper   r    r   r!   )r/   r9   r<   ÚheightÚwidthÚ
out_imagesÚimage_sizess   &&     r'   ÚforwardÚEdgeDetector.forwardv   sÅ   € ð. ×$×$Ð$¬¯
©
×(DÑ(D×(FÒ(FÜ˜6¤5§<¡<×0Ò0Ø×,Ñ,×.Ò.ð !×6Ñ6Ó8ˆMØ"ŸL™L¨¨Ð-‰MˆFØŸ™ D×$6Ñ$6°vÓ$>¸qÕ$AÓBˆJÜ˜*¨u oÀ]ÔSÐSØ"×0Ñ0°Ó8ÑˆØ—Z‘Z Ó'ˆ
Ø×"Ñ" :Ó;Ð;r*   c               ó   € V ^8„  d   QhRR/# ©r   r#   r   r%   )r&   s   "r'   r(   r)   Ÿ   s   € ÷ 
ñ 
¨ñ 
r*   c                ó¤   € \        V P                  \        4      ;'       d0    \        V P                  4      P                  \        P                  J # )zºWhether an export replaces the post-processor: a ``ResizePostProcessor`` that keeps its own ``forward``.

A subclass that overrides ``forward`` is exported as that ``forward`` computes.
)r@   r!   r   ÚtyperI   ©r/   s   &r'   rB   Ú$EdgeDetector._resizes_back_on_exportŸ   sF   € ô �t×*Ñ*Ô,?Ó@÷ Qð QÜ�T×(Ñ(Ó)×1Ñ1Ô5H×5PÑ5PÐPð	
r*   c               ó   € V ^8„  d   QhRR/# rL   r%   )r&   s   "r'   r(   r)   ©   s   € ÷ 
ñ 
¨tñ 
r*   c                ó°   € V P                  4       ;'       d@    \        V P                  RR4      \        P                  J ;'       d    \	        V 4      '       * # )aÀ  Whether an export returns the maps of the batch as one tensor, so ``to_onnx`` reads no output kind.

That holds for a post-processor the export replaces (:meth:`_resizes_back_on_export`) under this class's own
:meth:`forward`, with no forward hook on the detector, on a module inside it or on all modules. Any other
detector is probed; with such a post-processor the probe reads the eager per-image list and the detector is
exported for one image.
Ú__func__N)rB   ÚgetattrrI   r   r   rO   s   &r'   Ú_returns_one_tensor_on_exportÚ*EdgeDetector._returns_one_tensor_on_export©   sO   € ð ×(Ñ(Ó*÷ -ð -Ü˜Ÿ™ j°$Ó7¼<×;OÑ;OÐO÷-ð -ä& tÓ,Ô,ð	
r*   c               ó   € V ^8„  d   QhRR/# )r   r#   r   r%   )r&   s   "r'   r(   r)   ·   s   € ÷ ñ  sñ r*   c                óV   € V P                   P                  pVR8X  d   \        R4      hV# )zºThe post-processor's interpolation mode, which an export resizes the maps back with.

Raises:
    ValueError: For ``"area"``, which an exported graph cannot compute at the input's size.
Úareaa2  A ResizePostProcessor with interpolation_mode="area" cannot be exported with the input's size: "area" resizing is adaptive average pooling, which an exported graph cannot compute to a size known only at run time. Build the post-processor with "bilinear", "bicubic", "nearest" or "nearest-exact" for export.)r!   Úinterpolation_modeÚ
ValueError)r/   r<   s   & r'   rC   Ú"EdgeDetector._export_interpolation·   s7   € ð ×+Ñ+×>Ñ>ˆØ˜FÔ"Üðóð ð Ðr*   c               ó(   € V ^8„  d   QhRRRRRRRR/# )	r   r9   r:   Ú	edge_mapsú1Optional[Union[torch.Tensor, list[torch.Tensor]]]Úoutput_typer   r#   z:Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]r%   )r&   s   "r'   r(   r)   Ç   s4   € ÷ 9ñ 9à7ð9ð Eð9ð ð	9ð
 
Dñ9r*   c                ó¦   € Vf   V P                  V4      p. pV F$  pVP                  \        V4      ^ ,          4       K&  	  V P                  WC4      # )a“  Turn one-channel edge maps into grey RGB images; an edge map with another ``C`` raises ``ValueError``.

Args:
    images: input torch.Tensor.
    edge_maps: detected edges; computed with :meth:`forward` when None.
    output_type: ``"torch"`` or ``"pil"``.

Returns:
    A list with one ``(3, H, W)`` image per edge map, its one channel repeated, or a list of PIL images for
    ``output_type="pil"``.

)rI   Úappendr   Ú_tensor_to_type)r/   r9   r^   r`   ÚoutputÚedge_maps   &&&&  r'   Ú	visualizeÚEdgeDetector.visualizeÇ   sQ   € ð$ ÒØŸ™ VÓ,ˆIØˆÛ!ˆHØ�M‰MÔ*¨8Ó4°QÕ7Ö8ñ "ð ×#Ñ# FÓ8Ð8r*   c          
     ó,   € V ^8„  d   QhRRRRRRRRR	R
/# )r   r9   r:   r^   r_   Ú	directoryr"   r`   r   r#   r$   r%   )r&   s   "r'   r(   r)   á   s=   € ÷ ?ñ ?à7ð?ð Eð?ð !ð	?ð
 ð?ð 
ñ?r*   c                óv   € V P                  WV4      pV P                  WRR7       V P                  WSRR7       R# )a  Save the input images and their edge maps as PNG files.

Args:
    images: input torch.Tensor.
    edge_maps: detected edges; computed with :meth:`forward` when None.
    directory: where to save outputs.
    output_type: ``"torch"`` or ``"pil"``, passed to :meth:`visualize`.

Ú_src)ÚsuffixÚ_edgeN)rf   Ú_save_outputs)r/   r9   r^   ri   r`   Úoutputss   &&&&& r'   ÚsaveÚEdgeDetector.saveá   s:   € ð  —.‘. °KÓ@ˆØ×Ñ˜6°VÐÔ<Ø×Ñ˜7°gÐÖ>r*   c               ó4   € V ^8„  d   QhRRRRRRRRRR	R
RRR/# )r   Ú	onnx_namer"   Ú
image_sizezOptional[int]Úinclude_pre_and_post_processorr   rp   Úadditional_metadatazOptional[list[tuple[str, str]]]Úkwargsr   r#   zonnx.ModelProtor%   )r&   s   "r'   r(   r)   õ   sY   € ÷ _/ñ _/à ð_/ð "ð_/ð )-ð	_/ð
 ð_/ð =ð_/ð ð_/ð 
ñ_/r*   c                óN  € Vf   RV P                    RV R2pV'       d'   V P                  4       '       d   V P                  4        ^^T;'       g    RT;'       g    R.pV P                  pRV n         Rp	V'       dR   V P	                  4       '       g<   \        4       ;_uu_ 4        \        V \        P                  ! V4      4      p	RRR4       V	'       d   ^MRp
V P                  V	4      ;_uu_ 4        \        P                  ! V V3RT
^T;'       g    RT;'       g    R.RT
^T;'       g    RT;'       g    R.R	TR
V'       d   T MV P                  RVRV/VB uuRRR4       W€n        #   + '       g   i     L®; i  + '       g   i     M; i Y€n        R#   Y€n        i ; i)aô  Export the current edge detection model to an ONNX model file.

The graph takes one ``(B, 3, H, W)`` tensor. With the pre- and post-processor and a
``ResizePostProcessor``, it returns the edge maps of the batch as one ``(B, 1, H, W)`` tensor at the
input's size, resized with the post-processor's ``"bilinear"``, ``"bicubic"``, ``"nearest"`` or
``"nearest-exact"`` mode: the ``torch.cat`` of the list that :meth:`forward` returns. A subclass of
``ResizePostProcessor`` that overrides ``forward`` is exported as its ``forward`` computes. Export through
this method rather than ``torch.onnx.export(detector, ...)``: below torch 2.9, a direct
``torch.onnx.export(..., dynamo=True)`` traces the eager per-image list instead.

Args:
    onnx_name:
        The name of the output ONNX file. If not provided, ``"kornia_<name>_<image_size>.onnx"``, for
        example ``"kornia_dexined_352.onnx"`` (``"kornia_dexined_None.onnx"`` for ``image_size=None``).
    image_size:
        The height and width of the graph's input, which the returned maps have too. If None, both are
        dynamic. With the pre- and post-processor, the pre-processor resizes the input to the size it was
        built with, whatever ``image_size`` is; without them, the model runs at the size of its input.
    include_pre_and_post_processor:
        Whether to include the pre-processor and post-processor in the exported model.
    save:
        If True, write the model to ``onnx_name``; it is returned either way.
    additional_metadata:
        Additional metadata to add to the ONNX model.
    kwargs: Additional keyword arguments of :func:`torch.onnx.export`.

Returns:
    The exported ONNX model.

Raises:
    ValueError: With the pre- and post-processor, if the ``ResizePostProcessor`` resizes with ``"area"``:
        adaptive average pooling cannot be exported with the input's size; or if the post-processor returns
        a list (or tuple) with one map per image and the exported batch is dynamic, from a ``dynamic_axes`` or
        ``dynamic_shapes`` argument or, with the TorchScript exporter, because the list comes only for more
        than one image.

Note:
    With the pre- and post-processor, a detector whose post-processor returns a list with one map per image,
    or a tuple as long as the batch at two batch sizes, is exported for a batch of one image: the exporters
    turn such a sequence into one graph output per traced image, so a dynamic batch would return the traced
    batch's maps at any batch size. A ``ResizePostProcessor`` that keeps
    its own ``forward`` is not such a post-processor, since the export replaces it, as long as the detector
    keeps :meth:`forward` as this class defines it and no forward hook applies to it. Which kind of output
    any other detector returns is read from one forward pass of the detector for one image at the export
    size, in eval mode, without gradients and outside the export. A ``forward`` that returns a list there is
    therefore exported for one image even if it returns a tensor under export, as a ``ResizePostProcessor``
    subclass whose own ``forward`` calls ``ResizePostProcessor.forward`` does. A tensor there is read again at
    the batch a dynamic export traces, since the kind can depend on the batch size. Return the maps of the
    batch as one tensor to export a batch of any size. A ``dynamic_axes`` or ``dynamic_shapes`` argument that
    makes the batch of such an export dynamic raises a ``ValueError`` after the export, before anything is
    saved. A post-processor that returns a list only for more than one image has no dynamic export either: the
    TorchScript exporter's graph raises that ``ValueError``, the dynamo exporter of torch 2.9 and later fails to
    trace it, and that of torch 2.5.1 fixes the batch at the two images it traces.

NÚkornia_Ú_z.onnxé`  TÚinput_shapeÚoutput_shapeÚpseudo_shaper   rp   rv   éÿÿÿÿ)r   rB   rC   r   rU   r   r   r>   ÚrandÚ_onnx_output_kind_keptr   Úto_onnxr   )r/   rs   rt   ru   rp   rv   rw   r~   ÚpreviousÚ	per_imageÚbatchs   &&&&&&,    r'   r‚   ÚEdgeDetector.to_onnxõ   s–  € ð@ ÒØ! $§)¡) ¨A¨j¨\¸Ð?ˆIß)¨d×.JÑ.J×.LÒ.LØ×&Ñ&Ô(Ø˜1˜j×/Ð/¨C°×1BÐ1B¸sÐCˆà×*Ñ*ˆØ"&ˆÔð	/ð ˆIß-°d×6XÑ6X×6ZÒ6Zô $×%Õ%Ü :¸4ÄÇÂÈLÓAYÓ Z�I÷ &ç"‘A¨ˆEØ×,Ñ,¨Y×7Õ7Ü&×.Ò.ØØñ
ð "'¨¨:×+;Ð+;¸¸Z×=MÐ=MÈ2Ð Nð
ð #(¨¨J×,<Ð,<¸"¸j×>NÐ>NÈBÐ!Oð	
ð
 ".ð
÷ #A™$ÀdÇjÁjð
ð ð
ð )<ð
ð ñ
÷ 8Ñ7ð '/Õ#÷! &×%ú÷ 8×7úÐ7ð '/Ö#ø hÕ#úsf   Á4	F Á>F ÂF Â&!E-ÃF ÃF Ã4*F ÄF Ä.
F Ä9F ÅF Å
F Å-E=	Å8F Æ F	ÆF ÆF$c               ó$   € V ^8„  d   QhRRRRRR/# )r   Úmoduler   Údummy_inputr#   r"   r%   )r&   s   "r'   r(   r)   V  s!   € ÷ 
ñ 
¨Sð 
¸sð 
À}ñ 
r*   c                	óp   € WJg.   V P                  4       '       g   V P                  V4      '       g   R #  R# )Nz³Use a post-processor that returns the maps of the batch as one tensor, or a ResizePostProcessor, which the export replaces with one resize of the batch, to export a dynamic batch.)rU   Ú_onnx_returns_per_image_outputs)r/   rˆ   r‰   s   &&&r'   Ú_onnx_fixed_batch_hintÚ#EdgeDetector._onnx_fixed_batch_hintV  s8   € ð ÓØ×1Ñ1×3Ò3Ø×7Ñ7¸×DÒDáð[ñ	
r*   )r   r   r   r!   r    )N)Nr>   )NNr>   )Nr{   TTN)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r   Ú__annotations__r   r-   Ústaticmethodr6   r>   Úinference_moderI   rB   rU   rC   rf   rp   r‚   rŒ   Ú__static_attributes__Ú__classcell__)r0   s   @r'   r   r   0   s…   ø‡ ñð4 !€Dˆ#Ó à$Ð˜Ó$÷ò ð. ô
ó ð
ð ×ÒÓô&<ó ð&<õP
õ
õ÷ 9÷4?÷(_/÷B
ó 
r*   c                  ó4   € ] tR tRtRt]RR R ll4       tRtR# )r   ie  av  Build an EdgeDetector around the pretrained DexiNed edge network.

``detector = EdgeDetectorBuilder.build()`` returns a :class:`~kornia.contrib.EdgeDetector`, downloading the
DexiNed weights on first use. ``edges = detector(images)`` takes RGB images in :math:`[0, 1]` and returns a list
with one ``(1, 1, H, W)`` map of edge probabilities in :math:`[0, 1]` per image, at that image's size.

See Also:
    - :class:`~kornia.contrib.EdgeDetector`: the wrapper it returns, for your own edge network.
    - :func:`~kornia.filters.canny`: edges from image gradients with hysteresis thresholds, without a network or
      a download.

c               ó(   € V ^8„  d   QhRRRRRRRR/# )	r   Ú
model_namer   Ú
pretrainedr   rt   Úintr#   r   r%   )r&   s   "r'   r(   Ú EdgeDetectorBuilder.__annotate__t  s*   € ÷ %
ñ %
˜#ð %
°tð %
ÐPSð %
Ð^jñ %
r*   c           
     óÄ  € V P                  4       R8X  dž   \        P                  ! . RO.4      p\        P                  ! \        4       \        VR,          \        P                  ! R	.^,          .4      R7      4      p\        P                  ! V\        VR7      \        P                  ! 4       4      pM\        RV  R24      h\        V\        W"4      \        4       RR7      # )
as  Build an edge detection model.

The detector takes RGB images in :math:`[0, 1]`. For ``"dexined"`` it flips them to BGR, scales them to
:math:`[0, 255]` and subtracts the BGR mean ``[103.939, 116.779, 123.68]``, the input the pretrained DexiNed
was trained on (xavysp/DexiNed@d944b70), then applies a sigmoid to the network's logits.

Args:
    model_name: Name of the model to build. Only ``"dexined"`` (any case) is supported; another name raises
        ``ValueError``.
    pretrained: If True, loads pretrained weights; otherwise the network is randomly initialized.
    image_size: Size to which input images will be resized during preprocessing.

Returns:
    EdgeDetector instance configured with the specified model.

Example:
    >>> detector = EdgeDetectorBuilder.build(pretrained=True, image_size=352)
    >>> img = torch.rand(1, 3, 320, 320)
    >>> out = detector(img)

Údexinedg     ào@)ÚmeanÚstd)r›   zModel z) not found. Please choose from 'dexined'.)r   )gj¼t“üY@g`åÐ"Û1]@gìQ¸…ë^@gp?)Úlowerr>   Útensorr   Ú
Sequentialr   r   r   ÚSigmoidr[   r   r   r   )rš   r›   rt   Úmean_bgrÚto_bgrr   s   &&&   r'   ÚbuildÚEdgeDetectorBuilder.builds  s³   € ð. ×ÑÓ Ô*ô —|’|Ò%?Ð$@ÓAˆHÜ—]’]¤8£:¬y¸hÈÕ>NÔTY×T`ÒT`ÐcnÐboÐrsÕbsÐatÓTuÔ/vÓwˆFÜ—M’M &¬'¸ZÔ*HÌ"Ï*Ê*Ë,ÓW‰Eä˜v j \Ð1ZÐ[Ó\Ð\äØÜ˜zÓ6ÜÓ!Øô	
ð 	
r*   r%   N)rŸ   Tr{   )rŽ   r�   r�   r‘   r’   r”   r¨   r–   r%   r*   r'   r   r   e  s   † ñð ö%
ó ô%
r*   )$r’   Ú
__future__r   Útypingr   r   r   r>   r   Úkornia.color.grayr   Úkornia.color.rgbr   Úkornia.core.externalr	   ÚImager
   Úkornia.core.mixin.onnxr   r   r   r   Úkornia.enhance.normalizer   Úkornia.geometry.transformr   Úkornia.models.baser   Úkornia.models.dexinedr   Úkornia.models.processorsr   r   Ú__all__r   r   r%   r*   r'   Ú<module>r·      sb   ðñ$õ #ç 'Ñ 'ã Ý å .Ý %Ý 2Ý %ß rÓ rÝ .Ý ,Ý (Ý )ß LàÐ0Ð
1€ôr
�9˜oô r
÷j	4
ó 4
r*   