
    FPh[                         d Z ddlmZ ddlmZ ddlmZ ddlZddl	Z	ddl
mZ ddlmZmZmZ ddlmZmZmZ dd	lmZ  G d
 de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Zy)z
Ultralytics Results, Boxes and Masks classes for handling inference results.

Usage: See https://docs.ultralytics.com/modes/predict/
    )deepcopy)	lru_cache)PathN)	LetterBox)LOGGERSimpleClassops)	Annotatorcolorssave_one_box)smart_inference_modec                   L    e Zd ZdZddZed        Zd Zd Zd Z	d Z
d	 Zd
 Zy)
BaseTensorzTBase tensor class with additional methods for easy manipulation and device handling.Nc                 x    t        |t        j                  t        j                  f      sJ || _        || _        y)z
        Initialize BaseTensor with data and original shape.

        Args:
            data (torch.Tensor | np.ndarray): Predictions, such as bboxes, masks and keypoints.
            orig_shape (tuple): Original shape of image.
        N)
isinstancetorchTensornpndarraydata
orig_shape)selfr   r   s      eC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/engine/results.py__init__zBaseTensor.__init__   s/     $rzz :;;;	$    c                 .    | j                   j                  S )z$Return the shape of the data tensor.)r   shaper   s    r   r   zBaseTensor.shape$   s     yyr   c                     t        | j                  t        j                        r| S | j	                  | j                  j                         | j                        S )z*Return a copy of the tensor on CPU memory.)r   r   r   r   	__class__cpur   r   s    r   r!   zBaseTensor.cpu)   s:    !$))RZZ8tndnnTYY]]_^b^m^m>nnr   c                     t        | j                  t        j                        r| S | j	                  | j                  j                         | j                        S )z-Return a copy of the tensor as a numpy array.)r   r   r   r   r    numpyr   r   s    r   r#   zBaseTensor.numpy-   s;    !$))RZZ8tpdnnTYY__M^`d`o`o>ppr   c                     | j                  t        j                  | j                        j	                         | j
                        S )z*Return a copy of the tensor on GPU memory.)r    r   	as_tensorr   cudar   r   s    r   r&   zBaseTensor.cuda1   s-    ~~eoodii8==?QQr   c                     | j                   t        j                  | j                        j                  |i || j
                        S )z@Return a copy of the tensor with the specified device and dtype.)r    r   r%   r   tor   r   argskwargss      r   r(   zBaseTensor.to5   s7    ~~;eoodii8;;TLVLdoo^^r   c                 ,    t        | j                        S )z%Return the length of the data tensor.)lenr   r   s    r   __len__zBaseTensor.__len__9   s    499~r   c                 T    | j                  | j                  |   | j                        S )z@Return a BaseTensor with the specified index of the data tensor.)r    r   r   r   idxs     r   __getitem__zBaseTensor.__getitem__=   s    ~~diindoo>>r   returnN)__name__
__module____qualname____doc__r   propertyr   r!   r#   r&   r(   r.   r2    r   r   r   r      s@    ^
%  oqR_?r   r   c                       e Zd ZdZdddZd Zd ZddZd Zd Z	d	 Z
d
 Zd Zd Z	 	 	 	 	 	 	 	 	 	 	 	 	 ddZd ZddZ ed      fdZddZy)Resultsa  
    A class for storing and manipulating inference results.

    Args:
        orig_img (numpy.ndarray): The original image as a numpy array.
        path (str): The path to the image file.
        names (dict): A dictionary of class names.
        boxes (torch.tensor, optional): A 2D tensor of bounding box coordinates for each detection.
        masks (torch.tensor, optional): A 3D tensor of detection masks, where each mask is a binary image.
        probs (torch.tensor, optional): A 1D tensor of probabilities of each class for classification task.
        keypoints (List[List[float]], optional): A list of detected keypoints for each object.

    Attributes:
        orig_img (numpy.ndarray): The original image as a numpy array.
        orig_shape (tuple): The original image shape in (height, width) format.
        boxes (Boxes, optional): A Boxes object containing the detection bounding boxes.
        masks (Masks, optional): A Masks object containing the detection masks.
        probs (Probs, optional): A Probs object containing probabilities of each class for classification task.
        keypoints (Keypoints, optional): A Keypoints object containing detected keypoints for each object.
        speed (dict): A dictionary of preprocess, inference, and postprocess speeds in milliseconds per image.
        names (dict): A dictionary of class names.
        path (str): The path to the image file.
        _keys (tuple): A tuple of attribute names for non-empty attributes.
    Nc                 j   || _         |j                  dd | _        |t        || j                        nd| _        |t        || j                        nd| _        |t        |      nd| _        |t        || j                        nd| _
        dddd| _        || _        || _        d| _        d| _        y)zInitialize the Results class.N   )
