dataset.py 23 KB

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