a
    yµÿf‰S  ã                   @   sš   d dl Z d dlmZ d dlmZ d dlZd dlZd dlm	Z	m
Z
 d dlmZ dd„ Zdd	„ Zddd„Zdd„ Zedœdd„Zdd„ Zdd„ Zddd„ZdS )é    N)Údefaultdict)ÚPath)ÚLOGGERÚTQDM)Úincrement_pathc                   C   s   g d¢S )zî
    Converts 91-index COCO class IDs to 80-index COCO class IDs.

    Returns:
        (list): A list of 91 class IDs where the index represents the 80-index class ID and the value is the
            corresponding 91-index class ID.
    )[r   é   é   é   é   é   é   é   é   é	   é
   Né   é   é   é   é   é   é   é   é   é   é   é   é   Né   é   NNé   é   é   é   é   é   é    é!   é"   é#   é$   é%   é&   é'   Né(   é)   é*   é+   é,   é-   é.   é/   é0   é1   é2   é3   é4   é5   é6   é7   é8   é9   é:   é;   Né<   NNé=   Né>   é?   é@   éA   éB   éC   éD   éE   éF   éG   éH   NéI   éJ   éK   éL   éM   éN   éO   N© rV   rV   rV   úV/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/data/converter.pyÚcoco91_to_coco80_class   s    rX   c                   C   s   g d¢S )aD  
    Converts 80-index (val2014) to 91-index (paper).
    For details see https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/.

    Example:
        ```python
        import numpy as np

        a = np.loadtxt("data/coco.names", dtype="str", delimiter="\n")
        b = np.loadtxt("data/coco_paper.names", dtype="str", delimiter="\n")
        x1 = [list(a[i] == b).index(True) + 1 for i in range(80)]  # darknet to coco
        x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)]  # coco to darknet
        ```
    )Pr   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r!   r"   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rI   rL   rN   rO   rP   rQ   rR   rS   rT   rU   éP   éQ   éR   éT   éU   éV   éW   éX   éY   éZ   rV   rV   rV   rV   rW   Úcoco80_to_coco91_classu   s    rc   ú../coco/annotations/úcoco_converted/FTc                 C   sØ  t |ƒ}|d |d fD ]}|jddd qtƒ }tt| ƒ ¡  d¡ƒD ]f}|rVdn|j dd¡}	t|ƒd |	 }
|
jddd |rª|
d jddd |
d	 jddd t	|ƒ}t
 |¡}W d
  ƒ n1 sÒ0    Y  dd„ |d D ƒ}ttƒ}|d D ]}||d   |¡ qþg }t| ¡ d|› dD ]\}}||d› }|d |d  }}|rttt|d ƒ d¡ƒn|d }|r˜| ttdƒ| ƒ¡ g }g }g }|D ]ö}| dd¡rÀq¨tj|d tjd}|d
d…  |dd
… d 7  < |ddg  |  < |ddg  |  < |d dks¨|d dkr<q¨|rR||d  d  n
|d  d }|g| ¡  }||vr¨| |¡ |rN| d!¡d
urNt|d! ƒdkr¸| g ¡ q¨n‚t|d! ƒdkrþt|d! ƒ}tj|dd"t ||g¡  d#¡ ¡ }n<d$d%„ |d! D ƒ}t |¡ d#d¡t ||g¡  d#¡ ¡ }|g| }| |¡ |r¨| d&¡d
ur¨| |t |d& ¡ d#d¡t ||dg¡  d#¡ ¡  ¡ q¨t	|
|  d'¡d(ƒ†}tt|ƒƒD ]h}|rÞg || ¢R }n.g |r t|| ƒdkr || n|| ¢R }| d)t|ƒ  ¡ | d* ¡ qÄW d
  ƒ n1 sD0    Y  q0|rHt	t|ƒ|j  d+d¡ d,d'¡ d(ƒ$}| !d-d.„ |D ƒ¡ W d
  ƒ qH1 s¦0    Y  qHt" #|rÀd/nd0› d1| ¡ › ¡ d