preprocess	inferencepostprocess)boxesmasksprobs	keypoints)orig_imgr   r   BoxesrB   MasksrC   ProbsrD   	KeypointsrE   speednamespathsave_dir_keys)r   rF   rM   rL   rB   rC   rD   rE   s           r   r   zResults.__init__\   s     "..!,6;6GU5$//2T
6;6GU5$//2T
%*%6U5\D
BKBW9doo>]a$(tDQ

	;
r   c                 &    | j                  d|      S )z0Return a Results object for the specified index.r2   _applyr0   s     r   r2   zResults.__getitem__j   s    {{=#..r   c                 \    | j                   D ]  }t        | |      }|t        |      c S  y)z6Return the number of detections in the Results object.N)rO   getattrr-   )r   kvs      r   r.   zResults.__len__n   s*    Aa A}1v r   c                     |;t        j                  || j                         t        || j                        | _        |t        || j                        | _        ||| _        yy)zDUpdate the boxes, masks, and probs attributes of the Results object.N)r	   
clip_boxesr   rG   rB   rH   rC   rD   )r   rB   rC   rD   s       r   updatezResults.updateu   sV    NN5$//2udoo6DJudoo6DJDJ r   c           
          | j                         }| j                  D ].  }t        | |      }|t        || t        ||      |i |       0 |S )a  
        Applies a function to all non-empty attributes and returns a new Results object with modified attributes. This
        function is internally called by methods like .to(), .cuda(), .cpu(), etc.

        Args:
            fn (str): The name of the function to apply.
            *args: Variable length argument list to pass to the function.
            **kwargs: Arbitrary keyword arguments to pass to the function.

        Returns:
            Results: A new Results object with attributes modified by the applied function.
        )newrO   rT   setattr)r   fnr*   r+   rrU   rV   s          r   rR   zResults._apply   sS     HHJAa A}1ngand=f=>  r   c                 $    | j                  d      S )zCReturn a copy of the Results object with all tensors on CPU memory.r!   rQ   r   s    r   r!   zResults.cpu   s    {{5!!r   c                 $    | j                  d      S )zEReturn a copy of the Results object with all tensors as numpy arrays.r#   rQ   r   s    r   r#   zResults.numpy   s    {{7##r   c                 $    | j                  d      S )zCReturn a copy of the Results object with all tensors on GPU memory.r&   rQ   r   s    r   r&   zResults.cuda   s    {{6""r   c                 .     | j                   dg|i |S )zSReturn a copy of the Results object with tensors on the specified device and dtype.r(   rQ   r)   s      r   r(   z
Results.to   s    t{{41$1&11r   c                 Z    t        | j                  | j                  | j                        S )zAReturn a new Results object with the same image, path, and names.)rF   rM   rL   )r<   rF   rM   rL   r   s    r   r[   zResults.new   s    DIITZZPPr   c           
         |t        | j                  t        j                        rx| j                  d   j	                         j                  ddd      j                         dz  j                  t        j                        j                         j                         }| j                  | j                  |}}| j                  |}}| j                  |c}t        t!        || j                  n|      ||||xs duxr |      }|r|r| t#        |j$                  dd       |j'                               }t        j(                  |t        j*                  |j,                  j.                        j                  ddd      j1                  d      j                         dz  }|r|j2                  nt5        t7        |            }|j                  |j,                  |D cg c]  }t9        |d	       c}|
       |r|rt;        |      D ]  }t=        |j2                        |rt?        |j@                        nd|jB                  dn"t=        |jB                  jE                               }}}|dnd| d|   z   }|
