dataset.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import contextlib
  3. import json
  4. from collections import defaultdict
  5. from itertools import repeat
  6. from multiprocessing.pool import ThreadPool
  7. from pathlib import Path
  8. import cv2
  9. import numpy as np
  10. import torch
  11. from PIL import Image
  12. from torch.utils.data import ConcatDataset
  13. from ultralytics.utils import LOCAL_RANK, NUM_THREADS, TQDM, colorstr
  14. from ultralytics.utils.ops import resample_segments
  15. from .augment import (
  16. Compose,
  17. Format,
  18. Instances,
  19. LetterBox,
  20. RandomLoadText,
  21. classify_augmentations,
  22. classify_transforms,
  23. v8_transforms,
  24. )
  25. from .base import BaseDataset
  26. from .utils import (
  27. HELP_URL,
  28. LOGGER,
  29. get_hash,
  30. img2label_paths,
  31. load_dataset_cache_file,
  32. save_dataset_cache_file,
  33. verify_image,
  34. verify_image_label,
  35. )
  36. from ultralytics.data.datagenerate import DataGenerator
  37. # Ultralytics dataset *.cache version, >= 1.0.0 for YOLOv8
  38. DATASET_CACHE_VERSION = "1.0.3"
  39. class YOLODataset(BaseDataset):
  40. """
  41. Dataset class for loading object detection and/or segmentation labels in YOLO format.
  42. Args:
  43. task (str): An explicit arg to point current task, Defaults to 'detect'.
  44. Returns:
  45. (torch.utils.data.Dataset): A PyTorch dataset object that can be used for training an object detection model.
  46. """
  47. def __init__(self, *args, task="detect", **kwargs):
  48. """Initializes the YOLODataset with optional configurations for segments and keypoints."""
  49. self.use_segments = task == "segment"
  50. self.use_keypoints = task == "pose"
  51. self.use_obb = task == "obb"
  52. assert not (self.use_segments and self.use_keypoints), "Can not use both segments and keypoints."
  53. super().__init__(*args, **kwargs)
  54. def cache_labels(self, path=Path("./labels.cache")):
  55. """
  56. Cache dataset labels, check images and read shapes.
  57. Args:
  58. path (Path): Path where to save the cache file. Default is Path('./labels.cache').
  59. Returns:
  60. (dict): labels.
  61. """
  62. x = {"labels": []}
  63. nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
  64. desc = f"{self.prefix}Scanning {path.parent / path.stem}..."
  65. total = len(self.im_files)
  66. nkpt, ndim = self.data.get("kpt_shape", (0, 0))
  67. if self.use_keypoints and (nkpt <= 0 or ndim not in {2, 3}):
  68. raise ValueError(
  69. "'kpt_shape' in data.yaml missing or incorrect. Should be a list with [number of "
  70. "keypoints, number of dims (2 for x,y or 3 for x,y,visible)], i.e. 'kpt_shape: [17, 3]'"
  71. )
  72. with ThreadPool(NUM_THREADS) as pool:
  73. results = pool.imap(
  74. func=verify_image_label,
  75. iterable=zip(
  76. self.im_files,
  77. self.label_files,
  78. repeat(self.prefix),
  79. repeat(self.use_keypoints),
  80. repeat(len(self.data["names"])),
  81. repeat(nkpt),
  82. repeat(ndim),
  83. ),
  84. )
  85. pbar = TQDM(results, desc=desc, total=total)
  86. for im_file, lb, shape, segments, keypoint, nm_f, nf_f, ne_f, nc_f, msg in pbar:
  87. nm += nm_f
  88. nf += nf_f
  89. ne += ne_f
  90. nc += nc_f
  91. if im_file:
  92. x["labels"].append(
  93. {
  94. "im_file": im_file,
  95. "shape": shape,
  96. "cls": lb[:, 0:1], # n, 1
  97. "bboxes": lb[:, 1:], # n, 4
  98. "segments": segments,
  99. "keypoints": keypoint,
  100. "normalized": True,
  101. "bbox_format": "xywh",
  102. }
  103. )
  104. if msg:
  105. msgs.append(msg)
  106. pbar.desc = f"{desc} {nf} images, {nm + ne} backgrounds, {nc} corrupt"
  107. pbar.close()
  108. if msgs:
  109. LOGGER.info("\n".join(msgs))
  110. if nf == 0:
  111. LOGGER.warning(f"{self.prefix}WARNING ⚠️ No labels found in {path}. {HELP_URL}")
  112. x["hash"] = get_hash(self.label_files + self.im_files)
  113. x["results"] = nf, nm, ne, nc, len(self.im_files)
  114. x["msgs"] = msgs # warnings
  115. save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION)
  116. return x
  117. def get_labels(self):
  118. """Returns dictionary of labels for YOLO training."""
  119. self.label_files = img2label_paths(self.im_files)
  120. cache_path = Path(self.label_files[0]).parent.with_suffix(".cache")
  121. try:
  122. cache, exists = load_dataset_cache_file(cache_path), True # attempt to load a *.cache file
  123. assert cache["version"] == DATASET_CACHE_VERSION # matches current version
  124. assert cache["hash"] == get_hash(self.label_files + self.im_files) # identical hash
  125. except (FileNotFoundError, AssertionError, AttributeError):
  126. cache, exists = self.cache_labels(cache_path), False # run cache ops
  127. # Display cache
  128. nf, nm, ne, nc, n = cache.pop("results") # found, missing, empty, corrupt, total
  129. if exists and LOCAL_RANK in {-1, 0}:
  130. d = f"Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt"
  131. TQDM(None, desc=self.prefix + d, total=n, initial=n) # display results
  132. if cache["msgs"]:
  133. LOGGER.info("\n".join(cache["msgs"])) # display warnings
  134. # Read cache
  135. [cache.pop(k) for k in ("hash", "version", "msgs")] # remove items
  136. labels = cache["labels"]
  137. if not labels:
  138. LOGGER.warning(f"WARNING ⚠️ No images found in {cache_path}, training may not work correctly. {HELP_URL}")
  139. self.im_files = [lb["im_file"] for lb in labels] # update im_files
  140. # Check if the dataset is all boxes or all segments
  141. lengths = ((len(lb["cls"]), len(lb["bboxes"]), len(lb["segments"])) for lb in labels)
  142. len_cls, len_boxes, len_segments = (sum(x) for x in zip(*lengths))
  143. if len_segments and len_boxes != len_segments:
  144. LOGGER.warning(
  145. f"WARNING ⚠️ Box and segment counts should be equal, but got len(segments) = {len_segments}, "
  146. f"len(boxes) = {len_boxes}. To resolve this only boxes will be used and all segments will be removed. "
  147. "To avoid this please supply either a detect or segment dataset, not a detect-segment mixed dataset."
  148. )
  149. for lb in labels:
  150. lb["segments"] = []
  151. if len_cls == 0:
  152. LOGGER.warning(f"WARNING ⚠️ No labels found in {cache_path}, training may not work correctly. {HELP_URL}")
  153. return labels
  154. def get_img_files_and_labels(self):
  155. """平台训练时,获取图像和labels"""
  156. if self.is_train_on_platform:
  157. last_name = self.data['names']
  158. wrong_file = self.platform_data_args["wrong_file"]
  159. data_type = self.platform_data_args["data_type"]
  160. needed_image_results_dict = self.platform_data_args['needed_image_results_dict']
  161. needed_rois_dict = self.platform_data_args['needed_rois_dict']
  162. class_aug_times = self.platform_data_args['class_aug_times']
  163. label_aug_level = self.platform_data_args['label_aug_level']
  164. labels, im_files, shapes, segments, crop_boxes, crop_contours = DataGenerator(
  165. self.token,
  166. self.train_or_val_data,
  167. wrong_file,
  168. needed_image_results_dict,
  169. needed_rois_dict,
  170. label_aug_level,
  171. class_aug_times,
  172. last_name,
  173. data_type,
  174. self.extra_contours_args).generate()
  175. all_labels = []
  176. # 暂时不支持输出keypoints,后续可以修改DataGenerator,获取所需要的keypoints
  177. for idx in range(len(im_files)):
  178. all_labels.append(
  179. {
  180. "im_file": im_files[idx],
  181. "shape": shapes[idx],
  182. "cls": labels[idx][:, 0:1], # n, 1
  183. "bboxes": labels[idx][:, 1:], # n, 4
  184. "segments": segments[idx],
  185. "keypoints": None,
  186. "normalized": True,
  187. "bbox_format": "xywh",
  188. }
  189. )
  190. return im_files, all_labels, crop_boxes, crop_contours
  191. def build_transforms(self, hyp=None):
  192. """Builds and appends transforms to the list."""
  193. if self.augment:
  194. hyp.mosaic = hyp.mosaic if self.augment and not self.rect else 0.0
  195. hyp.mixup = hyp.mixup if self.augment and not self.rect else 0.0
  196. transforms = v8_transforms(self, self.imgsz, hyp)
  197. else:
  198. transforms = Compose([LetterBox(new_shape=(self.imgsz, self.imgsz), scaleup=False)])
  199. transforms.append(
  200. Format(
  201. bbox_format="xywh",
  202. normalize=True,
  203. return_mask=self.use_segments,
  204. return_keypoint=self.use_keypoints,
  205. return_obb=self.use_obb,
  206. batch_idx=True,
  207. mask_ratio=hyp.mask_ratio,
  208. mask_overlap=hyp.overlap_mask,
  209. bgr=hyp.bgr if self.augment else 0.0, # only affect training.
  210. )
  211. )
  212. return transforms
  213. def close_mosaic(self, hyp):
  214. """Sets mosaic, copy_paste and mixup options to 0.0 and builds transformations."""
  215. hyp.mosaic = 0.0 # set mosaic ratio=0.0
  216. hyp.copy_paste = 0.0 # keep the same behavior as previous v8 close-mosaic
  217. hyp.mixup = 0.0 # keep the same behavior as previous v8 close-mosaic
  218. self.transforms = self.build_transforms(hyp)
  219. def update_labels_info(self, label):
  220. """
  221. Custom your label format here.
  222. Note:
  223. cls is not with bboxes now, classification and semantic segmentation need an independent cls label
  224. Can also support classification and semantic segmentation by adding or removing dict keys there.
  225. """
  226. bboxes = label.pop("bboxes")
  227. segments = label.pop("segments", [])
  228. keypoints = label.pop("keypoints", None)
  229. bbox_format = label.pop("bbox_format")
  230. normalized = label.pop("normalized")
  231. # NOTE: do NOT resample oriented boxes
  232. segment_resamples = 100 if self.use_obb else 1000
  233. if len(segments) > 0:
  234. # list[np.array(1000, 2)] * num_samples
  235. # (N, 1000, 2)
  236. segments = np.stack(resample_segments(segments, n=segment_resamples), axis=0)
  237. else:
  238. segments = np.zeros((0, segment_resamples, 2), dtype=np.float32)
  239. label["instances"] = Instances(bboxes, segments, keypoints, bbox_format=bbox_format, normalized=normalized)
  240. return label
  241. @staticmethod
  242. def collate_fn(batch):
  243. """Collates data samples into batches."""
  244. new_batch = {}
  245. keys = batch[0].keys()
  246. values = list(zip(*[list(b.values()) for b in batch]))
  247. for i, k in enumerate(keys):
  248. value = values[i]
  249. if k == "img":
  250. value = torch.stack(value, 0)
  251. if k in {"masks", "keypoints", "bboxes", "cls", "segments", "obb"}:
  252. value = torch.cat(value, 0)
  253. new_batch[k] = value
  254. new_batch["batch_idx"] = list(new_batch["batch_idx"])
  255. for i in range(len(new_batch["batch_idx"])):
  256. new_batch["batch_idx"][i] += i # add target image index for build_targets()
  257. new_batch["batch_idx"] = torch.cat(new_batch["batch_idx"], 0)
  258. return new_batch
  259. class YOLOMultiModalDataset(YOLODataset):
  260. """
  261. Dataset class for loading object detection and/or segmentation labels in YOLO format.
  262. Args:
  263. data (dict, optional): A dataset YAML dictionary. Defaults to None.
  264. task (str): An explicit arg to point current task, Defaults to 'detect'.
  265. Returns:
  266. (torch.utils.data.Dataset): A PyTorch dataset object that can be used for training an object detection model.
  267. """
  268. def __init__(self, *args, data=None, task="detect", **kwargs):
  269. """Initializes a dataset object for object detection tasks with optional specifications."""
  270. super().__init__(*args, data=data, task=task, **kwargs)
  271. def update_labels_info(self, label):
  272. """Add texts information for multi modal model training."""
  273. labels = super().update_labels_info(label)
  274. # NOTE: some categories are concatenated with its synonyms by `/`.
  275. labels["texts"] = [v.split("/") for _, v in self.data["names"].items()]
  276. return labels
  277. def build_transforms(self, hyp=None):
  278. """Enhances data transformations with optional text augmentation for multi-modal training."""
  279. transforms = super().build_transforms(hyp)
  280. if self.augment:
  281. # NOTE: hard-coded the args for now.
  282. transforms.insert(-1, RandomLoadText(max_samples=min(self.data["nc"], 80), padding=True))
  283. return transforms
  284. class GroundingDataset(YOLODataset):
  285. def __init__(self, *args, task="detect", json_file, **kwargs):
  286. """Initializes a GroundingDataset for object detection, loading annotations from a specified JSON file."""
  287. assert task == "detect", "`GroundingDataset` only support `detect` task for now!"
  288. self.json_file = json_file
  289. super().__init__(*args, task=task, data={}, **kwargs)
  290. def get_img_files(self, img_path):
  291. """The image files would be read in `get_labels` function, return empty list here."""
  292. return []
  293. def get_labels(self):
  294. """Loads annotations from a JSON file, filters, and normalizes bounding boxes for each image."""
  295. labels = []
  296. LOGGER.info("Loading annotation file...")
  297. with open(self.json_file, "r") as f:
  298. annotations = json.load(f)
  299. images = {f'{x["id"]:d}': x for x in annotations["images"]}
  300. imgToAnns = defaultdict(list)
  301. for ann in annotations["annotations"]:
  302. imgToAnns[ann["image_id"]].append(ann)
  303. for img_id, anns in TQDM(imgToAnns.items(), desc=f"Reading annotations {self.json_file}"):
  304. img = images[f"{img_id:d}"]
  305. h, w, f = img["height"], img["width"], img["file_name"]
  306. im_file = Path(self.img_path) / f
  307. if not im_file.exists():
  308. continue
  309. self.im_files.append(str(im_file))
  310. bboxes = []
  311. cat2id = {}
  312. texts = []
  313. for ann in anns:
  314. if ann["iscrowd"]:
  315. continue
  316. box = np.array(ann["bbox"], dtype=np.float32)
  317. box[:2] += box[2:] / 2
  318. box[[0, 2]] /= float(w)
  319. box[[1, 3]] /= float(h)
  320. if box[2] <= 0 or box[3] <= 0:
  321. continue
  322. cat_name = " ".join([img["caption"][t[0] : t[1]] for t in ann["tokens_positive"]])
  323. if cat_name not in cat2id:
  324. cat2id[cat_name] = len(cat2id)
  325. texts.append([cat_name])
  326. cls = cat2id[cat_name] # class
  327. box = [cls] + box.tolist()
  328. if box not in bboxes:
  329. bboxes.append(box)
  330. lb = np.array(bboxes, dtype=np.float32) if len(bboxes) else np.zeros((0, 5), dtype=np.float32)
  331. labels.append(
  332. {
  333. "im_file": im_file,
  334. "shape": (h, w),
  335. "cls": lb[:, 0:1], # n, 1
  336. "bboxes": lb[:, 1:], # n, 4
  337. "normalized": True,
  338. "bbox_format": "xywh",
  339. "texts": texts,
  340. }
  341. )
  342. return labels
  343. def build_transforms(self, hyp=None):
  344. """Configures augmentations for training with optional text loading; `hyp` adjusts augmentation intensity."""
  345. transforms = super().build_transforms(hyp)
  346. if self.augment:
  347. # NOTE: hard-coded the args for now.
  348. transforms.insert(-1, RandomLoadText(max_samples=80, padding=True))
  349. return transforms
  350. class YOLOConcatDataset(ConcatDataset):
  351. """
  352. Dataset as a concatenation of multiple datasets.
  353. This class is useful to assemble different existing datasets.
  354. """
  355. @staticmethod
  356. def collate_fn(batch):
  357. """Collates data samples into batches."""
  358. return YOLODataset.collate_fn(batch)
  359. # TODO: support semantic segmentation
  360. class SemanticDataset(BaseDataset):
  361. """
  362. Semantic Segmentation Dataset.
  363. This class is responsible for handling datasets used for semantic segmentation tasks. It inherits functionalities
  364. from the BaseDataset class.
  365. Note:
  366. This class is currently a placeholder and needs to be populated with methods and attributes for supporting
  367. semantic segmentation tasks.
  368. """
  369. def __init__(self):
  370. """Initialize a SemanticDataset object."""
  371. super().__init__()
  372. class ClassificationDataset:
  373. """
  374. Extends torchvision ImageFolder to support YOLO classification tasks, offering functionalities like image
  375. augmentation, caching, and verification. It's designed to efficiently handle large datasets for training deep
  376. learning models, with optional image transformations and caching mechanisms to speed up training.
  377. This class allows for augmentations using both torchvision and Albumentations libraries, and supports caching images
  378. in RAM or on disk to reduce IO overhead during training. Additionally, it implements a robust verification process
  379. to ensure data integrity and consistency.
  380. Attributes:
  381. cache_ram (bool): Indicates if caching in RAM is enabled.
  382. cache_disk (bool): Indicates if caching on disk is enabled.
  383. samples (list): A list of tuples, each containing the path to an image, its class index, path to its .npy cache
  384. file (if caching on disk), and optionally the loaded image array (if caching in RAM).
  385. torch_transforms (callable): PyTorch transforms to be applied to the images.
  386. """
  387. def __init__(self, root, args, augment=False, prefix=""):
  388. """
  389. Initialize YOLO object with root, image size, augmentations, and cache settings.
  390. Args:
  391. root (str): Path to the dataset directory where images are stored in a class-specific folder structure.
  392. args (Namespace): Configuration containing dataset-related settings such as image size, augmentation
  393. parameters, and cache settings. It includes attributes like `imgsz` (image size), `fraction` (fraction
  394. of data to use), `scale`, `fliplr`, `flipud`, `cache` (disk or RAM caching for faster training),
  395. `auto_augment`, `hsv_h`, `hsv_s`, `hsv_v`, and `crop_fraction`.
  396. augment (bool, optional): Whether to apply augmentations to the dataset. Default is False.
  397. prefix (str, optional): Prefix for logging and cache filenames, aiding in dataset identification and
  398. debugging. Default is an empty string.
  399. """
  400. import torchvision # scope for faster 'import ultralytics'
  401. # Base class assigned as attribute rather than used as base class to allow for scoping slow torchvision import
  402. self.base = torchvision.datasets.ImageFolder(root=root)
  403. self.samples = self.base.samples
  404. self.root = self.base.root
  405. # Initialize attributes
  406. if augment and args.fraction < 1.0: # reduce training fraction
  407. self.samples = self.samples[: round(len(self.samples) * args.fraction)]
  408. self.prefix = colorstr(f"{prefix}: ") if prefix else ""
  409. self.cache_ram = args.cache is True or str(args.cache).lower() == "ram" # cache images into RAM
  410. self.cache_disk = str(args.cache).lower() == "disk" # cache images on hard drive as uncompressed *.npy files
  411. self.samples = self.verify_images() # filter out bad images
  412. self.samples = [list(x) + [Path(x[0]).with_suffix(".npy"), None] for x in self.samples] # file, index, npy, im
  413. scale = (1.0 - args.scale, 1.0) # (0.08, 1.0)
  414. self.torch_transforms = (
  415. classify_augmentations(
  416. size=args.imgsz,
  417. scale=scale,
  418. hflip=args.fliplr,
  419. vflip=args.flipud,
  420. erasing=args.erasing,
  421. auto_augment=args.auto_augment,
  422. hsv_h=args.hsv_h,
  423. hsv_s=args.hsv_s,
  424. hsv_v=args.hsv_v,
  425. )
  426. if augment
  427. else classify_transforms(size=args.imgsz, crop_fraction=args.crop_fraction)
  428. )
  429. def __getitem__(self, i):
  430. """Returns subset of data and targets corresponding to given indices."""
  431. f, j, fn, im = self.samples[i] # filename, index, filename.with_suffix('.npy'), image
  432. if self.cache_ram:
  433. if im is None: # Warning: two separate if statements required here, do not combine this with previous line
  434. im = self.samples[i][3] = cv2.imread(f)
  435. elif self.cache_disk:
  436. if not fn.exists(): # load npy
  437. np.save(fn.as_posix(), cv2.imread(f), allow_pickle=False)
  438. im = np.load(fn)
  439. else: # read image
  440. im = cv2.imread(f) # BGR
  441. # Convert NumPy array to PIL image
  442. im = Image.fromarray(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
  443. sample = self.torch_transforms(im)
  444. return {"img": sample, "cls": j}
  445. def __len__(self) -> int:
  446. """Return the total number of samples in the dataset."""
  447. return len(self.samples)
  448. def verify_images(self):
  449. """Verify all images in dataset."""
  450. desc = f"{self.prefix}Scanning {self.root}..."
  451. path = Path(self.root).with_suffix(".cache") # *.cache file path
  452. with contextlib.suppress(FileNotFoundError, AssertionError, AttributeError):
  453. cache = load_dataset_cache_file(path) # attempt to load a *.cache file
  454. assert cache["version"] == DATASET_CACHE_VERSION # matches current version
  455. assert cache["hash"] == get_hash([x[0] for x in self.samples]) # identical hash
  456. nf, nc, n, samples = cache.pop("results") # found, missing, empty, corrupt, total
  457. if LOCAL_RANK in {-1, 0}:
  458. d = f"{desc} {nf} images, {nc} corrupt"
  459. TQDM(None, desc=d, total=n, initial=n)
  460. if cache["msgs"]:
  461. LOGGER.info("\n".join(cache["msgs"])) # display warnings
  462. return samples
  463. # Run scan if *.cache retrieval failed
  464. nf, nc, msgs, samples, x = 0, 0, [], [], {}
  465. with ThreadPool(NUM_THREADS) as pool:
  466. results = pool.imap(func=verify_image, iterable=zip(self.samples, repeat(self.prefix)))
  467. pbar = TQDM(results, desc=desc, total=len(self.samples))
  468. for sample, nf_f, nc_f, msg in pbar:
  469. if nf_f:
  470. samples.append(sample)
  471. if msg:
  472. msgs.append(msg)
  473. nf += nf_f
  474. nc += nc_f
  475. pbar.desc = f"{desc} {nf} images, {nc} corrupt"
  476. pbar.close()
  477. if msgs:
  478. LOGGER.info("\n".join(msgs))
  479. x["hash"] = get_hash([x[0] for x in self.samples])
  480. x["results"] = nf, nc, len(samples), samples
  481. x["msgs"] = msgs # warnings
  482. save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION)
  483. return samples