S )2a2  
    Converts COCO dataset annotations to a YOLO annotation format  suitable for training YOLO models.

    Args:
        labels_dir (str, optional): Path to directory containing COCO dataset annotation files.
        save_dir (str, optional): Path to directory to save results to.
        use_segments (bool, optional): Whether to include segmentation masks in the output.
        use_keypoints (bool, optional): Whether to include keypoint annotations in the output.
        cls91to80 (bool, optional): Whether to map 91 COCO class IDs to the corresponding 80 COCO class IDs.
        lvis (bool, optional): Whether to convert data in lvis dataset way.

    Example:
        ```python
        from ultralytics.data.converter import convert_coco

        convert_coco("../datasets/coco/annotations/", use_segments=True, use_keypoints=False, cls91to80=True)
        convert_coco("../datasets/lvis/annotations/", use_segments=True, use_keypoints=False, cls91to80=False, lvis=True)
        ```

    Output:
        Generates output files in the specified output directory.
    ÚlabelsÚimagesT©ÚparentsÚexist_okz*.jsonÚ Z
instances_Z	train2017Zval2017Nc                 S   s   i | ]}|d  d›|“qS )ÚidÚdrV   )Ú.0ÚxrV   rV   rW   Ú
<dictcomp>  ó    z convert_coco.<locals>.<dictcomp>ÚannotationsZimage_idzAnnotations ©Údescrm   ÚheightÚwidthZcoco_urlzhttp://images.cocodataset.orgÚ	file_namez./imagesZiscrowdFZbbox)Zdtyper   r   r   r	   Zcategory_idZsegmentation©Zaxiséÿÿÿÿc                 S   s   g | ]}|D ]}|‘qqS rV   rV   )rn   ÚiÚjrV   rV   rW   Ú
<listcomp>5  rq   z convert_coco.<locals>.<listcomp>Ú	keypointsú.txtÚaú%g Ú
Zlvis_v1_z.jsonc                 s   s   | ]}|› d V  qdS ©r   NrV   )rn   ÚlinerV   rV   rW   Ú	<genexpr>K  rq   zconvert_coco.<locals>.<genexpr>ZLVISZCOCOz/ data converted successfully.
Results saved to )$r   ÚmkdirrX   Úsortedr   ÚresolveÚglobÚstemÚreplaceÚopenÚjsonÚloadr   ÚlistÚappendr   ÚitemsÚstrÚrelative_toÚgetÚnpÚarrayZfloat64ÚtolistÚlenÚmerge_multi_segmentÚconcatenateÚreshapeÚwith_suffixÚrangeÚwriteÚrstripÚnameÚ
writelinesr   Úinfo)Z
labels_dirÚsave_dirZuse_segmentsZuse_keypointsZ	cls91to80ZlvisÚpZcoco80Z	json_fileÚlnameÚfnÚfÚdatarg   Z	imgToAnnsÚannZ	image_txtZimg_idÚannsÚimgÚhÚwÚbboxesÚsegmentsr}   ÚboxÚclsÚsÚfilerz   rƒ   rV   rV   rW   Úconvert_cocoØ   s†    
( $
 "


(*

2ÿ&ÿF&6r³   c              	   C   sÎ  dd„ t |ƒD ƒ}t| ƒ ¡ D ]¨}|jdkrt t|ƒtj¡}|j\}}t	 
d|› d|› d|› ¡ t |¡}g }	|D ]È}
|
dkr†qx| |
d¡}|dkr´t	 d	|
› d
|› d¡ qxt ||
k tj¡tjtj¡\}}|D ]d}t|ƒdkrÚ| ¡ }|g}|D ]6}| t|d | dƒ¡ | t|d | dƒ¡  qü|	 |¡ qÚqxt|ƒ|j› d }t|dƒ:}|	D ]$}d tt|ƒ¡}| |d ¡ qfW d  ƒ n1 s¢0    Y  t	 
d|› d|› d|› ¡ qdS )u÷  
    Converts a dataset of segmentation mask images to the YOLO segmentation format.

    This function takes the directory containing the binary format mask images and converts them into YOLO segmentation format.
    The converted masks are saved in the specified output directory.

    Args:
        masks_dir (str): The path to the directory where all mask images (png, jpg) are stored.
        output_dir (str): The path to the directory where the converted YOLO segmentation masks will be stored.
        classes (int): Total classes in the dataset i.e. for COCO classes=80

    Example:
        ```python
        from ultralytics.data.converter import convert_segment_masks_to_yolo_seg

        # The classes here is the total classes in the dataset, for COCO dataset we have 80 classes
        convert_segment_masks_to_yolo_seg("path/to/masks_directory", "path/to/output/directory", classes=80)
        ```

    Notes:
        The expected directory structure for the masks is:

            - masks
                â”œâ”€ mask_image_01.png or mask_image_01.jpg
                â”œâ”€ mask_image_02.png or mask_image_02.jpg
                â”œâ”€ mask_image_03.png or mask_image_03.jpg
                â””â”€ mask_image_04.png or mask_image_04.jpg

        After execution, the labels will be organized in the following structure:

            - output_dir
                â”œâ”€ mask_yolo_01.txt
                â”œâ”€ mask_yolo_02.txt
                â”œâ”€ mask_yolo_03.txt
                â””â”€ mask_yolo_04.txt
    c                 S   s   i | ]}|d  |“qS )r   rV   ©rn   rz   rV   rV   rW   rp   u  rq   z5convert_segment_masks_to_yolo_seg.<locals>.<dictcomp>ú.pngúProcessing z	 imgsz = z x r   ry   zUnknown class for pixel value z	 in file z, skipping.r	   r   r   r~   r¬   ú r   NzProcessed and stored at )rœ   r   ÚiterdirÚsuffixÚcv2Úimreadr‘   ZIMREAD_GRAYSCALEÚshaper   r¡   r”   Úuniquer“   ÚwarningZfindContoursZastypeZuint8ZRETR_EXTERNALZCHAIN_APPROX_SIMPLEr—   Zsqueezer   Úroundr‰   r‹   ÚjoinÚmapr   )Z	masks_dirÚ
