+
     åûj�y  ã                  ó¤  € R t ^ RIHt ^ RIHt ^ RIHt ^ RIHtH	t	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Ot" ! R R]4      t#]! RR7       ! R R4      4       t$]! RR7       ! R R4      4       t%R R lt& ! R R]]4      t' ! R R]PP                  ]4      t) ! R R4      t*R# ) aî  Detect objects in RGB images with a network, then filter the detections or convert them to Python objects.

A detection is a row ``(class_id, score, x, y, w, h)``: the box's top-left corner, width and height in the pixels of
the input image.

Which class to use:

- Objects of the 80 COCO classes, from a pretrained RT-DETR network: :class:`RTDETRDetectorBuilder`.
- Your own detection network with its own pre- and post-processing: :class:`ObjectDetector`.
- Keep the detections above a score and in given classes: :class:`BoxFiltering`.
- The detections of one image as Python objects: :func:`results_from_detections`, which returns
  :class:`ObjectDetectorResult` items holding a :class:`BoundingBox` tagged with a :class:`BoundingBoxDataFormat`.
)Úannotations)Ú	dataclass)ÚEnum)ÚAnyÚClassVarÚListÚOptionalÚUnionN)Únn)Ú_get_by_name)ÚKORNIA_CHECK_SHAPE)ÚPILImage)Úonnx)ÚONNXExportMixinÚ_preserved_rngÚ_returns_per_image_outputsÚ_uses_dynamic_shapes)Údraw_rectangle)Ú	ModelBase)ÚResizePreProcessorÚBoundingBoxÚBoundingBoxDataFormatÚBoxFilteringÚObjectDetectorÚObjectDetectorResultÚRTDETRDetectorBuilderc                  ó*   € ] tR t^=tRt^ t^t^t^tRt	R# )r   aE  Name the layout of the four values of a BoundingBox: xywh, xyxy or center xywh.

``BoundingBoxDataFormat.XYWH`` tags a :class:`BoundingBox` whose values are the top-left ``x, y``, the width and
the height; ``XYXY`` the top-left and bottom-right corners; ``CXCYWH`` the center, the width and the height.
``CENTER_XYWH`` is another name of ``CXCYWH``, the same member.

See Also:
    - :class:`BoundingBox`: the box whose values this names.
    - :class:`~kornia.geometry.boxes.Boxes`: a batch of boxes as tensors, converted between the ``xyxy``,
      ``xywh`` and corner layouts.

© N)
Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__ÚXYWHÚXYXYÚCXCYWHÚCENTER_XYWHÚ__static_attributes__r   ó    Ú[C:\Ai_Coding\apps\studio\ComfyUI\.venv\Lib\site-packages\kornia\contrib\object_detection.pyr   r   =   s   † ñð €DØ€DØ€FØ„Kr(   T)Úfrozenc                  ó0   € ] tR t^Wt$ RtR]R&   R]R&   RtR# )r   a  Hold one box as four Python floats tagged with their BoundingBoxDataFormat.

``box = BoundingBox(data=(x, y, w, h), data_format=BoundingBoxDataFormat.XYWH)`` is a frozen dataclass: ``data``
holds the four values and ``data_format`` says how to read them; nothing converts or checks them.
:func:`results_from_detections` builds one per detection.

Args:
    data: tuple of bounding box data. The length of the tuple depends on the data format.
    data_format: bounding box data format.

See Also:
    - :class:`BoundingBoxDataFormat`: the layouts that ``data_format`` names.
    - :class:`ObjectDetectorResult`: one detection, holding this box with its class and confidence.
    - :class:`~kornia.geometry.boxes.Boxes`: a batch of boxes as tensors, with layout conversions.

