converter.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import json
  3. import shutil
  4. from collections import defaultdict
  5. from pathlib import Path
  6. import cv2
  7. import numpy as np
  8. from tqdm import tqdm
  9. def coco91_to_coco80_class():
  10. """Converts 91-index COCO class IDs to 80-index COCO class IDs.
  11. Returns:
  12. (list): A list of 91 class IDs where the index represents the 80-index class ID and the value is the
  13. corresponding 91-index class ID.
  14. """
  15. return [
  16. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, None, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, None, 24, 25, None,
  17. None, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, None, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
  18. 51, 52, 53, 54, 55, 56, 57, 58, 59, None, 60, None, None, 61, None, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
  19. None, 73, 74, 75, 76, 77, 78, 79, None]
  20. def coco80_to_coco91_class(): #
  21. """
  22. Converts 80-index (val2014) to 91-index (paper).
  23. For details see https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/.
  24. Example:
  25. ```python
  26. import numpy as np
  27. a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
  28. b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
  29. x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
  30. x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
  31. ```
  32. """
  33. return [
  34. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
  35. 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
  36. 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
  37. def convert_coco(labels_dir='../coco/annotations/', use_segments=False, use_keypoints=False, cls91to80=True):
  38. """Converts COCO dataset annotations to a format suitable for training YOLOv5 models.
  39. Args:
  40. labels_dir (str, optional): Path to directory containing COCO dataset annotation files.
  41. use_segments (bool, optional): Whether to include segmentation masks in the output.
  42. use_keypoints (bool, optional): Whether to include keypoint annotations in the output.
  43. cls91to80 (bool, optional): Whether to map 91 COCO class IDs to the corresponding 80 COCO class IDs.
  44. Example:
  45. ```python
  46. from ultralytics.data.converter import convert_coco
  47. convert_coco('../datasets/coco/annotations/', use_segments=True, use_keypoints=False, cls91to80=True)
  48. ```
  49. Output:
  50. Generates output files in the specified output directory.
  51. """
  52. # Create dataset directory
  53. save_dir = Path('yolo_labels')
  54. if save_dir.exists():
  55. shutil.rmtree(save_dir) # delete dir
  56. for p in save_dir / 'labels', save_dir / 'images':
  57. p.mkdir(parents=True, exist_ok=True) # make dir
  58. # Convert classes
  59. coco80 = coco91_to_coco80_class()
  60. # Import json
  61. for json_file in sorted(Path(labels_dir).resolve().glob('*.json')):
  62. fn = Path(save_dir) / 'labels' / json_file.stem.replace('instances_', '') # folder name
  63. fn.mkdir(parents=True, exist_ok=True)
  64. with open(json_file) as f:
  65. data = json.load(f)
  66. # Create image dict
  67. images = {f'{x["id"]:d}': x for x in data['images']}
  68. # Create image-annotations dict
  69. imgToAnns = defaultdict(list)
  70. for ann in data['annotations']:
  71. imgToAnns[ann['image_id']].append(ann)
  72. # Write labels file
  73. for img_id, anns in tqdm(imgToAnns.items(), desc=f'Annotations {json_file}'):
  74. img = images[f'{img_id:d}']
  75. h, w, f = img['height'], img['width'], img['file_name']
  76. bboxes = []
  77. segments = []
  78. keypoints = []
  79. for ann in anns:
  80. if ann['iscrowd']:
  81. continue
  82. # The COCO box format is [top left x, top left y, width, height]
  83. box = np.array(ann['bbox'], dtype=np.float64)
  84. box[:2] += box[2:] / 2 # xy top-left corner to center
  85. box[[0, 2]] /= w # normalize x
  86. box[[1, 3]] /= h # normalize y
  87. if box[2] <= 0 or box[3] <= 0: # if w <= 0 and h <= 0
  88. continue
  89. cls = coco80[ann['category_id'] - 1] if cls91to80 else ann['category_id'] - 1 # class
  90. box = [cls] + box.tolist()
  91. if box not in bboxes:
  92. bboxes.append(box)
  93. if use_segments and ann.get('segmentation') is not None:
  94. if len(ann['segmentation']) == 0:
  95. segments.append([])
  96. continue
  97. elif len(ann['segmentation']) > 1:
  98. s = merge_multi_segment(ann['segmentation'])
  99. s = (np.concatenate(s, axis=0) / np.array([w, h])).reshape(-1).tolist()
  100. else:
  101. s = [j for i in ann['segmentation'] for j in i] # all segments concatenated
  102. s = (np.array(s).reshape(-1, 2) / np.array([w, h])).reshape(-1).tolist()
  103. s = [cls] + s
  104. if s not in segments:
  105. segments.append(s)
  106. if use_keypoints and ann.get('keypoints') is not None:
  107. keypoints.append(box + (np.array(ann['keypoints']).reshape(-1, 3) /
  108. np.array([w, h, 1])).reshape(-1).tolist())
  109. # Write
  110. with open((fn / f).with_suffix('.txt'), 'a') as file:
  111. for i in range(len(bboxes)):
  112. if use_keypoints:
  113. line = *(keypoints[i]), # cls, box, keypoints
  114. else:
  115. line = *(segments[i]
  116. if use_segments and len(segments[i]) > 0 else bboxes[i]), # cls, box or segments
  117. file.write(('%g ' * len(line)).rstrip() % line + '\n')
  118. def convert_dota_to_yolo_obb(dota_root_path: str):
  119. """
  120. Converts DOTA dataset annotations to YOLO OBB (Oriented Bounding Box) format.
  121. The function processes images in the 'train' and 'val' folders of the DOTA dataset. For each image, it reads the
  122. associated label from the original labels directory and writes new labels in YOLO OBB format to a new directory.
  123. Args:
  124. dota_root_path (str): The root directory path of the DOTA dataset.
  125. Example:
  126. ```python
  127. from ultralytics.data.converter import convert_dota_to_yolo_obb
  128. convert_dota_to_yolo_obb('path/to/DOTA')
  129. ```
  130. Notes:
  131. The directory structure assumed for the DOTA dataset:
  132. - DOTA
  133. - images
  134. - train
  135. - val
  136. - labels
  137. - train_original
  138. - val_original
  139. After the function execution, the new labels will be saved in:
  140. - DOTA
  141. - labels
  142. - train
  143. - val
  144. """
  145. dota_root_path = Path(dota_root_path)
  146. # Class names to indices mapping
  147. class_mapping = {
  148. 'plane': 0,
  149. 'ship': 1,
  150. 'storage-tank': 2,
  151. 'baseball-diamond': 3,
  152. 'tennis-court': 4,
  153. 'basketball-court': 5,
  154. 'ground-track-field': 6,
  155. 'harbor': 7,
  156. 'bridge': 8,
  157. 'large-vehicle': 9,
  158. 'small-vehicle': 10,
  159. 'helicopter': 11,
  160. 'roundabout': 12,
  161. 'soccer ball-field': 13,
  162. 'swimming-pool': 14,
  163. 'container-crane': 15,
  164. 'airport': 16,
  165. 'helipad': 17}
  166. def convert_label(image_name, image_width, image_height, orig_label_dir, save_dir):
  167. orig_label_path = orig_label_dir / f'{image_name}.txt'
  168. save_path = save_dir / f'{image_name}.txt'
  169. with orig_label_path.open('r') as f, save_path.open('w') as g:
  170. lines = f.readlines()
  171. for line in lines:
  172. parts = line.strip().split()
  173. if len(parts) < 9:
  174. continue
  175. class_name = parts[8]
  176. class_idx = class_mapping[class_name]
  177. coords = [float(p) for p in parts[:8]]
  178. normalized_coords = [
  179. coords[i] / image_width if i % 2 == 0 else coords[i] / image_height for i in range(8)]
  180. formatted_coords = ['{:.6g}'.format(coord) for coord in normalized_coords]
  181. g.write(f"{class_idx} {' '.join(formatted_coords)}\n")
  182. for phase in ['train', 'val']:
  183. image_dir = dota_root_path / 'images' / phase
  184. orig_label_dir = dota_root_path / 'labels' / f'{phase}_original'
  185. save_dir = dota_root_path / 'labels' / phase
  186. save_dir.mkdir(parents=True, exist_ok=True)
  187. image_paths = list(image_dir.iterdir())
  188. for image_path in tqdm(image_paths, desc=f'Processing {phase} images'):
  189. if image_path.suffix != '.png':
  190. continue
  191. image_name_without_ext = image_path.stem
  192. img = cv2.imread(str(image_path))
  193. h, w = img.shape[:2]
  194. convert_label(image_name_without_ext, w, h, orig_label_dir, save_dir)
  195. def min_index(arr1, arr2):
  196. """
  197. Find a pair of indexes with the shortest distance between two arrays of 2D points.
  198. Args:
  199. arr1 (np.array): A NumPy array of shape (N, 2) representing N 2D points.
  200. arr2 (np.array): A NumPy array of shape (M, 2) representing M 2D points.
  201. Returns:
  202. (tuple): A tuple containing the indexes of the points with the shortest distance in arr1 and arr2 respectively.
  203. """
  204. dis = ((arr1[:, None, :] - arr2[None, :, :]) ** 2).sum(-1)
  205. return np.unravel_index(np.argmin(dis, axis=None), dis.shape)
  206. def merge_multi_segment(segments):
  207. """
  208. Merge multiple segments into one list by connecting the coordinates with the minimum distance between each segment.
  209. This function connects these coordinates with a thin line to merge all segments into one.
  210. Args:
  211. segments (List[List]): Original segmentations in COCO's JSON file.
  212. Each element is a list of coordinates, like [segmentation1, segmentation2,...].
  213. Returns:
  214. s (List[np.ndarray]): A list of connected segments represented as NumPy arrays.
  215. """
  216. s = []
  217. segments = [np.array(i).reshape(-1, 2) for i in segments]
  218. idx_list = [[] for _ in range(len(segments))]
  219. # record the indexes with min distance between each segment
  220. for i in range(1, len(segments)):
  221. idx1, idx2 = min_index(segments[i - 1], segments[i])
  222. idx_list[i - 1].append(idx1)
  223. idx_list[i].append(idx2)
  224. # use two round to connect all the segments
  225. for k in range(2):
  226. # forward connection
  227. if k == 0:
  228. for i, idx in enumerate(idx_list):
  229. # middle segments have two indexes
  230. # reverse the index of middle segments
  231. if len(idx) == 2 and idx[0] > idx[1]:
  232. idx = idx[::-1]
  233. segments[i] = segments[i][::-1, :]
  234. segments[i] = np.roll(segments[i], -idx[0], axis=0)
  235. segments[i] = np.concatenate([segments[i], segments[i][:1]])
  236. # deal with the first segment and the last one
  237. if i in [0, len(idx_list) - 1]:
  238. s.append(segments[i])
  239. else:
  240. idx = [0, idx[1] - idx[0]]
  241. s.append(segments[i][idx[0]:idx[1] + 1])
  242. else:
  243. for i in range(len(idx_list) - 1, -1, -1):
  244. if i not in [0, len(idx_list) - 1]:
  245. idx = idx_list[i]
  246. nidx = abs(idx[1] - idx[0])
  247. s.append(segments[i][nidx:])
  248. return s