converter.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import json
  3. from collections import defaultdict
  4. from pathlib import Path
  5. import cv2
  6. import numpy as np
  7. from ultralytics.utils import LOGGER, TQDM
  8. from ultralytics.utils.files import increment_path
  9. def coco91_to_coco80_class():
  10. """
  11. Converts 91-index COCO class IDs to 80-index COCO class IDs.
  12. Returns:
  13. (list): A list of 91 class IDs where the index represents the 80-index class ID and the value is the
  14. corresponding 91-index class ID.
  15. """
  16. return [
  17. 0,
  18. 1,
  19. 2,
  20. 3,
  21. 4,
  22. 5,
  23. 6,
  24. 7,
  25. 8,
  26. 9,
  27. 10,
  28. None,
  29. 11,
  30. 12,
  31. 13,
  32. 14,
  33. 15,
  34. 16,
  35. 17,
  36. 18,
  37. 19,
  38. 20,
  39. 21,
  40. 22,
  41. 23,
  42. None,
  43. 24,
  44. 25,
  45. None,
  46. None,
  47. 26,
  48. 27,
  49. 28,
  50. 29,
  51. 30,
  52. 31,
  53. 32,
  54. 33,
  55. 34,
  56. 35,
  57. 36,
  58. 37,
  59. 38,
  60. 39,
  61. None,
  62. 40,
  63. 41,
  64. 42,
  65. 43,
  66. 44,
  67. 45,
  68. 46,
  69. 47,
  70. 48,
  71. 49,
  72. 50,
  73. 51,
  74. 52,
  75. 53,
  76. 54,
  77. 55,
  78. 56,
  79. 57,
  80. 58,
  81. 59,
  82. None,
  83. 60,
  84. None,
  85. None,
  86. 61,
  87. None,
  88. 62,
  89. 63,
  90. 64,
  91. 65,
  92. 66,
  93. 67,
  94. 68,
  95. 69,
  96. 70,
  97. 71,
  98. 72,
  99. None,
  100. 73,
  101. 74,
  102. 75,
  103. 76,
  104. 77,
  105. 78,
  106. 79,
  107. None,
  108. ]
  109. def coco80_to_coco91_class():
  110. """
  111. Converts 80-index (val2014) to 91-index (paper).
  112. For details see https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/.
  113. Example:
  114. ```python
  115. import numpy as np
  116. a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
  117. b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
  118. x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
  119. x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
  120. ```
  121. """
  122. return [
  123. 1,
  124. 2,
  125. 3,
  126. 4,
  127. 5,
  128. 6,
  129. 7,
  130. 8,
  131. 9,
  132. 10,
  133. 11,
  134. 13,
  135. 14,
  136. 15,
  137. 16,
  138. 17,
  139. 18,
  140. 19,
  141. 20,
  142. 21,
  143. 22,
  144. 23,
  145. 24,
  146. 25,
  147. 27,
  148. 28,
  149. 31,
  150. 32,
  151. 33,
  152. 34,
  153. 35,
  154. 36,
  155. 37,
  156. 38,
  157. 39,
  158. 40,
  159. 41,
  160. 42,
  161. 43,
  162. 44,
  163. 46,
  164. 47,
  165. 48,
  166. 49,
  167. 50,
  168. 51,
  169. 52,
  170. 53,
  171. 54,
  172. 55,
  173. 56,
  174. 57,
  175. 58,
  176. 59,
  177. 60,
  178. 61,
  179. 62,
  180. 63,
  181. 64,
  182. 65,
  183. 67,
  184. 70,
  185. 72,
  186. 73,
  187. 74,
  188. 75,
  189. 76,
  190. 77,
  191. 78,
  192. 79,
  193. 80,
  194. 81,
  195. 82,
  196. 84,
  197. 85,
  198. 86,
  199. 87,
  200. 88,
  201. 89,
  202. 90,
  203. ]
  204. def convert_coco(
  205. labels_dir="../coco/annotations/",
  206. save_dir="coco_converted/",
  207. use_segments=False,
  208. use_keypoints=False,
  209. cls91to80=True,
  210. lvis=False,
  211. ):
  212. """
  213. Converts COCO dataset annotations to a YOLO annotation format suitable for training YOLO models.
  214. Args:
  215. labels_dir (str, optional): Path to directory containing COCO dataset annotation files.
  216. save_dir (str, optional): Path to directory to save results to.
  217. use_segments (bool, optional): Whether to include segmentation masks in the output.
  218. use_keypoints (bool, optional): Whether to include keypoint annotations in the output.
  219. cls91to80 (bool, optional): Whether to map 91 COCO class IDs to the corresponding 80 COCO class IDs.
  220. lvis (bool, optional): Whether to convert data in lvis dataset way.
  221. Example:
  222. ```python
  223. from ultralytics.data.converter import convert_coco
  224. convert_coco('../datasets/coco/annotations/', use_segments=True, use_keypoints=False, cls91to80=True)
  225. convert_coco('../datasets/lvis/annotations/', use_segments=True, use_keypoints=False, cls91to80=False, lvis=True)
  226. ```
  227. Output:
  228. Generates output files in the specified output directory.
  229. """
  230. # Create dataset directory
  231. save_dir = increment_path(save_dir) # increment if save directory already exists
  232. for p in save_dir / "labels", save_dir / "images":
  233. p.mkdir(parents=True, exist_ok=True) # make dir
  234. # Convert classes
  235. coco80 = coco91_to_coco80_class()
  236. # Import json
  237. for json_file in sorted(Path(labels_dir).resolve().glob("*.json")):
  238. lname = "" if lvis else json_file.stem.replace("instances_", "")
  239. fn = Path(save_dir) / "labels" / lname # folder name
  240. fn.mkdir(parents=True, exist_ok=True)
  241. if lvis:
  242. # NOTE: create folders for both train and val in advance,
  243. # since LVIS val set contains images from COCO 2017 train in addition to the COCO 2017 val split.
  244. (fn / "train2017").mkdir(parents=True, exist_ok=True)
  245. (fn / "val2017").mkdir(parents=True, exist_ok=True)
  246. with open(json_file) as f:
  247. data = json.load(f)
  248. # Create image dict
  249. images = {f'{x["id"]:d}': x for x in data["images"]}
  250. # Create image-annotations dict
  251. imgToAnns = defaultdict(list)
  252. for ann in data["annotations"]:
  253. imgToAnns[ann["image_id"]].append(ann)
  254. image_txt = []
  255. # Write labels file
  256. for img_id, anns in TQDM(imgToAnns.items(), desc=f"Annotations {json_file}"):
  257. img = images[f"{img_id:d}"]
  258. h, w = img["height"], img["width"]
  259. f = str(Path(img["coco_url"]).relative_to("http://images.cocodataset.org")) if lvis else img["file_name"]
  260. if lvis:
  261. image_txt.append(str(Path("./images") / f))
  262. bboxes = []
  263. segments = []
  264. keypoints = []
  265. for ann in anns:
  266. if ann.get("iscrowd", False):
  267. continue
  268. # The COCO box format is [top left x, top left y, width, height]
  269. box = np.array(ann["bbox"], dtype=np.float64)
  270. box[:2] += box[2:] / 2 # xy top-left corner to center
  271. box[[0, 2]] /= w # normalize x
  272. box[[1, 3]] /= h # normalize y
  273. if box[2] <= 0 or box[3] <= 0: # if w <= 0 and h <= 0
  274. continue
  275. cls = coco80[ann["category_id"] - 1] if cls91to80 else ann["category_id"] - 1 # class
  276. box = [cls] + box.tolist()
  277. if box not in bboxes:
  278. bboxes.append(box)
  279. if use_segments and ann.get("segmentation") is not None:
  280. if len(ann["segmentation"]) == 0:
  281. segments.append([])
  282. continue
  283. elif len(ann["segmentation"]) > 1:
  284. s = merge_multi_segment(ann["segmentation"])
  285. s = (np.concatenate(s, axis=0) / np.array([w, h])).reshape(-1).tolist()
  286. else:
  287. s = [j for i in ann["segmentation"] for j in i] # all segments concatenated
  288. s = (np.array(s).reshape(-1, 2) / np.array([w, h])).reshape(-1).tolist()
  289. s = [cls] + s
  290. segments.append(s)
  291. if use_keypoints and ann.get("keypoints") is not None:
  292. keypoints.append(
  293. box + (np.array(ann["keypoints"]).reshape(-1, 3) / np.array([w, h, 1])).reshape(-1).tolist()
  294. )
  295. # Write
  296. with open((fn / f).with_suffix(".txt"), "a") as file:
  297. for i in range(len(bboxes)):
  298. if use_keypoints:
  299. line = (*(keypoints[i]),) # cls, box, keypoints
  300. else:
  301. line = (
  302. *(segments[i] if use_segments and len(segments[i]) > 0 else bboxes[i]),
  303. ) # cls, box or segments
  304. file.write(("%g " * len(line)).rstrip() % line + "\n")
  305. if lvis:
  306. with open((Path(save_dir) / json_file.name.replace("lvis_v1_", "").replace(".json", ".txt")), "a") as f:
  307. f.writelines(f"{line}\n" for line in image_txt)
  308. LOGGER.info(f"{'LVIS' if lvis else 'COCO'} data converted successfully.\nResults saved to {save_dir.resolve()}")
  309. def convert_dota_to_yolo_obb(dota_root_path: str):
  310. """
  311. Converts DOTA dataset annotations to YOLO OBB (Oriented Bounding Box) format.
  312. The function processes images in the 'train' and 'val' folders of the DOTA dataset. For each image, it reads the
  313. associated label from the original labels directory and writes new labels in YOLO OBB format to a new directory.
  314. Args:
  315. dota_root_path (str): The root directory path of the DOTA dataset.
  316. Example:
  317. ```python
  318. from ultralytics.data.converter import convert_dota_to_yolo_obb
  319. convert_dota_to_yolo_obb('path/to/DOTA')
  320. ```
  321. Notes:
  322. The directory structure assumed for the DOTA dataset:
  323. - DOTA
  324. ├─ images
  325. │ ├─ train
  326. │ └─ val
  327. └─ labels
  328. ├─ train_original
  329. └─ val_original
  330. After execution, the function will organize the labels into:
  331. - DOTA
  332. └─ labels
  333. ├─ train
  334. └─ val
  335. """
  336. dota_root_path = Path(dota_root_path)
  337. # Class names to indices mapping
  338. class_mapping = {
  339. "plane": 0,
  340. "ship": 1,
  341. "storage-tank": 2,
  342. "baseball-diamond": 3,
  343. "tennis-court": 4,
  344. "basketball-court": 5,
  345. "ground-track-field": 6,
  346. "harbor": 7,
  347. "bridge": 8,
  348. "large-vehicle": 9,
  349. "small-vehicle": 10,
  350. "helicopter": 11,
  351. "roundabout": 12,
  352. "soccer-ball-field": 13,
  353. "swimming-pool": 14,
  354. "container-crane": 15,
  355. "airport": 16,
  356. "helipad": 17,
  357. }
  358. def convert_label(image_name, image_width, image_height, orig_label_dir, save_dir):
  359. """Converts a single image's DOTA annotation to YOLO OBB format and saves it to a specified directory."""
  360. orig_label_path = orig_label_dir / f"{image_name}.txt"
  361. save_path = save_dir / f"{image_name}.txt"
  362. with orig_label_path.open("r") as f, save_path.open("w") as g:
  363. lines = f.readlines()
  364. for line in lines:
  365. parts = line.strip().split()
  366. if len(parts) < 9:
  367. continue
  368. class_name = parts[8]
  369. class_idx = class_mapping[class_name]
  370. coords = [float(p) for p in parts[:8]]
  371. normalized_coords = [
  372. coords[i] / image_width if i % 2 == 0 else coords[i] / image_height for i in range(8)
  373. ]
  374. formatted_coords = ["{:.6g}".format(coord) for coord in normalized_coords]
  375. g.write(f"{class_idx} {' '.join(formatted_coords)}\n")
  376. for phase in ["train", "val"]:
  377. image_dir = dota_root_path / "images" / phase
  378. orig_label_dir = dota_root_path / "labels" / f"{phase}_original"
  379. save_dir = dota_root_path / "labels" / phase
  380. save_dir.mkdir(parents=True, exist_ok=True)
  381. image_paths = list(image_dir.iterdir())
  382. for image_path in TQDM(image_paths, desc=f"Processing {phase} images"):
  383. if image_path.suffix != ".png":
  384. continue
  385. image_name_without_ext = image_path.stem
  386. img = cv2.imread(str(image_path))
  387. h, w = img.shape[:2]
  388. convert_label(image_name_without_ext, w, h, orig_label_dir, save_dir)
  389. def min_index(arr1, arr2):
  390. """
  391. Find a pair of indexes with the shortest distance between two arrays of 2D points.
  392. Args:
  393. arr1 (np.ndarray): A NumPy array of shape (N, 2) representing N 2D points.
  394. arr2 (np.ndarray): A NumPy array of shape (M, 2) representing M 2D points.
  395. Returns:
  396. (tuple): A tuple containing the indexes of the points with the shortest distance in arr1 and arr2 respectively.
  397. """
  398. dis = ((arr1[:, None, :] - arr2[None, :, :]) ** 2).sum(-1)
  399. return np.unravel_index(np.argmin(dis, axis=None), dis.shape)
  400. def merge_multi_segment(segments):
  401. """
  402. Merge multiple segments into one list by connecting the coordinates with the minimum distance between each segment.
  403. This function connects these coordinates with a thin line to merge all segments into one.
  404. Args:
  405. segments (List[List]): Original segmentations in COCO's JSON file.
  406. Each element is a list of coordinates, like [segmentation1, segmentation2,...].
  407. Returns:
  408. s (List[np.ndarray]): A list of connected segments represented as NumPy arrays.
  409. """
  410. s = []
  411. segments = [np.array(i).reshape(-1, 2) for i in segments]
  412. idx_list = [[] for _ in range(len(segments))]
  413. # Record the indexes with min distance between each segment
  414. for i in range(1, len(segments)):
  415. idx1, idx2 = min_index(segments[i - 1], segments[i])
  416. idx_list[i - 1].append(idx1)
  417. idx_list[i].append(idx2)
  418. # Use two round to connect all the segments
  419. for k in range(2):
  420. # Forward connection
  421. if k == 0:
  422. for i, idx in enumerate(idx_list):
  423. # Middle segments have two indexes, reverse the index of middle segments
  424. if len(idx) == 2 and idx[0] > idx[1]:
  425. idx = idx[::-1]
  426. segments[i] = segments[i][::-1, :]
  427. segments[i] = np.roll(segments[i], -idx[0], axis=0)
  428. segments[i] = np.concatenate([segments[i], segments[i][:1]])
  429. # Deal with the first segment and the last one
  430. if i in {0, len(idx_list) - 1}:
  431. s.append(segments[i])
  432. else:
  433. idx = [0, idx[1] - idx[0]]
  434. s.append(segments[i][idx[0] : idx[1] + 1])
  435. else:
  436. for i in range(len(idx_list) - 1, -1, -1):
  437. if i not in {0, len(idx_list) - 1}:
  438. idx = idx_list[i]
  439. nidx = abs(idx[1] - idx[0])
  440. s.append(segments[i][nidx:])
  441. return s
  442. def yolo_bbox2segment(im_dir, save_dir=None, sam_model="sam_b.pt"):
  443. """
  444. Converts existing object detection dataset (bounding boxes) to segmentation dataset or oriented bounding box (OBB)
  445. in YOLO format. Generates segmentation data using SAM auto-annotator as needed.
  446. Args:
  447. im_dir (str | Path): Path to image directory to convert.
  448. save_dir (str | Path): Path to save the generated labels, labels will be saved
  449. into `labels-segment` in the same directory level of `im_dir` if save_dir is None. Default: None.
  450. sam_model (str): Segmentation model to use for intermediate segmentation data; optional.
  451. Notes:
  452. The input directory structure assumed for dataset:
  453. - im_dir
  454. ├─ 001.jpg
  455. ├─ ..
  456. └─ NNN.jpg
  457. - labels
  458. ├─ 001.txt
  459. ├─ ..
  460. └─ NNN.txt
  461. """
  462. from tqdm import tqdm
  463. from ultralytics import SAM
  464. from ultralytics.data import YOLODataset
  465. from ultralytics.utils import LOGGER
  466. from ultralytics.utils.ops import xywh2xyxy
  467. # NOTE: add placeholder to pass class index check
  468. dataset = YOLODataset(im_dir, data=dict(names=list(range(1000))))
  469. if len(dataset.labels[0]["segments"]) > 0: # if it's segment data
  470. LOGGER.info("Segmentation labels detected, no need to generate new ones!")
  471. return
  472. LOGGER.info("Detection labels detected, generating segment labels by SAM model!")
  473. sam_model = SAM(sam_model)
  474. for label in tqdm(dataset.labels, total=len(dataset.labels), desc="Generating segment labels"):
  475. h, w = label["shape"]
  476. boxes = label["bboxes"]
  477. if len(boxes) == 0: # skip empty labels
  478. continue
  479. boxes[:, [0, 2]] *= w
  480. boxes[:, [1, 3]] *= h
  481. im = cv2.imread(label["im_file"])
  482. sam_results = sam_model(im, bboxes=xywh2xyxy(boxes), verbose=False, save=False)
  483. label["segments"] = sam_results[0].masks.xyn
  484. save_dir = Path(save_dir) if save_dir else Path(im_dir).parent / "labels-segment"
  485. save_dir.mkdir(parents=True, exist_ok=True)
  486. for label in dataset.labels:
  487. texts = []
  488. lb_name = Path(label["im_file"]).with_suffix(".txt").name
  489. txt_file = save_dir / lb_name
  490. cls = label["cls"]
  491. for i, s in enumerate(label["segments"]):
  492. line = (int(cls[i]), *s.reshape(-1))
  493. texts.append(("%g " * len(line)).rstrip() % line)
  494. if texts:
  495. with open(txt_file, "a") as f:
  496. f.writelines(text + "\n" for text in texts)
  497. LOGGER.info(f"Generated segment labels saved in {save_dir}")