r|r| d|dn|nd}|jG                  |jH                  jK                         |t9        |d	              X|rVdjM                  fdjN                  D              }tQ        | jR                  d   dz        }|jU                  ||g|d       | jV                  Ct;        | jV                  j,                        D ]!  }|jY                  || jR                  ||	       # |j'                         S c c}w )a  
        Plots the detection results on an input RGB image. Accepts a numpy array (cv2) or a PIL Image.

        Args:
            conf (bool): Whether to plot the detection confidence score.
            line_width (float, optional): The line width of the bounding boxes. If None, it is scaled to the image size.
            font_size (float, optional): The font size of the text. If None, it is scaled to the image size.
            font (str): The font to use for the text.
            pil (bool): Whether to return the image as a PIL Image.
            img (numpy.ndarray): Plot to another image. if not, plot to original image.
            im_gpu (torch.Tensor): Normalized image in gpu with shape (1, 3, 640, 640), for faster mask plotting.
            kpt_radius (int, optional): Radius of the drawn keypoints. Default is 5.
            kpt_line (bool): Whether to draw lines connecting keypoints.
            labels (bool): Whether to plot the label of bounding boxes.
            boxes (bool): Whether to plot the bounding boxes.
            masks (bool): Whether to plot the masks.
            probs (bool): Whether to plot classification probability

        Returns:
            (numpy.ndarray): A numpy array of the annotated image.

        Example:
            ```python
            from PIL import Image
            from ultralytics import YOLO

            model = YOLO('yolov8n.pt')
            results = model('bus.jpg')  # results list
            for r in results:
                im_array = r.plot()  # plot a BGR numpy array of predictions
                im = Image.fromarray(im_array[..., ::-1])  # RGB PIL image
                im.show()  # show image
                im.save('results.jpg')  # save image
            ```
        Nr      r>      )example)image)dtypedeviceT)r   im_gpu zid: .2f)colorz,
c              3   V   K   | ]   }r|   n| d j                   |   d " ywrm   rn   Nr   ).0jrL   
pred_probss     r   	<genexpr>zResults.plot.<locals>.<genexpr>   s5     n^mYZUq :!JOOA<Ns;ST^ms   &)gQ?)rf   rf   rf   )	txt_color)radiuskpt_line)-r   rF   r   r   detachpermute
contiguousr(   uint8r!   r#   rL   rB   rC   rD   r
   r   r   r   resultr%   float16r   rj   flipclsranger-   r   reversedintfloatconfiditem	box_labelxyxysqueezejointop5roundr   textrE   kpts)r   r   
line_width	font_sizefontpilimgrk   
kpt_radiusry   labelsrB   rC   rD   
pred_boxes
show_boxes
pred_masks
show_masks
show_probs	annotatorr1   xdcr   namelabelr   rU   rL   ru   s                                @@r   plotzResults.plot   s   f ;:dmmU\\B==#**,44Q1=HHJSPTTUZU`U`aeegmmoC

!%UJ
!%UJ
!%U
JckT]]s;:Jd*9z	 *~5i
 0 0 45I<L<L<NOEMM*//J`J`aiiq!!T!WZZ\C8$.*..E#j/4JCOOJOOc4RcVAt_c4R[aOb *j)!!%%j4%-TSTSWSWS_4ehijimimiririteu4 jB4qkU1XEDJD64*-4PT##AFFNN$4e6!T?#S	 * !j::n^h^m^mnnDdooa(4/0ANNAq64?NC >>%dnn112q$//*xX 3 !!+ 5Ss   $N