z!tuple[float, float, float, float]Údatar   Údata_formatr   N©r   r   r    r!   r"   Ú__annotations__r'   r   r(   r)   r   r   W   s   ‡ ñð" ,Ó+Ø&×&r(   c                  ó:   € ] tR t^nt$ RtR]R&   R]R&   R]R&   RtR	# )
r   a`  Hold one detection as a class id, a confidence and a BoundingBox.

``result = ObjectDetectorResult(class_id, confidence, bbox)`` is a frozen dataclass of Python values.
:func:`results_from_detections` builds one per row of the ``(D, 6)`` detections of an image.

Args:
    class_id: class id of the detected object.
    confidence: confidence score of the detected object.
    bbox: bounding box of the detected object, whose ``data_format`` says the layout of its values.

See Also:
    - :func:`results_from_detections`: builds these from a detection tensor.
    - :class:`BoundingBox`: the box it holds.

ÚintÚclass_idÚfloatÚ
confidencer   Úbboxr   Nr.   r   r(   r)   r   r   n   s   ‡ ñð  ƒMØÓØ
×r(   c               ó$   € V ^8„  d   QhRRRRRR/# )é   Ú
detectionsútorch.TensorÚformatzstr | BoundingBoxDataFormatÚreturnzlist[ObjectDetectorResult]r   )r:   s   "r)   Ú__annotate__r<   …   s$   € ÷ ,ñ ,Øð,Ø&Að,àñ,r(   c                ó¢  € \        V RR.4       \        V\        4      '       d   \        \        W4      p. pV  F’  pVP                  4       P                  4       p\        V4      ^8w  d   K3  VP                  \        \        V^ ,          4      V^,          \        V^,          V^,          V^,          V^,          3VR7      R7      4       K”  	  V# )aq  Convert the ``(D, 6)`` detections of one image to a list of ObjectDetectorResult.

``results = results_from_detections(dets, "xywh")`` takes ``D`` rows ``(class_id, score, b0, b1, b2, b3)`` and
returns ``D`` :class:`ObjectDetectorResult` items. ``format`` only tags each
:class:`BoundingBox`: the four box values are copied, not converted, so pass the layout the detections are in,
``"xywh"`` for those of :class:`ObjectDetector`.

Args:
    detections: torch.Tensor with shape ``(D, 6)``, where :math:`D` is the number of
        detections in the given image: the class id, the score and the four box values.
    format: the layout of the box values, a :class:`BoundingBoxDataFormat` or its name in any case.

Returns:
    list of :class:`ObjectDetectorResult`, one per row, in the order of the rows.

Raises:
    ShapeError: If ``detections`` is not ``(D, 6)``.
    ValueError: If ``format`` names no :class:`BoundingBoxDataFormat`.

See Also:
    - :class:`BoxFiltering`: keeps the rows above a score and in given classes, before the conversion.
    - :class:`ObjectDetector`: returns one detection tensor per image in this layout.

ÚDÚ6)r,   r-   )r2   r4   r5   )r   Ú
isinstanceÚstrr   r   ÚsqueezeÚtolistÚlenÚappendr   r1   r   )r8   r:   ÚresultsÚdets   &&  r)   Úresults_from_detectionsrH   …   s®   € ô6 �z C¨ :Ô.ä�&œ#×ÒÜÔ3°VÓDˆà*,€GÛˆØ�k‰k‹m×"Ñ"Ó$ˆÜˆs‹8�qŒ=ÙØ�‰Ü Ü˜S �V›Ø˜q�6Ü  s¨1¥v¨s°1­v°s¸1µv¸sÀ1½vÐ&FÐTZÔ[ôö	
ñ	 ð €Nr(   c                  óð   a € ] tR t^´t$ RtRtR]R&   R V 3R llt]R R l4       t	]
P                  ! 4       R	 R
 l4       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RRRRRRRRR/R R lltRtV ;t# )"r   a¨  Run a detection network on RGB images and return per-image (class, score, xywh box) rows.

``detector = ObjectDetector(model, pre_processor, post_processor)`` wraps a detection network.
``dets = detector(images)`` takes a ``(B, 3, H, W)`` tensor or a list of ``(3, H, W)`` images, runs
``pre_processor``, ``model`` and ``post_processor`` in turn, and returns what the post-processor returns.

See Also:
    - :class:`RTDETRDetectorBuilder`: builds this wrapper around a pretrained RT-DETR network.
    - :class:`BoxFiltering`: keeps the detections above a score and in given classes.
    - :func:`results_from_detections`: converts the detections of one image to Python objects.

Ú	detectionrA   Únamec               ó(   € V ^8„  d   QhRRRRRRRR/# )r7   Úmodelz	nn.ModuleÚpre_processorÚpost_processorr;   ÚNoner   )r:   s   "r)   r<   ÚObjectDetector.__annotate__Ä   s*   € ÷ -ñ -˜ið -¸	ð -ÐS\ð -Ðaeñ -r(   c                óf   <€ \         SV `  4        VP                  4       V n        W n        W0n        R# )zÔInitialize ObjectDetector.

Args:
    model: The object detection model.
    pre_processor: Pre-processing module (e.g., ResizePreProcessor).
    post_processor: Post-processing module (e.g., DETRPostProcessor).
N)ÚsuperÚ__init__ÚevalrM   rN   rO   )ÚselfrM   rN   rO   Ú	__class__s   &&&&€r)   rT   ÚObjectDetector.__init__Ä   s)   ø€ ô 	‰ÑÔØ—Z‘Z“\ˆŒ
Ø*ÔØ,Ör(   c               ó    € V ^8„  d   QhRRRR/# )r7   Úconfigr   r;   r   r   )r:   s   "r)   r<   rQ   Ò   s   € ÷ 
ñ 
˜Cð 
 Nñ 
r(   c                ó   € \        R4      h)zãRaise ``NotImplementedError``: build with :meth:`RTDETRDetectorBuilder.build` or the constructor.

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

Raises:
    NotImplementedError: Always.

zšObjectDetector.from_config() is not implemented. Use kornia.contrib.object_detection.RTDETRDetectorBuilder.build() or instantiate ObjectDetector directly.)ÚNotImplementedError)rZ   s   &r)   Úfrom_configÚObjectDetector.from_configÑ   s   € ô "ðxó
ð 	
r(   c               ó    € V ^8„  d   QhRRRR/# )r7   Úimagesú'Union[torch.Tensor, list[torch.Tensor]]r;   r   )r:   s   "r)   r<   rQ   â   s    € ÷ @ñ @ÐEð @ÐJqñ @r(   c                ór   € V P                  V4      w  rV P                  V4      w  r4V P                  W4V4      # )aƒ  Detect objects in a given list of images.

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)``.

