
    /j3                        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
c mZ d dlmZ d dlmZmZ d dlmZ d dlmZmZ  G d	 d
e          ZdS )    )annotations)Path)AnyN)DetectionValidator)LOGGERops)check_requirements)SegmentMetricsmask_iouc                       e Zd ZdZd)d* fdZd+ fd
Zd, fdZd-dZd. fdZd/ fdZ	d0 fdZ
d1 fdZd2d#Zd3 fd%Zd4 fd&Zd5 fd(Z xZS )6SegmentationValidatora  A class extending the DetectionValidator class for validation based on a segmentation model.

    This validator handles the evaluation of segmentation models, processing both bounding box and mask predictions to
    compute metrics such as mAP for both detection and segmentation tasks.

    Attributes:
        plot_masks (list): List to store masks for plotting.
        process (callable): Function to process masks based on save_json and save_txt flags.
        args (SimpleNamespace): Arguments for the validator.
        metrics (SegmentMetrics): Metrics calculator for segmentation tasks.
        stats (dict): Dictionary to store statistics during validation.

    Examples:
        >>> from ultralytics.models.yolo.segment import SegmentationValidator
        >>> args = dict(model="yolo26n-seg.pt", data="coco8-seg.yaml")
        >>> validator = SegmentationValidator(args=args)
        >>> validator()
    N
_callbacksdict | NonereturnNonec                    t                                          ||||           d| _        d| j        _        t                      | _        dS )a  Initialize SegmentationValidator and set task to 'segment', metrics to SegmentMetrics.

        Args:
            dataloader (torch.utils.data.DataLoader, optional): DataLoader to use for validation.
            save_dir (Path, optional): Directory to save results.
            args (dict, optional): Arguments for the validator.
            _callbacks (dict, optional): Dictionary of callback functions.
        Nsegment)super__init__processargstaskr
   metrics)self
dataloadersave_dirr   r   	__class__s        h/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/models/yolo/segment/val.pyr   zSegmentationValidator.__init__&   sD     	XtZ@@@"	%''    batchdict[str, Any]c                    t                                          |          }|d                                         |d<   |S )zPreprocess batch of images for YOLO segmentation validation.

        Args:
            batch (dict[str, Any]): Batch containing images and annotations.

        Returns:
            (dict[str, Any]): Preprocessed batch.
        masks)r   
preprocessfloat)r   r    r   s     r   r$   z SegmentationValidator.preprocess4   s:     ""5))w--//gr   modeltorch.nn.Modulec                    t                                          |           | j        j        rt	          d           | j        j        s| j        j        rt          j        nt          j        | _	        dS )zInitialize metrics and select mask processing function based on save_json flag.

        Args:
            model (torch.nn.Module): Model to validate.
        zfaster-coco-eval>=1.6.7N)
r   init_metricsr   	save_jsonr	   save_txtr   process_mask_nativeprocess_maskr   )r   r&   r   s     r   r)   z"SegmentationValidator.init_metricsA   sd     	U###9 	:899926)2EqI[qs..adaqr   strc                    ddz  S )z5Return a formatted description of evaluation metrics.z,%22s%11s%11s%11s%11s%11s%11s%11s%11s%11s%11s)ClassImages	InstanceszBox(PRmAP50	mAP50-95)zMask(Pr3   r4   r5    )r   s    r   get_desczSegmentationValidator.get_descM   s    $ )
 
 	
r   predslist[torch.Tensor]list[dict[str, torch.Tensor]]c                L   t          |d         t                    r|d         d         n|d         }t                                          |d                   }d |j        dd         D             }t          |          D ]\  }}|                    d          }|j        d         r%|                     ||         ||d         |          nQt          j	        dg| j        t          j        u r|n|j        dd         R t          j        |d         j        	          |d
<   |S )a  Post-process YOLO predictions and return output detections with proto.

        Args:
            preds (list[torch.Tensor]): Raw predictions from the model.

        Returns:
            (list[dict[str, torch.Tensor]]): Processed detection predictions with masks.
        r      c                    g | ]}d |z  S    r6   ).0xs     r   