c                     d} j                    j                  }t               dk(  r	|S | dS +|dj                   fdj                  D               dz  }|re|j
                  j                         D ]H  }|j
                  |k(  j                         }|| d j                  t        |          d|dkD  z   dz  }J |S )	z Return log string for each task.rl   r   z(no detections), z, c              3   b   K   | ]&  }j                   |    d j                  |   d ( ywrq   )rL   r   )rs   rt   rD   r   s     r   rv   z"Results.verbose.<locals>.<genexpr>  s3     &bWaRS$**Q-%**Q-9L'MWas   ,/rm   sre   )
rD   rB   r-   r   r   r   uniquesumrL   r   )r   
log_stringrB   r   nrD   s   `    @r   verbosezResults.verbose  s    




t9>!&!2:X:,FW8XXTYY&bW\WaWa&bbcceffJYY%%'YY!^((*1TZZA%7$8ArJJ
 ( r   c           	         | j                   }| j                  }| j                  }| j                  }g }|K|j                  D cg c]3  }|j                  |j                  |   dd| j                  |          5 c} n|rt        |      D ]p  \  }}	t        |	j                        t        |	j                        |	j                  dn"t        |	j                  j                               }}}
|
g|	j                  j!                  d      }|r5||   j"                  d   j%                         j'                  d      }|
g|}|x||   j(                  r5t+        j,                  ||   j"                  ||   j                  d   fd      n||   j"                  }|g |j'                  d      j/                         z  }||f|z  |dn|fz   z  }|j                  d	t1        |      z  j3                         |z         s |rTt5        |      j6                  j9                  d
d
       t;        |d      5 }|j=                  d |D               ddd       yyc c}w # 1 sw Y   yxY w)z
        Save predictions into txt file.

        Args:
            txt_file (str): txt file path.
            save_conf (bool): save confidence score or not.
        Nrn   rm   r   ).Nr>   r:   z%g T)parentsexist_okac              3   &   K   | ]	  }|d z     yw)
Nr:   )rs   r   s     r   rv   z#Results.save_txt.<locals>.<genexpr>7  s     ;UTTD[Us   )rB   rC   rD   rE   r   appendr   rL   	enumerater   r   r   r   r   r   xywhnviewxyncopyreshapehas_visibler   cattolistr-   rstripr   parentmkdiropen
writelines)r   txt_file	save_confrB   rC   rD   r   textsrt   r   r   r   r   linesegkptfs                    r   save_txtzResults.save_txt  s    





~~KP::V:aU\\UZZ]3/qA@A:V!%(1!!%%j%-SVWXW[W[W`W`WbSc4-AGGLL,-(,,q/..088<C99D#RVWXRYReRe%))T!W[[$q',,y2I$JANkopqkrkvkvC9ckk"o44699D9,bjrfMMec$i/779D@A ) N!!''t'Dh$;U;; %$  W" %$s   8I6II'zim.jpgc           
      V   | j                   t        j                  d       y| j                  D ]x  }t	        |j
                  | j                  j                         t        |      | j                  t        |j                           z  t        |      j                   dz  d       z y)z
        Save cropped predictions to `save_dir/cls/file_name.jpg`.

        Args:
            save_dir (str | pathlib.Path): Save path.
            file_name (str | pathlib.Path): File name.
        Nu8   WARNING ⚠️ Classify task do not support `save_crop`.z.jpgT)fileBGR)rD   r   warningrB   r   r   rF   r   r   rL   r   r   stem)r   rN   	file_namer   s       r   	save_cropzResults.save_crop9  s     ::!NNUVA++-"8ntzz#aee*/EE4PY?K_K_J``dHee!# r   c                    | j                   t        j                  d       yddl}g }| j                  j
                  j                         j                         }|r| j                  nd\  }}t        |      D ]  \  }}|d   |z  |d   |z  |d   |z  |d   |z  d}	|d	   }
t        |d
         }| j                  |   }|||
|	d}| j                  j                  rt        |d         |d<   | j                  rj| j                  j                  |   dddf   | j                  j                  |   dddf   }}||z  j                         ||z  j                         d|d<   | j                  w| j                  |   j
                  d   j                         j!                  d      \  }}}||z  j                         ||z  j                         |j                         d|d<   |j#                  |        |j%                  |d      S )z"Convert the object to JSON format.Nz3Warning: Classify task do not support `tojson` yet.r   )re   re   re   r>      )x1y1x2y2r   )r   class
confidenceboxtrack_id)r   ysegments)dim)r   r   visiblerE   )indent)rD   r   r   jsonrB   r   r!   r   r   r   r   rL   is_trackrC   xyrE   unbindr   dumps)r   	normalizer   resultsr   hwirowr   r   class_idr   r~   r   r   r   s                    r   tojsonzResults.tojsonJ  s   ::!NNPQ zz""$++-"+t1oFAsQ!3q6A:SVaZsSTvXYzZCr7D3r7|H::h'D"XTRUVFzz""%(R\z"zzzz}}Q'1-tzz}}Q/?1/E1,-E>>+;1q5..BR%Sz"~~) $q 1 6 6q 9 = = ? F F1 F M1g-.UNN,<AE>>CS`g`n`n`p&q{#NN6" &" zz'!z,,r   )NNNNr3   )NNN)TNNz	Arial.ttfFNN   TTTTT)F)r5   r6   r7   r8   r   r2   r.   rY   rR   r!   r#   r&   r(   r[   r   r   r   r   r   r   r:   r   r   r<   r<   B   s    2</("$#2Q ^"@!<F -1N #"-r   r<   c                        e Zd ZdZd fdZed        Zed        Zed        Zed        Z	e e
d      d	               Ze e
d      d
               Ze e
d      d               Z xZS )rG   aJ  
    A class for storing and manipulating detection boxes.

    Args:
        boxes (torch.Tensor | numpy.ndarray): A tensor or numpy array containing the detection boxes,
            with shape (num_boxes, 6) or (num_boxes, 7). The last two columns contain confidence and class values.
            If present, the third last column contains track IDs.
        orig_shape (tuple): Original image size, in the format (height, width).

    Attributes:
        xyxy (torch.Tensor | numpy.ndarray): The boxes in xyxy format.
        conf (torch.Tensor | numpy.ndarray): The confidence values of the boxes.
        cls (torch.Tensor | numpy.ndarray): The class values of the boxes.
        id (torch.Tensor | numpy.ndarray): The track IDs of the boxes (if available).
        xywh (torch.Tensor | numpy.ndarray): The boxes in xywh format.
        xyxyn (torch.Tensor | numpy.ndarray): The boxes in xyxy format normalized by original image size.
        xywhn (torch.Tensor | numpy.ndarray): The boxes in xywh format normalized by original image size.
        data (torch.Tensor): The raw bboxes tensor (alias for `boxes`).

    Methods:
        cpu(): Move the object to CPU memory.
        numpy(): Convert the object to a numpy array.
        cuda(): Move the object to CUDA memory.
        to(*args, **kwargs): Move the object to the specified device.
    c                     |j                   dk(  r	|dddf   }|j                  d   }|dv s
J d|        t        |   ||       |dk(  | _        || _        y)zInitialize the Boxes class.re   Nr   )      z expected `n` in [6, 7], but got r   )ndimr   superr   r   r   )r   rB   r   r   r    s       r   r   zBoxes.__init__  sb    ::?$'NEKKOF{B>qcBB{
+Q$r   c                 ,    | j                   ddddf   S )z Return the boxes in xyxy format.N   rr   r   s    r   r   z
Boxes.xyxy  s     yyBQBr   c                 (    | j                   dddf   S )z*Return the confidence values of the boxes.Nr   rr   r   s    r   r   z
Boxes.conf       yyBr   c                 (    | j                   dddf   S )z%Return the class values of the boxes.Nr   rr   r   s    r   r   z	Boxes.cls  r   r   c                 D    | j                   r| j                  dddf   S dS )z1Return the track IDs of the boxes (if available).Nr   )r   r   r   s    r   r   zBoxes.id  s"     $(==tyyB:d:r   r>   maxsizec                 @    t        j                  | j                        S )z Return the boxes in xywh format.)r	   	xyxy2xywhr   r   s    r   xywhz
Boxes.xywh  s     }}TYY''r   c                 8   t        | j                  t        j                        r| j                  j	                         nt        j                  | j                        }|dddgfxx   | j                  d   z  cc<   |dddgfxx   | j                  d   z  cc<   |S )zBReturn the boxes in xyxy format normalized by original image size..r   r>   re   r   )r   r   r   r   cloner   r   r   )r   r   s     r   xyxynzBoxes.xyxyn  s~     %/tyy%,,$Gtyy RWWUYU^U^M_S1a&[T__Q//S1a&[T__Q//r   c                     t        j                  | j                        }|dddgfxx   | j                  d   z  cc<   |dddgfxx   | j                  d   z  cc<   |S )zBReturn the boxes in xywh format normalized by original image size..r   r>   re   r   )r	   r   r   r   )r   r   s     r   r   zBoxes.xywhn  s]     }}TYY'S1a&[T__Q//S1a&[T__Q//r   r3   )r5   r6   r7   r8   r   r9   r   r   r   r   r   r   r  r   __classcell__r    s   @r   rG   rG   j  s    4%             ; ; q(  ( q   q  r   rG   c                   t     e Zd ZdZd fdZe ed      d               Ze ed      d               Z xZ	S )rH   a  
    A class for storing and manipulating detection masks.

    Attributes:
        xy (list): A list of segments in pixel coordinates.
        xyn (list): A list of normalized segments.

    Methods:
        cpu(): Returns the masks tensor on CPU memory.
        numpy(): Returns the masks tensor as a numpy array.
        cuda(): Returns the masks tensor on GPU memory.
        to(device, dtype): Returns the masks tensor with the specified device and dtype.
    c                 V    |j                   dk(  r	|dddf   }t        | 	  ||       y)zPInitialize the Masks class with the given masks tensor and original image shape.r>   N)r   r   r   )r   rC   r   r    s      r   r   zMasks.__init__  s*    ::?$'NE
+r   re   r   c           	          t        j                  | j                        D cg c]<  }t        j                  | j                  j                  dd || j
                  d      > c}S c c}w )zReturn normalized segments.re   NTr   r	   masks2segmentsr   scale_coordsr   r   r   r   s     r   r   z	Masks.xyn  s]     ''		242 TYY__QR0!T__PTU24 	4 4   AA&c           	          t        j                  | j                        D cg c]<  }t        j                  | j                  j                  dd || j
                  d      > c}S c c}w )z%Return segments in pixel coordinates.re   NFr
  r  r  s     r   r   zMasks.xy  s]     ''		242 TYY__QR0!T__PUV24 	4 4r  r3   )
r5   r6   r7   r8   r   r9   r   r   r   r  r  s   @r   rH   rH     sO    , q4  4 q4  4r   rH   c                        e Zd ZdZ e       d fd       Ze ed      d               Ze ed      d               Z	e ed      d               Z
 xZS )	rJ   a  
    A class for storing and manipulating detection keypoints.

    Attributes:
        xy (torch.Tensor): A collection of keypoints containing x, y coordinates for each detection.
        xyn (torch.Tensor): A normalized version of xy with coordinates in the range [0, 1].
        conf (torch.Tensor): Confidence values associated with keypoints if available, otherwise None.

    Methods:
        cpu(): Returns a copy of the keypoints tensor on CPU memory.
        numpy(): Returns a copy of the keypoints tensor as a numpy array.
        cuda(): Returns a copy of the keypoints tensor on GPU memory.
        to(device, dtype): Returns a copy of the keypoints tensor with the specified device and dtype.
    c                     |j                   dk(  r	|dddf   }|j                  d   dk(  r|d   dk  }d|dddf   |<   t        |   ||       | j                  j                  d   dk(  | _        y)	zRInitializes the Keypoints object with detection keypoints and original image size.r>   Nr   .r>   g      ?r   .r   )r   r   r   r   r   r   )r   rE   r   maskr    s       r   r   zKeypoints.__init__  s     >>Q!$'*I??1"V$s*D'(Ic2A2gt$J/99??2.!3r   re   r   c                 (    | j                   dddf   S )z&Returns x, y coordinates of keypoints..Nr>   rr   r   s    r   r   zKeypoints.xy  s     yybqb!!r   c                 (   t        | j                  t        j                        r| j                  j	                         nt        j                  | j                        }|dxx   | j                  d   z  cc<   |dxx   | j                  d   z  cc<   |S )z1Returns normalized x, y coordinates of keypoints.).r   re   ).re   r   )r   r   r   r   r  r   r   r   )r   r   s     r   r   zKeypoints.xyn  sf     !+477ELL ATWW]]_rwwtwwGW
6
dooa((

6
dooa((
	r   c                 <    | j                   r| j                  d   S dS )z?Returns confidence values of keypoints if available, else None.r  N)r   r   r   s    r   r   zKeypoints.conf  s      %)$4$4tyy >$>r   r3   )r5   r6   r7   r8   r   r   r9   r   r   r   r   r  r  s   @r   rJ   rJ     s     4 4 q"  " q   q?  ?r   rJ   c                        e Zd ZdZd	d
 fdZe ed      d               Ze ed      d               Ze ed      d               Z	e ed      d               Z
 xZS )rI   aq  
    A class for storing and manipulating classification predictions.

    Attributes:
        top1 (int): Index of the top 1 class.
        top5 (list[int]): Indices of the top 5 classes.
        top1conf (torch.Tensor): Confidence of the top 1 class.
        top5conf (torch.Tensor): Confidences of the top 5 classes.

    Methods:
        cpu(): Returns a copy of the probs tensor on CPU memory.
        numpy(): Returns a copy of the probs tensor as a numpy array.
        cuda(): Returns a copy of the probs tensor on GPU memory.
        to(): Returns a copy of the probs tensor with the specified device and dtype.
    c                 &    t         |   ||       y)zfInitialize the Probs class with classification probabilities and optional original shape of the image.N)r   r   )r   rD   r   r    s      r   r   zProbs.__init__$  s    
+r   re   r   c                 H    t        | j                  j                               S )zReturn the index of top 1.)r   r   argmaxr   s    r   top1z
Probs.top1(  s     499##%&&r   c                 \    | j                    j                  d      dd j                         S )zReturn the indices of top 5.r   Nr   )r   argsortr   r   s    r   r   z
Probs.top5.  s+     
##A&r*1133r   c                 4    | j                   | j                     S )zReturn the confidence of top 1.)r   r  r   s    r   top1confzProbs.top1conf4       yy##r   c                 4    | j                   | j                     S )z Return the confidences of top 5.)r   r   r   s    r   top5confzProbs.top5conf:  r!  r   )Nr3   )r5   r6   r7   r8   r   r9   r   r  r   r   r#  r  r  s   @r   rI   rI     s     , q'  ' q4  4 q$  $ q$  $r   rI   )r8   r   r   	functoolsr   pathlibr   r#   r   r   ultralytics.data.augmentr   ultralytics.utilsr   r   r	   ultralytics.utils.plottingr
   r   r   ultralytics.utils.torch_utilsr   r   r<   rG   rH   rJ   rI   r:   r   r   <module>r*     s~         . 6 6 F F >*? *?Ze-k e-P	OJ Od#4J #4L.?
 .?b+$J +$r   