
    FPh0                         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 Zd Z	 	 	 	 	 ddZd	efd
Zd Zd Zy)    N)defaultdict)Path)LOGGERTQDM)increment_pathc                  
    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   NI   J   K   L   M   N   O   N rX       eC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/data/converter.pycoco91_to_coco80_classr[      s    0 0rY   c                  
    g dS )aB  
    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='
')
        b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='
')
        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/   r0   r1   r2   r3   r4   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rK   rN   rP   rQ   rR   rS   rT   rU   rV   rW   P   Q   R   T   U   V   W   X   Y   Z   rX   rX   rY   rZ   coco80_to_coco91_classrg      s    ` `rY   c                 ~	   t        |      }|dz  |dz  fD ]  }|j                  dd        t               }t        t	        |       j                         j                  d            D ]  }t	        |      dz  |j                  j                  dd      z  }|j                  dd       t        |      5 }	t        j                  |	      }
ddd       
d   D ci c]
  }|d	   d
| }}t        t              }|
d   D ]  }||d      j                  |        t        |j!                         d|       D ]2  \  }}||d
   }|d   |d   |d   }	}}g }g }g }|D ]m  }|d   r
t#        j$                  |d   t"        j&                        }|ddxxx |dd dz  z  ccc |ddgxx   |z  cc<   |ddgxx   |z  cc<   |d   dk  s|d   dk  ru|r||d   dz
     n|d   dz
  }|g|j)                         z   }||vr|j                  |       |r1|j+                  d      t-        |d         dk(  r|j                  g        t-        |d         dkD  r[t/        |d         }t#        j0                  |d      t#        j$                  ||g      z  j3                  d      j)                         }nu|d   D cg c]  }|D ]  }|  }}}t#        j$                  |      j3                  dd      t#        j$                  ||g      z  j3                  d      j)                         }|g|z   }||vr|j                  |       |s|j+                  d      |j                  |t#        j$                  |d         j3                  dd      t#        j$                  ||dg      z  j3                  d      j)                         z          p t        ||	z  j5                  d      d      5 }t7        t-        |            D ]^  }|r	g ||   }n g |rt-        ||         dkD  r||   n||   }|j9                  d t-        |      z  j;                         |z  d!z          ` 	 ddd       5 	 t=        j>                  d"|j                                 y# 1 sw Y   xY wc c}w c c}}w # 1 sw Y   xY w)#al  
    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.

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

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

    Output:
        Generates output files in the specified output directory.
    labelsimagesTparentsexist_okz*.json
instances_ Niddannotationsimage_idzAnnotations descheightwidth	file_nameiscrowdbbox)dtyper
   r   r	   r   category_idsegmentationaxis	keypoints.txtaz%g 
z3COCO data converted successfully.
Results saved to ) r   mkdirr[   sortedr   resolveglobstemreplaceopenjsonloadr   listappendr   itemsnparrayfloat64tolistgetlenmerge_multi_segmentconcatenatereshapewith_suffixrangewriterstripr   info)
labels_dirsave_diruse_segmentsuse_keypoints	cls91to80pcoco80	json_filefnfdataxrj   	imgToAnnsannimg_idannsimghwbboxessegmentsr   boxclssijfilelines                                 rZ   convert_cocor   2   s   6 h'H (X"55	t, 6 $%F D,446;;HEF	(^h&)?)?b)QQ
-)_99Q<D  .2(^<^QtWQK!#^<%	&Cc*o&--c2 ' !!2<	{9STTLFDF1:'C(mS\3{3C!qAFHIy>hhs6{"**=BQ3qr7Q;&QFq QFq q6Q;#a&A+8AfS/!34s=GY\]G]ecjjl*f$MM#&CGGN$;$G3~./14 + S01A5/N0CD^^AA61a&9IIRRSUV]]_(+N(;G(;1QQQQ(;GXXa[00Q7"((Aq6:JJSSTVW^^`	A( * SWW[%9%E$$SBHHS5E,F,N,NrST,U,.HHaAY,?-@AHVVX&V W; B rAv**62C8Ds6{+A$/1/ [$0S!5E5I "*!OUVWy [JJD	 199;dBTIJ , 98Q U G~ KKFxGWGWGYFZ[\y _ =J H 98s%   6RR'>R,.A6R2R$	2R<dota_root_pathc           	         t        |       } i ddddddddd	d
dddddddddddddddddddddd d!d"d#d$ifd%}d&D ]  }| d'z  |z  }| d(z  | d)z  }| d(z  |z  }|j                  d*d*+       t        |j                               }t	        |d,| d-.      D ]Z  }|j
                  d/k7  r|j                  }t        j                  t        |            }	|	j                  d0d \  }
} ||||
||       \  y0)1a  
    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 the function execution, the new labels will be saved in:
            - DOTA
                - labels
                    - train
                    - val
    planer   shipr	   zstorage-tankr
   zbaseball-diamondr   ztennis-courtr   zbasketball-courtr   zground-track-fieldr   harborr   bridger   zlarge-vehicler   zsmall-vehicler   