Returns:
    What the post-processor returns. For a detector from :meth:`RTDETRDetectorBuilder.build`, a list with
    one ``(D, 6)`` tensor per image, where :math:`D` is the number of detections in that image, each row the
    class id, the score and the ``x, y, w, h`` box in that image's pixels; with
    ``confidence_filtering=False`` or a threshold of 0, one ``(B, Q, 6)`` tensor of the ``Q`` best detections
    of each image.

)rN   rM   rO   )rV   r`   Úimages_sizesÚlogitsÚboxess   &&   r)   ÚforwardÚObjectDetector.forwardá   s:   € ð   $×1Ñ1°&Ó9ÑˆØŸ
™
 6Ó*‰ˆØ×"Ñ" 6°,Ó?Ð?r(   Nc               ó(   € V ^8„  d   QhRRRRRRRR/# )	r7   r`   ra   r8   úOptional[torch.Tensor]Úoutput_typerA   r;   z:Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]r   )r:   s   "r)   r<   rQ   õ   s3   € ÷ 9ñ 9à7ð9ð +ð9ð ð	9ð
 
Dñ9r(   c           
     ó€  € Vf   V P                  V4      MTp. p\        W4       EF  w  rgVR,          P                  4       pV FÊ  p	\        P                  ! V	R,          V	R,          V	R,          V	R,          ,           V	R,          V	R,          ,           ...4      p
V
R,          P                  ^ VP                  R,          ^,
          4      V
R&   V
R,          P                  ^ VP                  R,          ^,
          4      V
R&   \        WŠ4      pKÌ  	  VP                  V^ ,          4       EK  	  V P                  WS4      # )aÂ  Draw the boxes of the detections on copies of the images.

Args:
    images: input images, a ``(B, 3, H, W)`` tensor or a list of ``(3, H, W)`` images.
    detections: the detections of each image, rows ending with the ``x, y, w, h`` box; computed with
        :meth:`forward` when None.
    output_type: ``"torch"`` or ``"pil"``.

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

Néüÿÿÿéýÿÿÿéþÿÿÿéÿÿÿÿ).:é    Nr7   ).:é   Nr7   )
rf   ÚzipÚcloneÚtorchÚTensorÚclampÚshaper   rE   Ú_tensor_to_type)rV   r`   r8   rj   ÚdetsÚoutputÚimagerJ   Úout_imgÚoutÚboxs   &&&&       r)   Ú	visualizeÚObjectDetector.visualizeõ   s  € ð$ (2Ò'9ˆt�|‰|˜FÔ#¸zˆØˆÜ # F× 1ÑˆEØ˜D•k×'Ñ'Ó)ˆGÛ �Ü—l’l c¨"¥g¨s°2­w¸¸B½À#ÀbÅ'Õ8IÈ3ÈrÍ7ÐUXÐY[ÕU\ÕK\Ð%]Ð$^Ð#_Ó`�à!$ Y¥×!5Ñ!5°a¸¿¹ÀrÕ9JÈQÕ9NÓ!O��I‘Ø!$ Y¥×!5Ñ!5°a¸¿¹ÀrÕ9JÈQÕ9NÓ!O��I‘Ü(¨Ó6’ñ !ð �M‰M˜' !�*×%ñ !2ð ×#Ñ# FÓ8Ð8r(   c               ó(   € V ^8„  d   QhRRRRRRRR/# )	r7   r`   ra   r8   ri   Ú	directoryúOptional[str]r;   rP   r   )r:   s   "r)   r<   rQ     s2   € ÷ /ñ /à7ð/ð +ð/ð !ð	/ð
 
ñ/r(   c                óJ   € V P                  W4      pV P                  WC4       R# )zÇSave the images with their boxes drawn by :meth:`visualize` as PNG files.

Args:
    images: input torch.Tensor.
    detections: detection torch.Tensor.
    directory: directory to save the images.

N)r   Ú_save_outputs)rV   r`   r8   r‚   Úoutputss   &&&& r)   ÚsaveÚObjectDetector.save  s    € ð —.‘. Ó4ˆØ×Ñ˜7Ö.r(   c               ó4   € V ^8„  d   QhRRRRRRRRRR	R
RRR/# )r7   Ú	onnx_namerƒ   Ú
image_sizeúOptional[int]Úinclude_pre_and_post_processorÚboolr‡   Úadditional_metadataúOptional[list[tuple[str, str]]]Úkwargsr   r;   úonnx.ModelProtor   )r:   s   "r)   r<   rQ   &  sY   € ÷ Uñ Uà ðUð "ðUð )-ð	Uð
 ðUð =ðUð ðUð 
ñUr(   c                óÊ  € Vf   RV P                    RV R2p^^T;'       g    RT;'       g    R.pRpV'       d<   \        4       ;_uu_ 4        \        V \        P                  ! V4      4      pRRR4       V'       d   ^MRp	T	^T;'       g    RT;'       g    R.p
V'       d   RM\        V P                  RR4      pV'       d�   VP                  R4      f   \        V4      VR&   \        V4      '       g]   RV9  dV   R	V9  dO   \        V
4       UUu/ uF  w  rÍVR8X  g   K  VR
V 2bK  	  pppVR,           Uu/ uF  qÿ^ R/bK	  	  ppRV/VCVR&   V P                  V4      ;_uu_ 4        \        P                  ! V V3RT
R. RORTRV'       d   T MV P                  RVRV/VB uuRRR4       #   + '       g   i     ELL; iu uppi u upi   + '       g   i     R# ; i)a½	  Export an RT-DETR object detection model to ONNX format.

Exports this detector, as built by :meth:`RTDETRDetectorBuilder.build` or the constructor.

Args:
    onnx_name:
        The name of the output ONNX file. If not provided, ``"kornia_<name>_<image_size>.onnx"``, with
        the detector's ``name``, for example ``"kornia_detection_640.onnx"``
        (``"kornia_detection_None.onnx"`` for ``image_size=None``).
    image_size:
        The height and width of the exported graph's input. 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.
        For RTDETR, recommended scales include [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800].
    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`.

