o
    ߥi4                     @   s   d dl mZ d dlZd dlmZ d dlmZmZ d dl	Z
d dlmZ d dl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 d d	lmZ ejeejd
G dd deZdd ZdS )    N)OrderedDict)AnyDict)COCO)COCOeval)dumpload)Metrics)METRICSMetric)default_group)	group_keymodule_namec                   @   s   e Zd ZdZdd Zdeeef deeef fddZdd	 Z	dddZ
dd Zdd ZdddZdd Zdd Zdd Zdd Zdd ZdS ) #ImageInstanceSegmentationCOCOMetriczMThe metric computation class for COCO-style image instance segmentation.
    c                 C   sH   d | _ d | _ddg| _d| _tjddttdd dd	| _g | _	d S )
Nbboxsegm)d   i,  i  g      ?gffffff?g!@   T)endpoint)
ann_fileclassesmetricsproposal_numsnplinspaceintroundiou_thrsresultsself r!   i/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/metrics/image_instance_segmentation_metric.py__init__   s   

z,ImageInstanceSegmentationCOCOMetric.__init__outputsinputsc                 C   sf   |d }t |d trdd |D }| j| | jd u r1|d d d | _|d d d | _d S d S )Neval_resultr   c                 S   s   g | ]
\}}|t |fqS r!   )encode_mask_results).0bbox_resultsmask_resultsr!   r!   r"   
<listcomp>&   s    z;ImageInstanceSegmentationCOCOMetric.add.<locals>.<listcomp>	img_metasr   r   )
isinstancetupler   extendr   r   )r    r$   r%   resultr!   r!   r"   add"   s   
z'ImageInstanceSegmentationCOCOMetric.addc                 C   s  t | j}|j| jd| _| | _| | j| j\}}t	 }| j
D ]}|}||vr1t| dzt|| }|dkrF|D ]}|d q>||}	W n tyZ   td Y  nw t||	|}
| j|
j_| j|
j_t| j|
j_| j|
j_dddd	d
dddddddd}|
  |
  |
  g d}|D ]}| d| }t|
j||  d}|||< q|
jd d }|d dd|d dd|d dd|d	 dd|d
 dd|d d|| d< q"|d ur|  |S )N)catNmsz is not in resultsr   r   z2The testing results of the whole dataset is empty.r   r                        	   
      )mAPmAP_50mAP_75mAP_smAP_mmAP_lzAR@100zAR@300zAR@1000z	AR_s@1000z	AR_m@1000z	AR_l@1000)r=   r>   r?   r@   rA   rB   _z.3f _mAP_copypaste) r   r   	getCatIdsr   cat_ids	getImgIdsimg_idsformat_resultsr   r   r   KeyErrorr   poploadRes
IndexErrorprintr   paramscatIdsimgIdslistr   maxDetsr   iouThrsevaluate
accumulate	summarizefloatstatscleanup)r    cocoGtresult_filestmp_direval_resultsmetriciou_typepredictionsxcocoDtcocoEvalcoco_metric_namesmetric_itemsmetric_itemkeyvalapr!   r!   r"   rV   -   sr   






0z,ImageInstanceSegmentationCOCOMetric.evaluateotherc                 C   s   | j |j  d S N)r   r/   )r    rl   r!   r!   r"   merges   s   z)ImageInstanceSegmentationCOCOMetric.mergec                 C   s   | j S rm   )r   r   r!   r!   r"   __getstate__v   s   z0ImageInstanceSegmentationCOCOMetric.__getstate__c                 C   s   |    || _d S rm   )r#   r   )r    stater!   r!   r"   __setstate__y   s   
z0ImageInstanceSegmentationCOCOMetric.__setstate__Nc                 K   sr   t |ts	J dt|t|ksJ dt|t||du r-t }t|jd}nd}| 	||}||fS )a  Format the results to json (standard format for COCO evaluation).

        Args:
            results (list[tuple | numpy.ndarray]): Testing results of the
                dataset.
            data_infos(list[tuple | numpy.ndarray]): data information
            jsonfile_prefix (str | None): The prefix of json files. It includes
                the file path and the prefix of filename, e.g., "a/b/prefix".
                If not specified, a temp file will be created. Default: None.

        Returns:
            tuple: (result_files, tmp_dir), result_files is a dict containing                 the json filepaths, tmp_dir is the temporal directory created                 for saving json files when jsonfile_prefix is not specified.
        zresults must be a listz?The length of results is not equal to the dataset len: {} != {}Nr   )
r-   rS   lenformattempfileTemporaryDirectoryospjoinnameresults2json)r    r   rI   jsonfile_prefixkwargsr^   r]   r!   r!   r"   rJ   }   s   z2ImageInstanceSegmentationCOCOMetric.format_resultsc                 C   s4   |  }|d |d |d |d  |d |d  gS )a.  Convert ``xyxy`` style bounding boxes to ``xywh`` style for COCO
        evaluation.

        Args:
            bbox (numpy.ndarray): The bounding boxes, shape (4, ), in
                ``xyxy`` order.

        Returns:
            list[float]: The converted bounding boxes, in ``xywh`` order.
        r   r   r3   r4   )tolist)r    r   _bboxr!   r!   r"   	xyxy2xywh   s   z-ImageInstanceSegmentationCOCOMetric.xyxy2xywhc                 C   s   g }t t| jD ]8}| j| }|| }t |jd D ]%}t }||d< | || |d< t|| d |d< d|d< || qq	|S )z,Convert proposal results to COCO json style.r   image_idr   r5   scorer   category_id)rangerr   rI   shapedictr~   rY   append)r    r   json_resultsidximg_idbboxesidatar!   r!   r"   _proposal2json   s   