output_dirÚclassesZpixel_to_class_mappingZ	mask_pathÚmaskZ
img_heightZ	img_widthZunique_valuesZyolo_format_dataÚvalueZclass_indexZcontoursÚ_ZcontourZyolo_formatÚpointZoutput_pathr²   Úitemrƒ   rV   rV   rW   Ú!convert_segment_masks_to_yolo_segP  s@    %


ÿ2rÉ   )Údota_root_pathc                    sì   t | ƒ} ddddddddd	d
dddddddddœ‰ ‡ fdd„}dD ]¤}| d | }| d |› d }| d | }|jddd t| ¡ ƒ}t|d|› ddD ]F}|jdkr®qž|j}t t	|ƒ¡}	|	j
d d… \}
}||||
||ƒ qžqBd S )!u&  
    Converts DOTA dataset annotations to YOLO OBB (Oriented Bounding Box) format.

    The function processes images in the 'train' and 'val' folders of the DOTA dataset. For each image, it reads the
    associated label from the original labels directory and writes new labels in YOLO OBB format to a new directory.

    Args:
        dota_root_path (str): The root directory path of the DOTA dataset.

    Example:
        ```python
        from ultralytics.data.converter import convert_dota_to_yolo_obb

        convert_dota_to_yolo_obb("path/to/DOTA")
        ```

    Notes:
        The directory structure assumed for the DOTA dataset:

            - DOTA
                â”œâ”€ images
                â”‚   â”œâ”€ train
                â”‚   â””â”€ val
                â””â”€ labels
                    â”œâ”€ train_original
                    â””â”€ val_original

        After execution, the function will organize the labels into:

            - DOTA
                â””â”€ labels
                    â”œâ”€ train
                    â””â”€ val
    r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   )ZplaneÚshipzstorage-tankzbaseball-diamondztennis-courtzbasketball-courtzground-track-fieldZharborZbridgezlarge-vehiclezsmall-vehicleÚ