Note:
    With a post-processor that returns a list or tuple of per-image detections, as a
    ``kornia.models.rt_detr.DETRPostProcessor`` that filters by confidence does, the model is
    exported for a batch of one image: no ONNX output holds a list as long as the batch. Which kind of output
    the detector returns is read from one forward pass for one image at the export size, in eval mode and
    without gradients, and a tuple as long as the batch from a second one at another batch size, which tells
    per-image results from a fixed set of batched outputs such as ``(boxes, scores)``. A per-image result
    requires a fixed batch; a tensor result is checked again at the actual tracing batch before accepting a
    dynamic graph. Build an RT-DETR detector with ``confidence_filtering=False`` 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.

    Without the pre- and post-processor, a model that declares ``ONNX_OUTPUT_NAMES``, as
    :class:`~kornia.models.rt_detr.RTDETR` does (``pred_logits`` and ``pred_boxes``), has its outputs exported
    under those names, each with a dynamic batch; any other model has one output, ``output``.

NÚkornia_Ú_z.onnxi`  ÚONNX_OUTPUT_NAMESÚoutput_namesÚdynamic_axesÚdynamic_shapesÚdim_Údim_0ÚinputÚinput_shapeÚoutput_shapeÚpseudo_shaperM   r‡   r�   ro   ©ro   ro   é   )rK   r   r   rt   ÚrandÚgetattrrM   ÚgetÚlistr   Ú	enumerateÚ_onnx_output_kind_keptr   Úto_onnx)rV   rŠ   r‹   r�   r‡   r�   r‘   rŸ   Ú	per_imageÚbatchr�   r—   ÚiÚdimÚ
input_axesrK   Úoutput_axess   &&&&&&,          r)   r¨   ÚObjectDetector.to_onnx&  sð  € ð` ÒØ! $§)¡) ¨A¨j¨\¸Ð?ˆIØ˜1˜j×/Ð/¨C°×1BÐ1B¸sÐCˆð ˆ	ß)ô  ×!Õ!Ü6°t¼U¿ZºZÈÓ=UÓV�	÷ "ç‘ BˆØ˜a ×!1Ð!1¨r°:×3CÐ3CÀÐDˆç=‘tÄ7È4Ï:É:ÐWjÐlpÓCqˆßð �z‰z˜.Ó)Ò1Ü)-¨lÓ);��~Ñ&Ü'¨×/Ò/°NÈ&Ô4PÐUeÐmsÔUsÜ:CÀKÔ:PÔ^Ñ:P±°ÐTWÐ[]ÑT]œm˜a 4¨ s šmÑ:P�
Ñ^à>DÀ^Ö>TÓUÑ>T°d a¨ \Ò1Ñ>T�ÐUØ*1°:Ð)MÀÐ)M��~Ñ&à×(Ñ(¨×3Õ3Ü"×*Ò*ØØñ
ð (ð
ò )ð	
ð
 *ð
÷ =‘dÀ$Ç*Á*ð
ð ð
ð %8ð
ð ñ
÷ 4Ò3÷# "×!Ð!üó _ùâU÷ 4×3Ð3ús*   Á!F2ÄGÄ$
GÄ<GÅ-:GÆ2G	ÇG"	c               ó$   € V ^8„  d   QhRRRRRR/# ©r7   Úmoduler   Údummy_inputr;   rƒ   r   )r:   s   "r)   r<   rQ   }  s!   € ÷ 
ñ 
¨Sð 
¸sð 
À}ñ 
r(   c                	óD   € WJg   V P                  V4      '       g   R #  R# )Nz“Use a post-processor that returns one tensor for the batch, such as a DETRPostProcessor with confidence_filtering=False, to export a dynamic batch.)Ú_onnx_returns_per_image_outputs©rV   r²   r³   s   &&&r)   Ú_onnx_fixed_batch_hintÚ%ObjectDetector._onnx_fixed_batch_hint}  s&   € ØÓ T×%IÑ%IÈ+×%VÒ%VÙðEñ	
r(   Ú	fullgraphFÚdynamicÚbackendÚinductorÚmodeÚoptionsÚdisablec               ó4   € V ^8„  d   QhRRRRRRRRRR	R
RRR/# )r7   r¹   rŽ   rº   r»   rA   r½   rƒ   r¾   z%Optional[dict[str, str | int | bool]]r¿   r;   rP   r   )r:   s   "r)   r<   rQ   …  sR   € ÷ 
ñ 
ð ð
ð ð	
ð
 ð
ð ð
ð 7ð
ð ð
ð 
ñ
r(   c          
     ó^   € \         P                  ! V P                  VVVVVVR7      V n        R# )zLCompile the internal object detection model with :py:func:`torch.compile()`.)r¹   rº   r»   r½   r¾   r¿   N)rt   ÚcompilerM   )rV   r¹   rº   r»   r½   r¾   r¿   s   &$$$$$$r)   rÂ   ÚObjectDetector.compile…  s-   € ô —]’]Ø�J‰JØØØØØØô
ˆŽ
r(   )rM   rO   rN   )Nrt   ©NN)Ni€  TTN)r   r   r    r!   r"   rK   r/   rT   Ústaticmethodr]   rt   Úinference_moderf   r   r‡   r¨   r·   rÂ   r'   Ú__classcell__©rW   s   @r)   r   r   ´   s®   ø‡ ñð €Dˆ#Ó÷-ð -ð ô
ó ð
ð ×ÒÓô@ó ð@÷&9÷@/÷"Uõn
ð
ð  ð
ð ð	
ð
 "ð