<listcomp>z5SegmentationValidator.postprocess.<locals>.<listcomp>h   s    0001Q000r      Nextrabboxes)shape)dtypedevicer#   )
isinstancetupler   postprocessrF   	enumeratepopr   torchzerosr   r,   uint8rH   )r   r8   protoimgszipredcoefficientr   s          r   rK   z!SegmentationValidator.postprocess]   s*     *%(E::Haa##E!H--00ABB000 '' 
	 
	GAt((7++K $Q'U1X{DN%PPP[a4<33J#J#J%%PUP[\]\^\^P_aa+>0   MM r   siintc                @    t                                          ||          }|d         j        d         } j        j        r[|d         |         }t          j        d|dz   |j                                      |dd          }||k    	                                }n|d         |d         |k             }|r` fd|d         D             }|j        dd	         |k    r9t          j        |d	         |d
d          d         }|                    d          }||d<   |S )a:  Prepare a batch for validation by processing images and targets.

        Args:
            si (int): Sample index within the batch.
            batch (dict[str, Any]): Batch data containing images and annotations.

        Returns:
            (dict[str, Any]): Prepared batch with processed annotations.
        clsr   r#   r<   )rH   	batch_idxc                D    g | ]}j         t          j        u r|n|d z  S r>   )r   r   r,   )r@   sr   s     r   rB   z8SegmentationValidator._prepare_batch.<locals>.<listcomp>   s2    sssVWdlc.EEE1PQ6sssr   rR   NbilinearF)modealign_cornersg      ?)r   _prepare_batchrF   r   overlap_maskrN   arangerH   viewr%   Finterpolategt_)	r   rV   r    prepared_batchnlr#   index	mask_sizer   s	   `       r   r`   z$SegmentationValidator._prepare_batchv   s(    //E::E"(+9! 	='N2&ELBF5<@@@EEb!QOOEe^**,,EE'N5#5#;<E 	'ssss[ijq[rsssI{122)++eDk9:]bcccdef		#"'wr   dict[str, torch.Tensor]dict[str, np.ndarray]c                l   t                                          ||          }|d         }|j        d         dk    s|d         j        d         dk    r4t          j        |d         j        d         | j        ft                    }nt          |d                             d          |d                             d          	                                          }| 
                    |d         ||                                                                          }|                    d|i           |S )a  Compute correct prediction matrix for a batch based on bounding boxes and optional masks.

        Args:
            preds (dict[str, torch.Tensor]): Dictionary containing predictions with keys like 'cls' and 'masks'.
            batch (dict[str, Any]): Dictionary containing batch data with keys like 'cls' and 'masks'.

        Returns:
            (dict[str, np.ndarray]): A dictionary containing correct prediction matrices including 'tp_m' for mask IoU.

        Examples:
            >>> preds = {"cls": torch.tensor([1, 0]), "masks": torch.rand(2, 640, 640), "bboxes": torch.rand(2, 4)}
            >>> batch = {"cls": torch.tensor([1, 0]), "masks": torch.rand(2, 640, 640), "bboxes": torch.rand(2, 4)}
            >>> correct_preds = validator._process_batch(preds, batch)

        Notes:
            - This method computes IoU between predicted and ground truth masks.
            - Overlapping masks are handled based on the overlap_mask argument setting.
        rY   r   rG   r#   r<   tp_m)r   _process_batchrF   nprO   niouboolr   flattenr%   match_predictionscpunumpyupdate)r   r8   r    tpgt_clsro   iour   s          r   rp   z$SegmentationValidator._process_batch   s   & WW##E511u<?a5<#5a#8A#=#=8U5\/2DI>dKKKDD5>11!44eGn6L6LQ6O6O6U6U6W6WXXC))%,DDHHJJPPRRD
		64.!!!	r   nic                   |D ]}|d         }|j         d         | j        j        k    r"t          j        d| j        j         d           t          j        |d| j        j                 t
          j                                                  |d<   t                      
                    |||| j        j                   dS )a  Plot batch predictions with masks and bounding boxes.

        Args:
            batch (dict[str, Any]): Batch containing images and annotations.
            preds (list[dict[str, torch.Tensor]]): List of predictions from the model.
            ni (int): Batch index.
        r#   r   z&Limiting validation plots to 'max_det=z' items.Nrn   )max_det)rF   r   r~   r   warningrN   	as_tensorrP   rv   r   plot_predictions)r   r    r8   r|   pr#   r   s         r   r   z&SegmentationValidator.plot_predictions   s      	^ 	^AgJE{1~	 111c	HYcccddd/B1B/B)C5;WWW[[]]AgJJ  r49;L MMMMMr   predn	save_confrs   rF   tuple[int, int]filer   c                   ddl m}  |t          j        |d         |d         ft          j                  d| j        t          j        |d         |d                             d          |d	                             d          gd
          t          j	        |d         t          j                            
                    ||           dS )a  Save YOLO detections to a txt file in normalized coordinates in a specific format.

        Args:
            predn (dict[str, torch.Tensor]): Prediction dictionary containing 'bboxes', 'conf', 'cls', and 'masks' keys.
            save_conf (bool): Whether to save confidence scores.
            shape (tuple[int, int]): Shape of the original image.
            file (Path): File path to save the detections.
        r   )Resultsr<   rn   NrE   confrY   )dimr#   )pathnamesboxesr#   )r   )ultralytics.engine.resultsr   rq   rO   rP   r   rN   cat	unsqueezer   r+   )r   r   r   rF   r   r   s         r   save_one_txtz"SegmentationValidator.save_one_txt   s     	766666HeAha):::*)U8_eFm.E.Eb.I.I5QV<KaKabdKeKeflmnnn/%.DDD	
 	
 	
 (49(
-
-
-
-
-r   pbatchc                   dd}dd}|d	                              d
d                                                              t          |d	                   d          }|d	         j        dd         \  }} ||          }g }	|D ]%}
|	                    ||g ||
          d           &t                                          ||           t          |	          D ]&\  }}|| j	        t          |	           |z            d<   'dS )a'  Save one JSON result for COCO evaluation.

        Args:
            predn (dict[str, torch.Tensor]): Predictions containing bboxes, masks, confidence scores, and classes.
            pbatch (dict[str, Any]): Batch dictionary containing 'imgsz', 'ori_shape', 'ratio_pad', and 'im_file'.
        counts	list[int]r   r.   c                v   g }t          t          |                     D ]}t          | |                   }|dk    r|t          | |dz
                     z  }	 |dz  }|dz  }|dz  r|dk    n|dk    }|r|dz  }|d	z  }|                    t	          |                     |snMd
                    |          S )zConverts the RLE object into a compact string representation. Each count is delta-encoded and
            variable-length encoded as a string.

            Args:
                counts (list[int]): List of RLE counts.
            rC   T         r   r       0    )rangelenrW   appendchrjoin)r   resultrS   rA   cmores         r   	to_stringz5SegmentationValidator.pred_to_json.<locals>.to_string   s     F3v;;''  q	NN q55VAE]+++ADA!GA *+T@AGGaD "T	GAMM#a&&)))  776??"r   pixelstorch.Tensorc                   | ddddf         | ddddf         k    }t          j        |          \  }}|dz   }g }t          | j        d                   D ]
}|||k             }t	          |          rt          j        |                                          }|                    d|d                                                    |	                    t	          | |                   |d                                         z
             nt	          | |                   g}| |         d                                         dk    rdg|}|	                    |           |S )aI  Convert multiple binary masks using Run-Length Encoding (RLE).

            Args:
                pixels (torch.Tensor): A 2D tensor where each row represents a flattened binary mask with shape [N,
                    H*W].

            Returns:
                (list[list[int]]): A list of RLE counts for each mask.
            Nr<   r   r   )