z2ImageInstanceSegmentationCOCOMetric._proposal2jsonc           
      C   s   g }t t| jD ]Q}| j| }|| }t t|D ]?}|t| jkr% n5|| }t |jd D ](}t }	||	d< | || |	d< t|| d |	d< | j| |	d< |	|	 q0qq	|S )z-Convert detection results to COCO json style.r   r   r   r5   r   r   )
r   rr   rI   r   r   r   r~   rY   rG   r   )
r    r   r   r   r   r0   labelr   r   r   r!   r!   r"   	_det2json   s$   
z-ImageInstanceSegmentationCOCOMetric._det2jsonc                 C   s  g }g }t t| jD ]}| j| }|| \}}t t|D ]}|t| jkr) n|| }	t |	jd D ](}
t }||d< | |	|
 |d< t|	|
 d |d< | j| |d< |	| q4t
|tro|d | }|d | }n|| }dd	 |	D }t |	jd D ]A}
t }||d< | |	|
 |d< t||
 |d< | j| |d< t
||
 d
 tr||
 d
  ||
 d
< ||
 |d< |	| qqq||fS )z9Convert instance segmentation results to COCO json style.r   r   r   r5   r   r   r   c                 S   s   g | ]}|d  qS )r5   r!   )r(   r   r!   r!   r"   r+      s    zBImageInstanceSegmentationCOCOMetric._segm2json.<locals>.<listcomp>countssegmentation)r   rr   rI   r   r   r   r~   rY   rG   r   r-   r.   bytesdecode)r    r   bbox_json_resultssegm_json_resultsr   r   detsegr   r   r   r   segms
mask_scorer!   r!   r"   
_segm2json   sD   


z.ImageInstanceSegmentationCOCOMetric._segm2jsonc                 C   s   t  }t|d tr&| |}| d|d< | d|d< t||d  |S t|d tr[| |}| d|d< | d|d< | d|d< t|d |d  t|d |d  |S t|d tjrx| 	|}| d|d< t||d  |S t
d	)
a(  Dump the detection results to a COCO style json file.

        There are 3 types of results: proposals, bbox predictions, mask
        predictions, and they have different data types. This method will
        automatically recognize the type, and dump them to json files.

        Args:
            results (list[list | tuple | ndarray]): Testing results of the
                dataset.
            outfile_prefix (str): The filename prefix of the json files. If the
                prefix is "somepath/xxx", the json files will be named
                "somepath/xxx.bbox.json", "somepath/xxx.segm.json",
                "somepath/xxx.proposal.json".

        Returns:
            dict[str: str]: Possible keys are "bbox", "segm", "proposal", and                 values are corresponding filenames.
        r   z
.bbox.jsonr   proposalz
.segm.jsonr   r   z.proposal.jsonzinvalid type of results)r   r-   rS   r   r   r.   r   r   ndarrayr   	TypeError)r    r   outfile_prefixr]   r   r!   r!   r"   ry      s*   


z0ImageInstanceSegmentationCOCOMetric.results2json)rl   r   rm   )__name__
__module____qualname____doc__r#   r   strr   r1   rV   rn   ro   rq   rJ   r~   r   r   r   ry   r!   r!   r!   r"   r      s    "	
F
,r   c                 C   s   t | tr
| \}}n| }t|}dd t|D }tt|D ]%}|| D ]}|| ttj|ddddtj	f dddd  q%qt | trN||fS |S )a  Encode bitmap mask to RLE code.

    Args:
        mask_results (list | tuple[list]): bitmap mask results.
            In mask scoring rcnn, mask_results is a tuple of (segm_results,
            segm_cls_score).

    Returns:
        list | tuple: RLE encoded mask.
    c                 S   s   g | ]}g qS r!   r!   )r(   rC   r!   r!   r"   r+   9  s    z'encode_mask_results.<locals>.<listcomp>NFuint8)orderdtyper   )
r-   r.   rr   r   r   	mask_utilencoder   arraynewaxis)r*   	cls_segmscls_mask_scoresnum_classesencoded_mask_resultsr   cls_segmr!   r!   r"   r'   )  s*   


r'   ) os.pathpathrv   rt   collectionsr   typingr   r   numpyr   pycocotools.maskmaskr   pycocotools.cocor   pycocotools.cocoevalr   modelscope.fileior   r   modelscope.metainfor	   modelscope.metricsr
   r   modelscope.utils.registryr   register_moduleimage_ins_seg_coco_metricr   r'   r!   r!   r!   r"   <module>   s&     