ð #ð
ð :>ð
ð ÷
õ 
r(   c                  ó    a € ] tR tRt$ Rt. ROtR]R&   . ROtR]R&   . ROtR]R&   RR V 3R lllt	RR	 R
 llt
RR V 3R llltR R ltRtV ;t# )r   i›  aù  Keep the detections above a confidence threshold and in given classes, per image.

``kept = BoxFiltering(confidence_threshold=0.3, classes_to_keep=[0, 2])(dets)`` keeps the rows
``(class_id, score, x, y, w, h)`` of ``(B, D, 6)`` detections that score strictly above the threshold and are in
``classes_to_keep``. It returns a list of ``B`` tensors ``(D_b, 6)``, or, with ``filter_as_zero=True``, the
``(B, D, 6)`` input with the other rows zeroed.

Args:
    confidence_threshold: a float or 0-d tensor; the rows scoring strictly above it are kept. If None, 0.
    classes_to_keep: a list or 1-d tensor of the class ids to keep. If None, keep all classes.
    filter_as_zero: whether to set the other rows to zero in one ``(B, D, 6)`` tensor instead of dropping them.

See Also:
    - :class:`~kornia.models.rt_detr.DETRPostProcessor`: RT-DETR's post-processor, which filters its detections
      by score with this class.
    - :func:`results_from_detections`: converts the kept rows of one image to Python objects.