rN   wherer   rF   r   difftolistinsertitemr   )r   transitionsrow_idxcol_idxr   rS   	positionscounts           r   multi_encodez8SegmentationValidator.pred_to_json.<locals>.multi_encode   sV    !ABB-6!!!SbS&>9K${;77GWkG F6<?++ % %#GqL1	y>> -!Jy1188::ELLIaL$5$5$7$7888LLVAY)B-2D2D2F2F!FGGGG ^^,E !9Q<$$&&!++KKEe$$$$Mr   r#   rC   r<   r      )sizer   segmentationN)r   r   r   r.   )r   r   r   r   )
	transpose
contiguousrc   r   rF   r   r   pred_to_jsonrL   jdict)r   r   r   r   r   
pred_maskshwr   rlesr   rS   rr   s                r   r   z"SegmentationValidator.pred_to_json   s6   	# 	# 	# 	#B	 	 	 	@ 7^--a33>>@@EEc%PW.FYFY[]^^
W~#AaC(1j)) 	B 	BAKK!Q99Q<<@@AAAAUF+++dOO 	; 	;DAq9:DJD		zA~&~66	; 	;r   c                    i t                                          ||          dt          j        |d         d         |d         |d                   d                                         iS )z.Scales predictions to the original image size.r#   N	ori_shape	ratio_pad)r   r   )r   scale_predsr   scale_masksbyte)r   r   r   r   s      r   r   z!SegmentationValidator.scale_preds"  so    
gg!!%00
S_U7^D%96+;NZ`alZmnnndff	
 
 	
r   statsc                    | j         dz  }| j        d         dz  | j        rdnd| j        j         dz  }t                                          |||ddgd	d
g          S )z;Return COCO-style instance segmentation evaluation metrics.zpredictions.jsonr   r   zinstances_val2017.jsonlvis_v1_z.jsonbboxsegmBoxMask)suffix)r   datais_cocor   splitr   coco_evaluate)r   r   	pred_json	anno_jsonr   s       r   	eval_jsonzSegmentationValidator.eval_json+  s~    M$66	If+/<^''=^	=^=^=^` 	
 ww$$UIy66BR\aci[j$kkkr   )NNNN)r   r   r   r   )r    r!   r   r!   )r&   r'   r   r   )r   r.   )r8   r9   r   r:   )rV   rW   r    r!   r   r!   )r8   rk   r    r!   r   rl   )r    r!   r8   r:   r|   rW   r   r   )
r   rk   r   rs   rF   r   r   r   r   r   )r   rk   r   r!   r   r   )r   rk   r   r!   r   rk   )r   r!   r   r!   )__name__
__module____qualname____doc__r   r$   r)   r7   rK   r`   rp   r   r   r   r   r   __classcell__)r   s   @r   r   r      s        &( ( ( ( ( ( (     
r 
r 
r 
r 
r 
r
 
 
 
      2     4     :N N N N N N. . . .&Q; Q; Q; Q; Q; Q;f
 
 
 
 
 
l l l l l l l l l lr   r   )
__future__r   pathlibr   typingr   rw   rq   rN   torch.nn.functionalnn
functionalrd   ultralytics.models.yolo.detectr   ultralytics.utilsr   r   ultralytics.utils.checksr	   ultralytics.utils.metricsr
   r   r   r6   r   r   <module>r      s
   # " " " " "                           = = = = = = ) ) ) ) ) ) ) ) 7 7 7 7 7 7 > > > > > > > >al al al al al. al al al al alr   