helicopterr   
roundaboutr   zsoccer ball-fieldr   zswimming-poolr   zcontainer-craner   airportr   helipadr   c           
         ||  dz  }||  dz  }|j                  d      5 }|j                  d      5 }|j                         }	|	D ]  }
|
j                         j                         }t	        |      dk  r0|d   }|   }|dd D cg c]  }t        |       }}t        d      D cg c]  }|dz  dk(  r||   |z  n||   |z   }}|D cg c]  }d	j                  |       }}|j                  | d
d
j                  |       d        	 ddd       ddd       yc c}w c c}w c c}w # 1 sw Y   !xY w# 1 sw Y   yxY w)zcConverts a single image's DOTA annotation to YOLO OBB format and saves it to a specified directory.r   rr   r   r   Nr
   r   z{:.6g} r   )
r   	readlinesstripsplitr   floatr   formatr   join)
image_nameimage_widthimage_heightorig_label_dirr   orig_label_path	save_pathr   glinesr   parts
class_name	class_idxr   coordsr   normalized_coordscoordformatted_coordsclass_mappings                       rZ   convert_labelz/convert_dota_to_yolo_obb.<locals>.convert_label   s`   (j\+>>*T22	!!#&!Y^^C-@AKKME

**,u:>"1X
)*5	,1"1I6Iq%(I6afghai%kai\]q1uzF1I+vay<?WWai " %kHY#ZHYuHOOE$:HY #Z9+Qsxx0@'A&B"EF  .A&& 7%k#Z .A-@&&sM   D>AD2	D#
D2*D(
	D2D-
'*D2D>#D22D;	7D>>E)trainvalrj   ri   	_originalTrk   zProcessing z imagesrt   z.pngN)r   r   r   iterdirr   suffixr   cv2imreadstrshape)r   r   phase	image_dirr   r   image_paths
image_pathimage_name_without_extr   r   r   r   s               @rZ   convert_dota_to_yolo_obbr      s   B .)N 	 	A	
 	 	A 	a 	! 	! 	 	 	b 	b 	R 	  	2!" 	2#$ 	2%M(G& ""X-5	'(2wi5HH!H,u4td39,,./{;ugW1MNJ  F*%/__"**S_-C99Ra=DAq0!QQ O "rY   c                     | dddddf   |dddddf   z
  dz  j                  d      }t        j                  t        j                  |d      |j                        S )a  
    Find a pair of indexes with the shortest distance between two arrays of 2D points.

    Args:
        arr1 (np.array): A NumPy array of shape (N, 2) representing N 2D points.
        arr2 (np.array): 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
   r   r~   )sumr   unravel_indexargminr   )arr1arr2diss      rZ   	min_indexr      sV     D!tD!QJ//A5
:
:2
>CBIIc5syyAArY   c                 .   g }| D cg c]'  }t        j                  |      j                  dd      ) } }t        t	        |             D cg c]  }g  }}t        dt	        |             D ]E  }t        | |dz
     | |         \  }}||dz
     j                  |       ||   j                  |       G t        d      D ]I  }|dk(  rt        |      D ]  \  }}t	        |      dk(  r%|d   |d   kD  r|ddd   }| |   dddddf   | |<   t        j                  | |   |d    d      | |<   t        j                  | |   | |   dd g      | |<   |dt	        |      dz
  fv r|j                  | |          d|d   |d   z
  g}|j                  | |   |d   |d   dz            t        t	        |      dz
  dd      D ]E  }|dt	        |      dz
  fvs||   }t        |d   |d   z
        }	|j                  | |   |	d        G L |S c c}w c c}w )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.
    r   r
   r	   r   Nr~   )r   r   r   r   r   r   r   	enumeraterollr   abs)
r   r   r   _idx_listidx1idx2kidxnidxs
             rZ   r   r     s4    	A4<=Hq##B*HH=!#h-010q0H1 1c(m$xA<
dQt$4  % 1X6#H-3s8q=SVc!f_dd)C"*1+ddAg"6HQK gghqkCF7C nnhqk8A;r?-KLCMA-..HHXa[)c!fs1vo.CHHXa[QA
;< .  3x=1,b"5QH 122"1+Cs1vA/DHHXa[/0	 6' 0 HE >1s   ,H	H)z../coco/annotations/zcoco_converted/FFT)r   collectionsr   pathlibr   r   numpyr   ultralytics.utilsr   r   ultralytics.utils.filesr   r[   rg   r   r   r   r   r   rX   rY   rZ   <module>r     s\     #  
  * 20`* 3+#$	b]JYRS YRxB/rY   