zClassVar[List[int]]ÚONNX_DEFAULT_INPUTSHAPEÚONNX_DEFAULT_OUTPUTSHAPEÚONNX_EXPORT_PSEUDO_SHAPEc               ó(   € V ^8„  d   QhRRRRRRRR/# )	r7   Úconfidence_thresholdz$Optional[Union[torch.Tensor, float]]Úclasses_to_keepz(Optional[Union[torch.Tensor, List[int]]]Úfilter_as_zerorŽ   r;   rP   r   )r:   s   "r)   r<   ÚBoxFiltering.__annotate__³  s9   € ÷ 	tñ 	tàBð	tð Bð	tð ð		tð
 
ñ	tr(   c                	óÂ   <€ \         SV `  4        W0n        Vf   R M\        P                  ! V4      V n        Vf
   R V n        R # \        P                  ! V4      V n        R # )N)rS   rT   rÐ   rt   Ú	as_tensorrÏ   rÎ   )rV   rÎ   rÏ   rÐ   rW   s   &&&&€r)   rT   ÚBoxFiltering.__init__³  sM   ø€ ô 	‰ÑÔØ,ÔØ'6Ò'>™tÄEÇOÂOÐTcÓDdˆÔØ,@Ò,H DˆÖ!ÌeÏoÊoÐ^rÓNsˆÖ!r(   c               ó(   € V ^8„  d   QhRRRRRRRR/# )r7   re   r9   rÎ   ri   rÏ   r;   z'Union[torch.Tensor, List[torch.Tensor]]r   )r:   s   "r)   r<   rÑ   ¾  s2   € ÷ :#ñ :#àð:#ð 5ð:#ð 0ð	:#ð
 
1ñ:#r(   c                ó²  € Vf   V P                   pVf.   \        P                  ! RVP                  VP                  R7      pVR,          V8„  pVf   V P
                  pVeK   VR,          pVP                  VP                  4      P                  ^^R4      pWS8H  P                  RR7      pM\        P                  ! V4      pWF,          pV P                  '       d.   \        P                  ! VR,          WP                  R4      4      # . p\        VP                  ^ ,          4       F,  p	W,          p
Wy,          pW«,          pVP                  V4       K.  	  V# )	a  Filter boxes according to the desired threshold.

To be ONNX-friendly, the inputs for direct forwarding need to be all tensors.

Args:
    boxes: ``(B, D, 6)``, where B is the batch size, D is the number of detections in each image,
        6 represent (class_id, confidence_score, x, y, w, h).
    confidence_threshold: a 0-d tensor that replaces the constructor's threshold for this call. If None,
        the constructor's.
    classes_to_keep: a 1-d torch.Tensor of classes to keep, replacing the constructor's for this call. If
        None, the constructor's.

Returns:
    If ``filter_as_zero`` is True, the ``(B, D, 6)`` input with the filtered-out rows set to zero.
    If ``filter_as_zero`` is False, a list of ``B`` tensors ``(D_b, 6)``, the rows kept in each image.

g        )ÚdeviceÚdtype)r¬   )ºNNNrÙ   rq   )rÙ   rÙ   :rp   rq   Nro   )rÙ   rÙ   Nr   )rÎ   rt   Útensorr×   rØ   rÏ   ÚtoÚviewÚanyÚ	ones_likerÐ   ÚwhereÚ	new_zerosÚrangerw   rE   )rV   re   rÎ   rÏ   Úconfidence_maskÚ	class_idsÚ
class_maskÚcombined_maskÚfiltered_boxes_listr«   r~   ÚmaskÚvalid_boxess   &&&&         r)   rf   ÚBoxFiltering.forward¾  s6  € ð2  Ò'Ø#'×#<Ñ#<Ð ØÒ'Ü#(§<¢<°¸E¿L¹LÐPU×P[ÑP[Ô#\Ð Ø �.Ð+?Ñ?ˆð Ò"Ø"×2Ñ2ˆOØÒ&Ø˜iÕ(ˆIð .×0Ñ0°·±Ó>×CÑCÀAÀqÈ"ÓMˆOØ#Ñ6×;Ñ;ÀÐ;ÓC‰Jô Ÿš¨Ó9ˆJð (Õ4ˆà××Ðä—;’;˜}¨ZÕ8¸%ÇÁÐQSÓATÓUÐUà ÐÜ�u—{‘{ 1•~Ö&ˆAØ•(ˆCØ Õ#ˆDØ�)ˆKØ×&Ñ& {Ö3ñ	 'ð #Ð"r(   c               ó<   € V ^8„  d   QhRRRRRRRRRRR	R
RRRRRR/	# )r7   rŠ   rƒ   r�   zOptional[list[int]]rž   rŸ   rM   zOptional[nn.Module]r‡   rŽ   r�   r�   r‘   r   r;   r’   r   )r:   s   "r)   r<   rÑ   ú  sd   € ÷ ?
ñ ?
à ð?
ð )ð?
ð *ð	?
ð
 *ð?
ð #ð?
ð ð?
ð =ð?
ð ð?
ð 
ñ?
r(   c                ó  <€ V P                   '       gQ   Vf$   Vf   ^MV^ ,          .V P                  R,          OpV'       d   V^ ,          R
8X  d   \        R4      hVf   R
^.p\        S	V `  ! RRVRVRVRVRVRVR	V/VB # )a  Export the filter with a fixed batch for per-image list outputs.

Args:
    onnx_name: The output file name. Defaults to ``Kornia-BoxFiltering.onnx``.
    input_shape: The ``[B, D, 6]`` input shape, with ``-1`` for a dynamic dimension. Defaults to
        ``[1, -1, 6]`` without ``filter_as_zero`` and ``[-1, -1, 6]`` with it.
    output_shape: The output shape used by the legacy TorchScript exporter. Defaults to ``[-1, 6]``
        without ``filter_as_zero`` and ``[-1, -1, 6]`` with it. The dynamo exporter infers output shapes.
    pseudo_shape: The dummy input shape used for tracing. Without ``filter_as_zero`` and ``input_shape``,
        its batch is the exported batch. Explicit input and pseudo shapes must agree on fixed dimensions.
    model: The model to export. Defaults to this filter.
    save: Whether to save the exported model to ``onnx_name``.
    additional_metadata: Additional metadata to add to the ONNX model.
    **kwargs: Additional arguments to :func:`torch.onnx.export`.

Returns:
    The exported ONNX model.

Raises:
    ValueError: If ``input_shape`` marks the batch ``-1`` without ``filter_as_zero``, or a ``dynamic_axes``
        or ``dynamic_shapes`` argument makes the exported batch dynamic without it.

Note:
    The exported graph takes the boxes as its only input and filters at the threshold given to the
    constructor, or at ``0.0`` when there is none, as eager does.

Note:
    The exporters flatten the Python list into a fixed number of graph outputs. Without ``filter_as_zero``,
    the batch is therefore fixed: at the batch of ``input_shape``, else of ``pseudo_shape``, else at 1. ONNX
    Runtime rejects other batch sizes. Each image's number of retained detections remains dynamic.
    Use ``filter_as_zero=True`` for one ``(B, D, 6)`` output with a dynamic batch.

:rq   NNzµBoxFiltering returns one ONNX output per image without filter_as_zero and requires a fixed batch. Fix the batch in input_shape, or use filter_as_zero=True to export a dynamic batch.rŠ   r�   rž   rŸ   rM   r‡   r�   ro   r   )rÐ   rÊ   Ú
ValueErrorrS   r¨   )
rV   rŠ   r�   rž   rŸ   rM   r‡   r�   r‘   rW   s
   &&&&&&&&,€r)   r¨   ÚBoxFiltering.to_onnxú  sÌ   ø€ ðX ×"×"Ð"ØÒ"Ø$0Ò$8™q¸lÈ1½oÐqÐPT×PlÑPlÐmoÕPpÐq�ß˜{¨1�~°Ô3Ü ðjóð ð Ò#Ø " A˜w�Ü‰wŠñ 	
Øð	
à#ð	
ð &ð	
ð &ð		
ð
 ð	
ð ð	
ð !4ð	
ð ñ	
ð 		
r(   c               ó$   € V ^8„  d   QhRRRRRR/# r±   r   )r:   s   "r)   r<   rÑ   ;  s&   € ÷ \ñ \¨Sð \¸sð \À}ñ \r(   c                	óZ   € \        V\        4      '       d   VP                  '       d   R # R# )NzJUse filter_as_zero=True to export a dynamic batch as one (B, D, 6) output.)r@   r   rÐ   r¶   s   &&&r)   r·   Ú#BoxFiltering._onnx_fixed_batch_hint;  s    € Ü˜&¤,×/Ò/°6×3H×3HÐ3HÙÙ[r(   )rÏ   rÎ   rÐ   r    )é   é   r¡   )NNFrÄ   )NNNNNTN)r   r   r    r!   r"   rÊ   r/   rË   rÌ   rT   rf   r¨   r·   r'   rÇ   rÈ   s   @r)   r   r   ›  sW   ø‡ ñò& 4?ÐÐ0Ó>Ú4?ÐÐ1Ó?Ú4>ÐÐ1Ó>÷	tò 	t÷:#÷x?
ò ?
÷B\ó \r(   c                  ó4   € ] tR tRtRt]RR R ll4       tRtR# )r   iA  a¿  Build an ObjectDetector around a pretrained RT-DETR network for the 80 COCO classes.

``detector = RTDETRDetectorBuilder.build("rtdetr_r18vd")`` downloads the released weights on first use and
returns an :class:`ObjectDetector`. ``dets = detector(images)`` takes RGB images in :math:`[0, 1]` and returns a
list with one ``(D, 6)`` tensor per image, rows ``(class_id, score, x, y, w, h)`` scoring above 0.3. The box is in
that image's pixels, and ``class_id`` is the COCO class index, from 0 to 79.

See Also:
    - :class:`ObjectDetector`: the wrapper it returns, for your own detection network.
    - :class:`~kornia.models.rt_detr.RTDETR`: the network, to build from a configuration or to fine-tune.

Nc               ó4   € V ^8„  d   QhRRRRRRRRR	R
RRRR/# )r7   Ú
model_namerƒ   rZ   zOptional[Any]Ú
pretrainedrŽ   r‹   rŒ   rÎ   zOptional[float]Úconfidence_filteringzOptional[bool]r;   r   r   )r:   s   "r)   r<   Ú"RTDETRDetectorBuilder.__annotate__P  sW   € ÷ H
ñ H
Ø!ðH
àðH
ð ðH
ð "ð	H
ð
 .ðH
