converter.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import json
  3. import random
  4. import shutil
  5. from collections import defaultdict
  6. from concurrent.futures import ThreadPoolExecutor, as_completed
  7. from pathlib import Path
  8. import cv2
  9. import numpy as np
  10. from PIL import Image
  11. from ultralytics.utils import DATASETS_DIR, LOGGER, NUM_THREADS, TQDM
  12. from ultralytics.utils.downloads import download
  13. from ultralytics.utils.files import increment_path
  14. def coco91_to_coco80_class():
  15. """
  16. Converts 91-index COCO class IDs to 80-index COCO class IDs.
  17. Returns:
  18. (list): A list of 91 class IDs where the index represents the 80-index class ID and the value is the
  19. corresponding 91-index class ID.
  20. """
  21. return [
  22. 0,
  23. 1,
  24. 2,
  25. 3,
  26. 4,
  27. 5,
  28. 6,
  29. 7,
  30. 8,
  31. 9,
  32. 10,
  33. None,
  34. 11,
  35. 12,
  36. 13,
  37. 14,
  38. 15,
  39. 16,
  40. 17,
  41. 18,
  42. 19,
  43. 20,
  44. 21,
  45. 22,
  46. 23,
  47. None,
  48. 24,
  49. 25,
  50. None,
  51. None,
  52. 26,
  53. 27,
  54. 28,
  55. 29,
  56. 30,
  57. 31,
  58. 32,
  59. 33,
  60. 34,
  61. 35,
  62. 36,
  63. 37,
  64. 38,
  65. 39,
  66. None,
  67. 40,
  68. 41,
  69. 42,
  70. 43,
  71. 44,
  72. 45,
  73. 46,
  74. 47,
  75. 48,
  76. 49,
  77. 50,
  78. 51,
  79. 52,
  80. 53,
  81. 54,
  82. 55,
  83. 56,
  84. 57,
  85. 58,
  86. 59,
  87. None,
  88. 60,
  89. None,
  90. None,
  91. 61,
  92. None,
  93. 62,
  94. 63,
  95. 64,
  96. 65,
  97. 66,
  98. 67,
  99. 68,
  100. 69,
  101. 70,
  102. 71,
  103. 72,
  104. None,
  105. 73,
  106. 74,
  107. 75,
  108. 76,
  109. 77,
  110. 78,
  111. 79,
  112. None,
  113. ]
  114. def coco80_to_coco91_class():
  115. r"""
  116. Converts 80-index (val2014) to 91-index (paper).
  117. For details see https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/.
  118. Example:
  119. ```python
  120. import numpy as np
  121. a = np.loadtxt("data/coco.names", dtype="str", delimiter="\n")
  122. b = np.loadtxt("data/coco_paper.names", dtype="str", delimiter="\n")
  123. x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
  124. x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
  125. ```
  126. """
  127. return [
  128. 1,
  129. 2,
  130. 3,
  131. 4,
  132. 5,
  133. 6,
  134. 7,
  135. 8,
  136. 9,
  137. 10,
  138. 11,
  139. 13,
  140. 14,
  141. 15,
  142. 16,
  143. 17,
  144. 18,
  145. 19,
  146. 20,
  147. 21,
  148. 22,
  149. 23,
  150. 24,
  151. 25,
  152. 27,
  153. 28,
  154. 31,
  155. 32,
  156. 33,
  157. 34,
  158. 35,
  159. 36,
  160. 37,
  161. 38,
  162. 39,
  163. 40,
  164. 41,
  165. 42,
  166. 43,
  167. 44,
  168. 46,
  169. 47,
  170. 48,
  171. 49,
  172. 50,
  173. 51,
  174. 52,
  175. 53,
  176. 54,
  177. 55,
  178. 56,
  179. 57,
  180. 58,
  181. 59,
  182. 60,
  183. 61,
  184. 62,
  185. 63,
  186. 64,
  187. 65,
  188. 67,
  189. 70,
  190. 72,
  191. 73,
  192. 74,
  193. 75,
  194. 76,
  195. 77,
  196. 78,
  197. 79,
  198. 80,
  199. 81,
  200. 82,
  201. 84,
  202. 85,
  203. 86,
  204. 87,
  205. 88,
  206. 89,
  207. 90,
  208. ]
  209. def convert_coco(
  210. labels_dir="../coco/annotations/",
  211. save_dir="coco_converted/",
  212. use_segments=False,
  213. use_keypoints=False,
  214. cls91to80=True,
  215. lvis=False,
  216. ):
  217. """
  218. Converts COCO dataset annotations to a YOLO annotation format suitable for training YOLO models.
  219. Args:
  220. labels_dir (str, optional): Path to directory containing COCO dataset annotation files.
  221. save_dir (str, optional): Path to directory to save results to.
  222. use_segments (bool, optional): Whether to include segmentation masks in the output.
  223. use_keypoints (bool, optional): Whether to include keypoint annotations in the output.
  224. cls91to80 (bool, optional): Whether to map 91 COCO class IDs to the corresponding 80 COCO class IDs.
  225. lvis (bool, optional): Whether to convert data in lvis dataset way.
  226. Example:
  227. ```python
  228. from ultralytics.data.converter import convert_coco
  229. convert_coco("../datasets/coco/annotations/", use_segments=True, use_keypoints=False, cls91to80=False)
  230. convert_coco(
  231. "../datasets/lvis/annotations/", use_segments=True, use_keypoints=False, cls91to80=False, lvis=True
  232. )
  233. ```
  234. Output:
  235. Generates output files in the specified output directory.
  236. """
  237. # Create dataset directory
  238. save_dir = increment_path(save_dir) # increment if save directory already exists
  239. for p in save_dir / "labels", save_dir / "images":
  240. p.mkdir(parents=True, exist_ok=True) # make dir
  241. # Convert classes
  242. coco80 = coco91_to_coco80_class()
  243. # Import json
  244. for json_file in sorted(Path(labels_dir).resolve().glob("*.json")):
  245. lname = "" if lvis else json_file.stem.replace("instances_", "")
  246. fn = Path(save_dir) / "labels" / lname # folder name
  247. fn.mkdir(parents=True, exist_ok=True)
  248. if lvis:
  249. # NOTE: create folders for both train and val in advance,
  250. # since LVIS val set contains images from COCO 2017 train in addition to the COCO 2017 val split.
  251. (fn / "train2017").mkdir(parents=True, exist_ok=True)
  252. (fn / "val2017").mkdir(parents=True, exist_ok=True)
  253. with open(json_file, encoding="utf-8") as f:
  254. data = json.load(f)
  255. # Create image dict
  256. images = {f"{x['id']:d}": x for x in data["images"]}
  257. # Create image-annotations dict
  258. imgToAnns = defaultdict(list)
  259. for ann in data["annotations"]:
  260. imgToAnns[ann["image_id"]].append(ann)
  261. image_txt = []
  262. # Write labels file
  263. for img_id, anns in TQDM(imgToAnns.items(), desc=f"Annotations {json_file}"):
  264. img = images[f"{img_id:d}"]
  265. h, w = img["height"], img["width"]
  266. f = str(Path(img["coco_url"]).relative_to("http://images.cocodataset.org")) if lvis else img["file_name"]
  267. if lvis:
  268. image_txt.append(str(Path("./images") / f))
  269. bboxes = []
  270. segments = []
  271. keypoints = []
  272. for ann in anns:
  273. if ann.get("iscrowd", False):
  274. continue
  275. # The COCO box format is [top left x, top left y, width, height]
  276. box = np.array(ann["bbox"], dtype=np.float64)
  277. box[:2] += box[2:] / 2 # xy top-left corner to center
  278. box[[0, 2]] /= w # normalize x
  279. box[[1, 3]] /= h # normalize y
  280. if box[2] <= 0 or box[3] <= 0: # if w <= 0 and h <= 0
  281. continue
  282. cls = coco80[ann["category_id"] - 1] if cls91to80 else ann["category_id"] - 1 # class
  283. box = [cls] + box.tolist()
  284. if box not in bboxes:
  285. bboxes.append(box)
  286. if use_segments and ann.get("segmentation") is not None:
  287. if len(ann["segmentation"]) == 0:
  288. segments.append([])
  289. continue
  290. elif len(ann["segmentation"]) > 1:
  291. s = merge_multi_segment(ann["segmentation"])
  292. s = (np.concatenate(s, axis=0) / np.array([w, h])).reshape(-1).tolist()
  293. else:
  294. s = [j for i in ann["segmentation"] for j in i] # all segments concatenated
  295. s = (np.array(s).reshape(-1, 2) / np.array([w, h])).reshape(-1).tolist()
  296. s = [cls] + s
  297. segments.append(s)
  298. if use_keypoints and ann.get("keypoints") is not None:
  299. keypoints.append(
  300. box + (np.array(ann["keypoints"]).reshape(-1, 3) / np.array([w, h, 1])).reshape(-1).tolist()
  301. )
  302. # Write
  303. with open((fn / f).with_suffix(".txt"), "a") as file:
  304. for i in range(len(bboxes)):
  305. if use_keypoints:
  306. line = (*(keypoints[i]),) # cls, box, keypoints
  307. else:
  308. line = (
  309. *(segments[i] if use_segments and len(segments[i]) > 0 else bboxes[i]),
  310. ) # cls, box or segments
  311. file.write(("%g " * len(line)).rstrip() % line + "\n")
  312. if lvis:
  313. with open((Path(save_dir) / json_file.name.replace("lvis_v1_", "").replace(".json", ".txt")), "a") as f:
  314. f.writelines(f"{line}\n" for line in image_txt)
  315. LOGGER.info(f"{'LVIS' if lvis else 'COCO'} data converted successfully.\nResults saved to {save_dir.resolve()}")
  316. def convert_segment_masks_to_yolo_seg(masks_dir, output_dir, classes):
  317. """
  318. Converts a dataset of segmentation mask images to the YOLO segmentation format.
  319. This function takes the directory containing the binary format mask images and converts them into YOLO segmentation format.
  320. The converted masks are saved in the specified output directory.
  321. Args:
  322. masks_dir (str): The path to the directory where all mask images (png, jpg) are stored.
  323. output_dir (str): The path to the directory where the converted YOLO segmentation masks will be stored.
  324. classes (int): Total classes in the dataset i.e. for COCO classes=80
  325. Example:
  326. ```python
  327. from ultralytics.data.converter import convert_segment_masks_to_yolo_seg
  328. # The classes here is the total classes in the dataset, for COCO dataset we have 80 classes
  329. convert_segment_masks_to_yolo_seg("path/to/masks_directory", "path/to/output/directory", classes=80)
  330. ```
  331. Notes:
  332. The expected directory structure for the masks is:
  333. - masks
  334. ├─ mask_image_01.png or mask_image_01.jpg
  335. ├─ mask_image_02.png or mask_image_02.jpg
  336. ├─ mask_image_03.png or mask_image_03.jpg
  337. └─ mask_image_04.png or mask_image_04.jpg
  338. After execution, the labels will be organized in the following structure:
  339. - output_dir
  340. ├─ mask_yolo_01.txt
  341. ├─ mask_yolo_02.txt
  342. ├─ mask_yolo_03.txt
  343. └─ mask_yolo_04.txt
  344. """
  345. pixel_to_class_mapping = {i + 1: i for i in range(classes)}
  346. for mask_path in Path(masks_dir).iterdir():
  347. if mask_path.suffix in {".png", ".jpg"}:
  348. mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE) # Read the mask image in grayscale
  349. img_height, img_width = mask.shape # Get image dimensions
  350. LOGGER.info(f"Processing {mask_path} imgsz = {img_height} x {img_width}")
  351. unique_values = np.unique(mask) # Get unique pixel values representing different classes
  352. yolo_format_data = []
  353. for value in unique_values:
  354. if value == 0:
  355. continue # Skip background
  356. class_index = pixel_to_class_mapping.get(value, -1)
  357. if class_index == -1:
  358. LOGGER.warning(f"Unknown class for pixel value {value} in file {mask_path}, skipping.")
  359. continue
  360. # Create a binary mask for the current class and find contours
  361. contours, _ = cv2.findContours(
  362. (mask == value).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
  363. ) # Find contours
  364. for contour in contours:
  365. if len(contour) >= 3: # YOLO requires at least 3 points for a valid segmentation
  366. contour = contour.squeeze() # Remove single-dimensional entries
  367. yolo_format = [class_index]
  368. for point in contour:
  369. # Normalize the coordinates
  370. yolo_format.append(round(point[0] / img_width, 6)) # Rounding to 6 decimal places
  371. yolo_format.append(round(point[1] / img_height, 6))
  372. yolo_format_data.append(yolo_format)
  373. # Save Ultralytics YOLO format data to file
  374. output_path = Path(output_dir) / f"{mask_path.stem}.txt"
  375. with open(output_path, "w") as file:
  376. for item in yolo_format_data:
  377. line = " ".join(map(str, item))
  378. file.write(line + "\n")
  379. LOGGER.info(f"Processed and stored at {output_path} imgsz = {img_height} x {img_width}")
  380. def convert_dota_to_yolo_obb(dota_root_path: str):
  381. """
  382. Converts DOTA dataset annotations to YOLO OBB (Oriented Bounding Box) format.
  383. The function processes images in the 'train' and 'val' folders of the DOTA dataset. For each image, it reads the
  384. associated label from the original labels directory and writes new labels in YOLO OBB format to a new directory.
  385. Args:
  386. dota_root_path (str): The root directory path of the DOTA dataset.
  387. Example:
  388. ```python
  389. from ultralytics.data.converter import convert_dota_to_yolo_obb
  390. convert_dota_to_yolo_obb("path/to/DOTA")
  391. ```
  392. Notes:
  393. The directory structure assumed for the DOTA dataset:
  394. - DOTA
  395. ├─ images
  396. │ ├─ train
  397. │ └─ val
  398. └─ labels
  399. ├─ train_original
  400. └─ val_original
  401. After execution, the function will organize the labels into:
  402. - DOTA
  403. └─ labels
  404. ├─ train
  405. └─ val
  406. """
  407. dota_root_path = Path(dota_root_path)
  408. # Class names to indices mapping
  409. class_mapping = {
  410. "plane": 0,
  411. "ship": 1,
  412. "storage-tank": 2,
  413. "baseball-diamond": 3,
  414. "tennis-court": 4,
  415. "basketball-court": 5,
  416. "ground-track-field": 6,
  417. "harbor": 7,
  418. "bridge": 8,
  419. "large-vehicle": 9,
  420. "small-vehicle": 10,
  421. "helicopter": 11,
  422. "roundabout": 12,
  423. "soccer-ball-field": 13,
  424. "swimming-pool": 14,
  425. "container-crane": 15,
  426. "airport": 16,
  427. "helipad": 17,
  428. }
  429. def convert_label(image_name, image_width, image_height, orig_label_dir, save_dir):
  430. """Converts a single image's DOTA annotation to YOLO OBB format and saves it to a specified directory."""
  431. orig_label_path = orig_label_dir / f"{image_name}.txt"
  432. save_path = save_dir / f"{image_name}.txt"
  433. with orig_label_path.open("r") as f, save_path.open("w") as g:
  434. lines = f.readlines()
  435. for line in lines:
  436. parts = line.strip().split()
  437. if len(parts) < 9:
  438. continue
  439. class_name = parts[8]
  440. class_idx = class_mapping[class_name]
  441. coords = [float(p) for p in parts[:8]]
  442. normalized_coords = [
  443. coords[i] / image_width if i % 2 == 0 else coords[i] / image_height for i in range(8)
  444. ]
  445. formatted_coords = [f"{coord:.6g}" for coord in normalized_coords]
  446. g.write(f"{class_idx} {' '.join(formatted_coords)}\n")
  447. for phase in ["train", "val"]:
  448. image_dir = dota_root_path / "images" / phase
  449. orig_label_dir = dota_root_path / "labels" / f"{phase}_original"
  450. save_dir = dota_root_path / "labels" / phase
  451. save_dir.mkdir(parents=True, exist_ok=True)
  452. image_paths = list(image_dir.iterdir())
  453. for image_path in TQDM(image_paths, desc=f"Processing {phase} images"):
  454. if image_path.suffix != ".png":
  455. continue
  456. image_name_without_ext = image_path.stem
  457. img = cv2.imread(str(image_path))
  458. h, w = img.shape[:2]
  459. convert_label(image_name_without_ext, w, h, orig_label_dir, save_dir)
  460. def min_index(arr1, arr2):
  461. """
  462. Find a pair of indexes with the shortest distance between two arrays of 2D points.
  463. Args:
  464. arr1 (np.ndarray): A NumPy array of shape (N, 2) representing N 2D points.
  465. arr2 (np.ndarray): A NumPy array of shape (M, 2) representing M 2D points.
  466. Returns:
  467. (tuple): A tuple containing the indexes of the points with the shortest distance in arr1 and arr2 respectively.
  468. """
  469. dis = ((arr1[:, None, :] - arr2[None, :, :]) ** 2).sum(-1)
  470. return np.unravel_index(np.argmin(dis, axis=None), dis.shape)
  471. def merge_multi_segment(segments):
  472. """
  473. Merge multiple segments into one list by connecting the coordinates with the minimum distance between each segment.
  474. This function connects these coordinates with a thin line to merge all segments into one.
  475. Args:
  476. segments (List[List]): Original segmentations in COCO's JSON file.
  477. Each element is a list of coordinates, like [segmentation1, segmentation2,...].
  478. Returns:
  479. s (List[np.ndarray]): A list of connected segments represented as NumPy arrays.
  480. """
  481. s = []
  482. segments = [np.array(i).reshape(-1, 2) for i in segments]
  483. idx_list = [[] for _ in range(len(segments))]
  484. # Record the indexes with min distance between each segment
  485. for i in range(1, len(segments)):
  486. idx1, idx2 = min_index(segments[i - 1], segments[i])
  487. idx_list[i - 1].append(idx1)
  488. idx_list[i].append(idx2)
  489. # Use two round to connect all the segments
  490. for k in range(2):
  491. # Forward connection
  492. if k == 0:
  493. for i, idx in enumerate(idx_list):
  494. # Middle segments have two indexes, reverse the index of middle segments
  495. if len(idx) == 2 and idx[0] > idx[1]:
  496. idx = idx[::-1]
  497. segments[i] = segments[i][::-1, :]
  498. segments[i] = np.roll(segments[i], -idx[0], axis=0)
  499. segments[i] = np.concatenate([segments[i], segments[i][:1]])
  500. # Deal with the first segment and the last one
  501. if i in {0, len(idx_list) - 1}:
  502. s.append(segments[i])
  503. else:
  504. idx = [0, idx[1] - idx[0]]
  505. s.append(segments[i][idx[0] : idx[1] + 1])
  506. else:
  507. for i in range(len(idx_list) - 1, -1, -1):
  508. if i not in {0, len(idx_list) - 1}:
  509. idx = idx_list[i]
  510. nidx = abs(idx[1] - idx[0])
  511. s.append(segments[i][nidx:])
  512. return s
  513. def yolo_bbox2segment(im_dir, save_dir=None, sam_model="sam_b.pt", device=None):
  514. """
  515. Converts existing object detection dataset (bounding boxes) to segmentation dataset or oriented bounding box (OBB)
  516. in YOLO format. Generates segmentation data using SAM auto-annotator as needed.
  517. Args:
  518. im_dir (str | Path): Path to image directory to convert.
  519. save_dir (str | Path): Path to save the generated labels, labels will be saved
  520. into `labels-segment` in the same directory level of `im_dir` if save_dir is None. Default: None.
  521. sam_model (str): Segmentation model to use for intermediate segmentation data; optional.
  522. device (int | str): The specific device to run SAM models. Default: None.
  523. Notes:
  524. The input directory structure assumed for dataset:
  525. - im_dir
  526. ├─ 001.jpg
  527. ├─ ...
  528. └─ NNN.jpg
  529. - labels
  530. ├─ 001.txt
  531. ├─ ...
  532. └─ NNN.txt
  533. """
  534. from ultralytics import SAM
  535. from ultralytics.data import YOLODataset
  536. from ultralytics.utils import LOGGER
  537. from ultralytics.utils.ops import xywh2xyxy
  538. # NOTE: add placeholder to pass class index check
  539. dataset = YOLODataset(im_dir, data=dict(names=list(range(1000))))
  540. if len(dataset.labels[0]["segments"]) > 0: # if it's segment data
  541. LOGGER.info("Segmentation labels detected, no need to generate new ones!")
  542. return
  543. LOGGER.info("Detection labels detected, generating segment labels by SAM model!")
  544. sam_model = SAM(sam_model)
  545. for label in TQDM(dataset.labels, total=len(dataset.labels), desc="Generating segment labels"):
  546. h, w = label["shape"]
  547. boxes = label["bboxes"]
  548. if len(boxes) == 0: # skip empty labels
  549. continue
  550. boxes[:, [0, 2]] *= w
  551. boxes[:, [1, 3]] *= h
  552. im = cv2.imread(label["im_file"])
  553. sam_results = sam_model(im, bboxes=xywh2xyxy(boxes), verbose=False, save=False, device=device)
  554. label["segments"] = sam_results[0].masks.xyn
  555. save_dir = Path(save_dir) if save_dir else Path(im_dir).parent / "labels-segment"
  556. save_dir.mkdir(parents=True, exist_ok=True)
  557. for label in dataset.labels:
  558. texts = []
  559. lb_name = Path(label["im_file"]).with_suffix(".txt").name
  560. txt_file = save_dir / lb_name
  561. cls = label["cls"]
  562. for i, s in enumerate(label["segments"]):
  563. if len(s) == 0:
  564. continue
  565. line = (int(cls[i]), *s.reshape(-1))
  566. texts.append(("%g " * len(line)).rstrip() % line)
  567. with open(txt_file, "a") as f:
  568. f.writelines(text + "\n" for text in texts)
  569. LOGGER.info(f"Generated segment labels saved in {save_dir}")
  570. def create_synthetic_coco_dataset():
  571. """
  572. Creates a synthetic COCO dataset with random images based on filenames from label lists.
  573. This function downloads COCO labels, reads image filenames from label list files,
  574. creates synthetic images for train2017 and val2017 subsets, and organizes
  575. them in the COCO dataset structure. It uses multithreading to generate images efficiently.
  576. Examples:
  577. >>> from ultralytics.data.converter import create_synthetic_coco_dataset
  578. >>> create_synthetic_coco_dataset()
  579. Notes:
  580. - Requires internet connection to download label files.
  581. - Generates random RGB images of varying sizes (480x480 to 640x640 pixels).
  582. - Existing test2017 directory is removed as it's not needed.
  583. - Reads image filenames from train2017.txt and val2017.txt files.
  584. """
  585. def create_synthetic_image(image_file):
  586. """Generates synthetic images with random sizes and colors for dataset augmentation or testing purposes."""
  587. if not image_file.exists():
  588. size = (random.randint(480, 640), random.randint(480, 640))
  589. Image.new(
  590. "RGB",
  591. size=size,
  592. color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),
  593. ).save(image_file)
  594. # Download labels
  595. dir = DATASETS_DIR / "coco"
  596. url = "https://github.com/ultralytics/assets/releases/download/v0.0.0/"
  597. label_zip = "coco2017labels-segments.zip"
  598. download([url + label_zip], dir=dir.parent)
  599. # Create synthetic images
  600. shutil.rmtree(dir / "labels" / "test2017", ignore_errors=True) # Remove test2017 directory as not needed
  601. with ThreadPoolExecutor(max_workers=NUM_THREADS) as executor:
  602. for subset in ["train2017", "val2017"]:
  603. subset_dir = dir / "images" / subset
  604. subset_dir.mkdir(parents=True, exist_ok=True)
  605. # Read image filenames from label list file
  606. label_list_file = dir / f"{subset}.txt"
  607. if label_list_file.exists():
  608. with open(label_list_file) as f:
  609. image_files = [dir / line.strip() for line in f]
  610. # Submit all tasks
  611. futures = [executor.submit(create_synthetic_image, image_file) for image_file in image_files]
  612. for _ in TQDM(as_completed(futures), total=len(futures), desc=f"Generating images for {subset}"):
  613. pass # The actual work is done in the background
  614. else:
  615. print(f"Warning: Labels file {label_list_file} does not exist. Skipping image creation for {subset}.")
  616. print("Synthetic COCO dataset created successfully.")