o mf`@sdZddlmZddlmZddlmZddlZddl Z ddl m Z ddl m Z mZmZmZddlmZmZmZGd d d eZGd d d eZGd ddeZGdddeZGdddeZGdddeZdS)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 SimpleClassdeprecation_warnops) Annotatorcolors save_one_boxc@sVeZdZdZdddZeddZdd Zd d Zd d Z ddZ ddZ ddZ dS) BaseTensorz^ Base tensor class with additional methods for easy manipulation and device handling. returnNcCs&t|tjtjfs J||_||_dS)zInitialize 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) isinstancetorchTensornpndarraydata orig_shape)selfrrrJC:\Users\silly-master\Desktop\PCB\PCB-DETECT\ultralytics\engine\results.py__init__s zBaseTensor.__init__cCs|jjS)z$Return the shape of the data tensor.)rshaperrrrr$szBaseTensor.shapecC&t|jtjr |S||j|jS)z*Return a copy of the tensor on CPU memory.)rrrr __class__cpurrrrrr)&zBaseTensor.cpucCr)z-Return a copy of the tensor as a numpy array.)rrrrrnumpyrrrrrr -rzBaseTensor.numpycCs|t|j|jS)z*Return a copy of the tensor on GPU memory.)rr as_tensorrcudarrrrrr"1szBaseTensor.cudacOs"|t|jj|i||jS)z@Return a copy of the tensor with the specified device and dtype.)rrr!rtor)rargskwargsrrrr#5s"z BaseTensor.tocCs t|jS)z%Return the length of the data tensor.)lenrrrrr__len__9s zBaseTensor.__len__cCs||j||jS)z@Return a BaseTensor with the specified index of the data tensor.)rrr)ridxrrr __getitem__=zBaseTensor.__getitem__rN) __name__ __module__ __qualname____doc__rpropertyrrr r"r#r'r)rrrrr s   r c@seZdZdZd'd(ddZddZdd Zd)d d Zd d ZddZ ddZ ddZ ddZ e ddZ             d*ddZddZd+d d!Zed"fd#d$Zd+d%d&ZdS),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. NrcCs||_|jdd|_|durt||jnd|_|dur"t||jnd|_|dur-t|nd|_|dur:t ||jnd|_ dddd|_ ||_ ||_ d|_d|_dS)zInitialize the Results class.N) preprocess inference postprocess)boxesmasksprobs keypoints)orig_imgrrBoxesr6Masksr7Probsr8 Keypointsr9speednamespathsave_dir_keys)rr:rAr@r6r7r8r9rrrr\s zResults.__init__cCs.|}|jD] }t||t|||q|S)z0Return a Results object for the specified index.)newkeyssetattrgetattr)rr(rkrrrr)j zResults.__getitem__cCs |jD] }tt||SdS)z6Return the number of detections in the Results object.N)rEr&rG)rrIrrrr'qs zResults.__len__cCsP|durt||jt||j|_|durt||j|_|dur&||_dSdS)zDUpdate the boxes, masks, and probs attributes of the Results object.N)r clip_boxesrr;r6r<r7r8)rr6r7r8rrrupdatevs zResults.updatecC.|}|jD] }t||t||q|S)zCReturn a copy of the Results object with all tensors on CPU memory.)rDrErFrGrrrHrIrrrrrJz Results.cpucCrM)zEReturn a copy of the Results object with all tensors as numpy arrays.)rDrErFrGr rNrrrr rJz Results.numpycCrM)zCReturn a copy of the Results object with all tensors on GPU memory.)rDrErFrGr"rNrrrr"rJz Results.cudacOs6|}|jD]}t||t||j|i|q|S)zSReturn a copy of the Results object with tensors on the specified device and dtype.)rDrErFrGr#)rr$r%rHrIrrrr#s  z Results.tocCst|j|j|jdS)zAReturn a new Results object with the same image, path, and names.)r:rAr@)r1r:rAr@rrrrrDr*z Results.newcsfddjDS)z+Return a list of non-empty attribute names.csg|] }t|dur|qSN)rG).0rIrrr sz Results.keys..)rCrrrrrEsz Results.keysT Arial.ttfFc s|dur t|jtjr t|jdddd d}d|vr7t dd|d}t |t ks7Jdd |vrNt d d |d }t |t ksNJd |j|j| }}|j| }}|j| }tt|durl|jn|||||pxduox|d }|r|r|durt|jdd|d }tj|tj|jjdddddd}|r|jntt|}|j|jdd|D|d|r|rt |D]P}t |j|rt!|j"nd|j#durdnt |j#$}}}|durdnd|d|}| r |r |d|dn|nd}|j%|j&'|t(|ddq̈durF|rFd)fddj*D}t+|j,dd}|j-||g|dd|j.dur`t |j.jD] }|j/||j,|| dqR|S)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[..., ::-1]) # RGB PIL image im.show() # show image im.save('results.jpg') # save image ``` Nrr2 show_confconfz@`show_conf` should be of boolean type, i.e, show_conf=True/Falseline_thickness line_widthz5`line_width` should be of int type, i.e, line_width=3)example)image)dtypedevicecSsg|]}t|dqS)T)r rPxrrrrQsz Results.plot..)r im_gpuzid: .2fT)colorz, c3s2|]}r |n|dj|dVqdSrbrcNrrPjr@Z pred_probsrr s0zResults.plot..gQ?)rUrUrU) txt_color)radiuskpt_line)0rr:rrrascontiguousarraypermuterdetachr rtypeboolintr@r6r7r8r rrrresultr!float16rr]flip contiguousclsranger&reversedfloatrWiditem box_labelxyxysqueezer jointop5roundrtextr9kpts)rrWrY font_sizefontpilimgr`Z kpt_radiusrmlabelsr6r7r8r% pred_boxesZ show_boxes pred_masksZ show_masksZ show_probs annotatorr(dcr|namelabelrr_rIrrirplots\4*         < $ z Results.plotcsd}jj}tdkrdur|S|dSdur0|dfddjDd7}|rV|jD]}|j|k}||djt |d |d kd7}q7|S) z2 Return log string for each task. rarNz(no detections), z, c3s,|]}j|dj|dVqdSre)r@rrgr8rrrrjs*z"Results.verbose..rbsrT) r8r6r&rrrxuniquesumr@rs)r log_stringr6rnrrrverboses &,zResults.verbosecsj}j}jj}gdurfddjDn|rt|D]\}}t|jt|j |j dur8dnt|j }} } |g|j dR} |ra||jdd} |g| R} |dur||jrzt||j||j dfdn||j} | g| dR7} | | f|| durdn| f7} d t| | q%rt|d }|d d DWddS1swYdSdS) z Save predictions into txt file. Args: txt_file (str): txt file path. save_conf (bool): save confidence score or not. Ncs.g|]}j|ddj|qS)rcrb)appendrr@rgr8rtextsrrrQ1s.z$Results.save_txt..r).Nr2rz%g acss|]}|dVqdS) Nr)rPrrrrrjBsz#Results.save_txt..)r6r7r8r9r enumeratersrxr{rWr|r}xywhnviewxyncopyreshape has_visiblercattolistrr&rstripopen writelines)rZtxt_file save_confr6r7rrhrrrWr|linesegkptfrrrsave_txt"s04 4  "zResults.save_txtzim.jpgcCs|jdur tddSt|trt|}t|trt|}|jD]}t|j|j ||j t |j |jdddq!dS)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. Nu8WARNING ⚠️ Classify task do not support `save_crop`.z.jpgT)fileBGR)r8rwarningrstrrr6r rr:rr@rsrxstem)rrB file_namerrrr save_cropDs     zResults.save_cropcCsp|jdur tddSddl}g}|jj}|r|jnd\}}t |D]\}}|d||d||d||d|d} |d } t |d } |j | } | | | | d } |j r|j j |dddf|j j |dddf}}||||d | d <|jdur|j|jdjdd\}}}|||||d| d<|| q'|j|ddS)z"Convert the object to JSON format.Nz3Warning: Classify task do not support `tojson` yet.r)rTrTrTr2)x1y1x2y2rS)rclass confidencebox)r_ysegments)dim)r_rvisibler9)indent)r8rrjsonr6rrrrrrsr@r7xyr9unbindrdumps)r normalizerresultsrhwirowrrWr|rrtr_rrrrrtojsonYs*  .  2 "$ zResults.tojson)NNNNr+)NNN) TNNrRFNNrSTTTTT)F)r,r-r.r/rr)r'rLrr r"r#rDr0rErrrrrrrrrrr1Bs>     l "r1cseZdZdZdfdd ZeddZedd Zed d Zed d Z ee ddddZ ee ddddZ ee ddddZ eddZZS)r;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. rNcs\|jdkr |dddf}|jd}|dvsJd|t|||dk|_||_dS)zInitialize the Boxes class.rTNr)z expected `n` in [6, 7], but got r)ndimrsuperris_trackr)rr6rrrrrrs    zBoxes.__init__cCs|jddddfS)z Return the boxes in xyxy format.Nrrfrrrrrsz Boxes.xyxycC|jdddfS)z*Return the confidence values of the boxes.NrfrrrrrWz Boxes.confcCr)z%Return the class values of the boxes.Nrrfrrrrrxrz Boxes.clscCs|jr |jdddfSdS)z1Return the track IDs of the boxes (if available).N)rrrrrrr|szBoxes.idr2maxsizecCs t|jS)z Return the boxes in xywh format.)r xyxy2xywhrrrrrxywh z Boxes.xywhcCsdt|jtjr |jnt|j}|dddgf|jd<|dddgf|jd<|S)zBReturn the boxes in xyxy format normalized by original image size..rr2rTr)rrrrclonerrr)rrrrrxyxyns$z Boxes.xyxyncCsLt|j}|dddgf|jd<|dddgf|jd<|S)zBReturn the boxes in xywh format normalized by original image size..rr2rTr)r rrr)rrrrrrs z Boxes.xywhncCtd|jS)z*Return the raw bboxes tensor (deprecated).uEWARNING ⚠️ 'Boxes.boxes' is deprecated. Use 'Boxes.data' instead.rrrrrrrr6 z Boxes.boxesr+)r,r-r.r/rr0rrWrxr|rrrrr6 __classcell__rrrrr;ws,       r;cspeZdZdZdfdd Zeedddd Zeeddd d Zeeddd d Z eddZ Z S)r<a A class for storing and manipulating detection masks. Attributes: segments (list): Deprecated property for segments (normalized). 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. rNcs,|jdkr |dddf}t||dS)zPInitialize the Masks class with the given masks tensor and original image shape.r2N)rrr)rr7rrrrrs zMasks.__init__rTrcCr)zCReturn segments (normalized). Deprecated; use xyn property instead.uWARNING ⚠️ 'Masks.segments' is deprecated. Use 'Masks.xyn' for segments (normalized) and 'Masks.xy' for segments (pixels) instead.)rrrrrrrrszMasks.segmentscfddtjDS)zReturn normalized segments.c,g|]}tjjjdd|jddqS)rTNTrr scale_coordsrrrr^rrrrQzMasks.xyn..r masks2segmentsrrrrrr  z Masks.xyncr)z%Return segments in pixel coordinates.cr)rTNFrrr^rrrrQrzMasks.xy..rrrrrrrzMasks.xycCr)zDReturn the raw masks tensor. Deprecated; use data attribute instead.uEWARNING ⚠️ 'Masks.masks' is deprecated. Use 'Masks.data' instead.rrrrrr7rz Masks.masksr+) r,r-r.r/rr0rrrrr7rrrrrr<s   r<csdeZdZdZdfdd Zeedddd Zeeddd d Zeeddd d Z Z S)r>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. rNcs>|jdkr |dddf}t|||jjddk|_dS)zRInitializes the Keypoints object with detection keypoints and original image size.r2Nrr)rrrrrr)rr9rrrrrs zKeypoints.__init__rTrcCs|jdddfS)z&Returns x, y coordinates of keypoints..Nr2rfrrrrrsz Keypoints.xycCsTt|jtjr |jnt|j}|d|jd<|d|jd<|S)z1Returns normalized x, y coordinates of keypoints.).rrT).rTr)rrrrrrrr)rrrrrr"s$z Keypoints.xyncCs|jr|jdSdS)z?Returns confidence values of keypoints if available, else None.).r2N)rrrrrrrW+szKeypoints.confr+) r,r-r.r/rr0rrrrWrrrrrr>s  r>cs|eZdZdZddfdd Zeedddd Zeeddd d Zeeddd d Z eeddddZ Z S)r=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. Nrcst||dSrO)rr)rr8rrrrrCszProbs.__init__rTrcCst|jS)zReturn the index of top 1.)rsrargmaxrrrrtop1Fsz Probs.top1cCs|j dddS)zReturn the indices of top 5.rNrS)rargsortrrrrrrLsz Probs.top5cC |j|jS)zReturn the confidence of top 1.)rrrrrrtop1confRrzProbs.top1confcCr)z Return the confidences of top 5.)rrrrrrtop5confXrzProbs.top5confrOr+) r,r-r.r/rr0rrrrrrrrrrr=2s   r=)r/rr functoolsrpathlibrr rrultralytics.data.augmentrultralytics.utilsrrrr ultralytics.utils.plottingr r r r r1r;r<r>r=rrrrs"    .7X6-