ð -ðH
ð 
ñH
r(   c                ó¶  € ^ RI p^ RIHp ^ RIHpHp	 V e   Ve   \        R4      hVe)   VP                  V4      p
T;'       g    VP                  pM¥V ec   V'       d.   VP                  V 4      p
V	P                  V 4      P                  pMlVP                  V 4      p
V	P                  V 4      P                  pM?VP                  R^R7       VP                  R4      p
V	P                  R4      P                  pVf   Ve   VP                  MRp\        T
\        W34      T! TVf   R	MTV
P                  P                   V
P                  P"                  R
7      4      # )a  Build an RT-DETR object detector.

Pass at most one of ``model_name`` and ``config``; both raise ``ValueError``. Without either, it warns and
builds the pretrained ``rtdetr_r18vd``.

Args:
    model_name:
        Name of the RT-DETR model to load. Can be one of the available pretrained models.
        Including 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'.
    config:
        A custom configuration object for building the RT-DETR model.
    pretrained:
        Whether to load a pretrained version of the model (applies when ``model_name`` is provided).
    image_size:
        The size to which input images will be resized during preprocessing, used only with ``config``. If
        None, ``config.input_size`` is used. With ``model_name``, or without either, it is ignored: the input is
        resized to the 640 px the published weights were trained for. Recommended scales include
        [480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800].
    confidence_threshold: The detections scoring strictly above it are kept. If None,
        ``config.confidence_threshold`` with ``config``, else 0.3.
    confidence_filtering: Whether to filter results based on confidence scores. None filters. Without
        filtering, or with a threshold of 0, the detector returns one ``(B, Q, 6)`` tensor, ``Q`` the
        decoder's number of queries (300 for the released models).