helicopterZ
roundaboutzsoccer-ball-fieldzswimming-poolzcontainer-craneZairportZhelipadc              
      s
  || › d }|| › d }|  d¡Ð}|  d¡¦}| ¡ }	|	D ]ˆ}
|
 ¡  ¡ }t|ƒdk r^q@|d }ˆ| }dd„ |dd… D ƒ‰ ‡ ‡‡fd	d„tdƒD ƒ}d
d„ |D ƒ}| |› dd |¡› d¡ q@W d  ƒ n1 sÞ0    Y  W d  ƒ n1 sü0    Y  dS )zcConverts a single image's DOTA annotation to YOLO OBB format and saves it to a specified directory.r~   Úrr¬   r   r   c                 S   s   g | ]}t |ƒ‘qS rV   )Úfloat)rn   r£   rV   rV   rW   r|   æ  rq   zCconvert_dota_to_yolo_obb.<locals>.convert_label.<locals>.<listcomp>Nc                    s0   g | ](}|d  dkr ˆ | ˆ n
ˆ | ˆ ‘qS )r   r   rV   r´   ©ZcoordsÚimage_heightÚimage_widthrV   rW   r|   ç  s   c                 S   s   g | ]}|d ›‘qS )z.6grV   )rn   ZcoordrV   rV   rW   r|   ê  rq   r·   r   )r‹   Ú	readlinesÚstripÚsplitr—   rœ   r   rÀ   )Z
image_namerÑ   rÐ   Úorig_label_dirr¢   Zorig_label_pathZ	save_pathr¦   ÚgÚlinesrƒ   ÚpartsÚ
class_nameZ	class_idxZnormalized_coordsZformatted_coords©Zclass_mappingrÏ   rW   Úconvert_labelÙ  s     ÿz/convert_dota_to_yolo_obb.<locals>.convert_label)ÚtrainÚvalrg   rf   Z	_originalTrh   r¶   z imagesrs   rµ   N)r   r…   rŽ   r¸   r   r¹   r‰   rº   r»   r‘   r¼   )rÊ   rÛ   ZphaseZ	image_dirrÕ   r¢   Zimage_pathsZ
image_pathZimage_name_without_extrª   r«   r¬   rV   rÚ   rW   Úconvert_dota_to_yolo_obbž  sD    #î
rÞ   c                 C   sN   | dd…ddd…f |ddd…dd…f  d   d¡}t tj|dd|j¡S )a“  
    Find a pair of indexes with the shortest distance between two arrays of 2D points.

    Args:
        arr1 (np.ndarray): A NumPy array of shape (N, 2) representing N 2D points.
        arr2 (np.ndarray): A NumPy array of shape (M, 2) representing M 2D points.

    Returns:
        (tuple): A tuple containing the indexes of the points with the shortest distance in arr1 and arr2 respectively.
    Nr   ry   rx   )Úsumr”   Zunravel_indexZargminr¼   )Zarr1Zarr2ÚdisrV   rV   rW   Ú	min_indexþ  s    6rá   c           	      C   sð  g }dd„ | D ƒ} dd„ t t| ƒƒD ƒ}t dt| ƒƒD ]>}t| |d  | | ƒ\}}||d   |¡ ||  |¡ q6t dƒD ]j}|dkr†t|ƒD ]ì\}}t|ƒdkræ|d |d kræ|ddd… }| | ddd…dd…f | |< tj| | |d  dd	| |< t | | | | dd… g¡| |< |dt|ƒd hv rL| | | ¡ q–d|d |d  g}| | | |d |d d … ¡ q–q~t t|ƒd ddƒD ]N}|dt|ƒd hvrš|| }t|d |d  ƒ}| | | |d… ¡ qšq~|S )