Returns:
    ObjectDetector
        An object detector instance initialized with the specified model, preprocessor, and post-processor.

N)ÚDETRPostProcessor)ÚRTDETRÚRTDETRConfigz1Either `model_name` or `config` should be `None`.zHNo `model_name` or `config` found. Will build pretrained `rtdetr_r18vd`.)Ú
stacklevelÚrtdetr_r18vdg333333Ó?T)rÎ   r÷   Únum_classesÚnum_top_queries)ÚwarningsÚkornia.models.rt_detrrú   Úkornia.models.rt_detr.modelrû   rü   rì   r]   Ú
input_sizeÚfrom_pretrainedÚ	from_nameÚwarnrÎ   r   r   Údecoderrÿ   Únum_queries)rõ   rZ   rö   r‹   rÎ   r÷   r  rú   rû   rü   rM   s   &&&&&&     r)   ÚbuildÚRTDETRDetectorBuilder.buildO  s=  € óL 	å;ßDàÒ! fÒ&8ÜÐPÓQÐQàÒØ×&Ñ& vÓ.ˆEØ#×8Ð8 v×'8Ñ'8‰JØÒ#ßØ×.Ñ.¨zÓ:�Ø)×3Ñ3°JÓ?×JÑJ‘
à×(Ñ(¨Ó4�Ø)×3Ñ3°JÓ?×JÑJ‘
à�M‰MÐdÐqrˆMÔsØ×*Ñ*¨>Ó:ˆEØ%×/Ñ/°Ó?×JÑJˆJàÒ'ØBHÒBT 6×#>Ò#>ÐZ]Ð äØÜ˜zÓ6ÙØ%9Ø-AÒ-I¡TÐOcØ!ŸM™M×5Ñ5Ø %§¡× 9Ñ 9ô	ó	
ð 		
r(   r   )NNTNNN)r   r   r    r!   r"   rÅ   r
  r'   r   r(   r)   r   r   A  s   † ñð öH
ó ôH
r(   )r   r   r   r   r   r   rH   )+r"   Ú
__future__r   Údataclassesr   Úenumr   Útypingr   r   r   r   r	   rt   r
   Úkornia.constantsr   Úkornia.core.checkr   Úkornia.core.externalr   ÚImager   Úkornia.core.mixin.onnxr   r   r   r   Úkornia.image.drawr   Úkornia.models.baser   Úkornia.models.processorsr   Ú__all__r   r   r   rH   r   ÚModuler   r   r   r(   r)   Ú<module>r     sÅ   ðñ$õ #å !Ý ß 7Õ 7ã Ý å )Ý 0Ý 2Ý %ß tÓ tÝ ,Ý (Ý 7ò€ô˜Dô ñ4 �$Ô÷'ð 'ó ð'ñ, �$Ô÷ð ó ðõ,,ô^d
�Y ô d
ôNc\�2—9‘9˜oô c\÷LW
ó W
r(   