a  
    Merge multiple segments into one list by connecting the coordinates with the minimum distance between each segment.
    This function connects these coordinates with a thin line to merge all segments into one.

    Args:
        segments (List[List]): Original segmentations in COCO's JSON file.
                               Each element is a list of coordinates, like [segmentation1, segmentation2,...].

    Returns:
        s (List[np.ndarray]): A list of connected segments represented as NumPy arrays.
    c                 S   s   g | ]}t  |¡ d d¡‘qS )ry   r   )r”   r•   rš   r´   rV   rV   rW   r|     rq   z'merge_multi_segment.<locals>.<listcomp>c                 S   s   g | ]}g ‘qS rV   rV   )rn   rÆ   rV   rV   rW   r|     rq   r   r   r   Nry   rx   )	rœ   r—   rá   r   Ú	enumerater”   Zrollr™   Úabs)	r®   r±   Zidx_listrz   Zidx1Zidx2ÚkÚidxZnidxrV   rV   rW   r˜     s2    
"&r˜   úsam_b.ptc              	   C   s:  ddl m } ddlm} ddlm} ddlm} ddlm} || t	t
tdƒƒdd	}t|jd d
 ƒdkrz| d¡ dS | d¡ ||ƒ}||jt|jƒddD ]}	|	d \}
}|	d }t|ƒdkrÈq¢|dd…ddgf  |9  < |dd…ddgf  |
9  < t |	d ¡}||||ƒddd}|d jj|	d
< q¢|rBt|ƒnt| ƒjd }|jddd |jD ]À}	g }t|	d ƒ d¡j}|| }|	d }t|	d
 ƒD ]>\}}t|| ƒg| d¡¢R }| dt|ƒ  ¡ | ¡ qœ|rdt|dƒ$}| d d!„ |D ƒ¡ W d  ƒ n1 s0    Y  qd| d"|› ¡ dS )#ud  
    Converts existing object detection dataset (bounding boxes) to segmentation dataset or oriented bounding box (OBB)
    in YOLO format. Generates segmentation data using SAM auto-annotator as needed.

    Args:
        im_dir (str | Path): Path to image directory to convert.
        save_dir (str | Path): Path to save the generated labels, labels will be saved
            into `labels-segment` in the same directory level of `im_dir` if save_dir is None. Default: None.
        sam_model (str): Segmentation model to use for intermediate segmentation data; optional.

    Notes:
        The input directory structure assumed for dataset:

            - im_dir
                â”œâ”€ 001.jpg
                â”œâ”€ ..
                â””â”€ NNN.jpg
            - labels
                â”œâ”€ 001.txt
                â”œâ”€ ..
                â””â”€ NNN.txt
    r   )Útqdm)ÚSAM)ÚYOLODataset)r   )Ú	xywh2xyxyiè  )Únames)r§   r®   z;Segmentation labels detected, no need to generate new ones!NzBDetection labels detected, generating segment labels by SAM model!zGenerating segment labels)Útotalrt   r¼   r­   r   r   r	   Zim_fileF)r­   ÚverboseÚsavezlabels-segmentTrh   r~   r°   ry   r€   r   c                 s   s   | ]}|d  V  qdS r‚   rV   )rn   ÚtextrV   rV   rW   r„   |  rq   z$yolo_bbox2segment.<locals>.<genexpr>z"Generated segment labels saved in )rç   Zultralyticsrè   Zultralytics.dataré   Úultralytics.utilsr   Zultralytics.utils.opsrê   ÚdictrŽ   rœ   r—   rf   r¡   rº   r»   ÚmasksZxynr   Úparentr…   r›   rŸ   râ   Úintrš   r   rž   r‹   r    )Zim_dirr¢   Z	sam_modelrç   rè   ré   r   rê   ZdatasetÚlabelr«   r¬   ZboxesZimZsam_resultsZtextsZlb_nameZtxt_filer°   rz   r±   rƒ   r¦   rV   rV   rW   Úyolo_bbox2segment?  sF    


8rö   )rd   re   FFTF)Nræ   )rŒ   Úcollectionsr   Úpathlibr   rº   Únumpyr”   rð   r   r   Zultralytics.utils.filesr   rX   rc   r³   rÉ   r‘   rÞ   rá   r˜   rö   rV   rV   rV   rW   Ú<module>   s(   gd      ú
xN`2