_dataset_wrapper.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. # type: ignore
  2. from __future__ import annotations
  3. import collections.abc
  4. import contextlib
  5. from collections import defaultdict
  6. import torch
  7. from torchvision import datasets, tv_tensors
  8. from torchvision.transforms.v2 import functional as F
  9. __all__ = ["wrap_dataset_for_transforms_v2"]
  10. def wrap_dataset_for_transforms_v2(dataset, target_keys=None):
  11. """[BETA] Wrap a ``torchvision.dataset`` for usage with :mod:`torchvision.transforms.v2`.
  12. .. v2betastatus:: wrap_dataset_for_transforms_v2 function
  13. Example:
  14. >>> dataset = torchvision.datasets.CocoDetection(...)
  15. >>> dataset = wrap_dataset_for_transforms_v2(dataset)
  16. .. note::
  17. For now, only the most popular datasets are supported. Furthermore, the wrapper only supports dataset
  18. configurations that are fully supported by ``torchvision.transforms.v2``. If you encounter an error prompting you
  19. to raise an issue to ``torchvision`` for a dataset or configuration that you need, please do so.
  20. The dataset samples are wrapped according to the description below.
  21. Special cases:
  22. * :class:`~torchvision.datasets.CocoDetection`: Instead of returning the target as list of dicts, the wrapper
  23. returns a dict of lists. In addition, the key-value-pairs ``"boxes"`` (in ``XYXY`` coordinate format),
  24. ``"masks"`` and ``"labels"`` are added and wrap the data in the corresponding ``torchvision.tv_tensors``.
  25. The original keys are preserved. If ``target_keys`` is omitted, returns only the values for the
  26. ``"image_id"``, ``"boxes"``, and ``"labels"``.
  27. * :class:`~torchvision.datasets.VOCDetection`: The key-value-pairs ``"boxes"`` and ``"labels"`` are added to
  28. the target and wrap the data in the corresponding ``torchvision.tv_tensors``. The original keys are
  29. preserved. If ``target_keys`` is omitted, returns only the values for the ``"boxes"`` and ``"labels"``.
  30. * :class:`~torchvision.datasets.CelebA`: The target for ``target_type="bbox"`` is converted to the ``XYXY``
  31. coordinate format and wrapped into a :class:`~torchvision.tv_tensors.BoundingBoxes` tv_tensor.
  32. * :class:`~torchvision.datasets.Kitti`: Instead returning the target as list of dicts, the wrapper returns a
  33. dict of lists. In addition, the key-value-pairs ``"boxes"`` and ``"labels"`` are added and wrap the data
  34. in the corresponding ``torchvision.tv_tensors``. The original keys are preserved. If ``target_keys`` is
  35. omitted, returns only the values for the ``"boxes"`` and ``"labels"``.
  36. * :class:`~torchvision.datasets.OxfordIIITPet`: The target for ``target_type="segmentation"`` is wrapped into a
  37. :class:`~torchvision.tv_tensors.Mask` tv_tensor.
  38. * :class:`~torchvision.datasets.Cityscapes`: The target for ``target_type="semantic"`` is wrapped into a
  39. :class:`~torchvision.tv_tensors.Mask` tv_tensor. The target for ``target_type="instance"`` is *replaced* by
  40. a dictionary with the key-value-pairs ``"masks"`` (as :class:`~torchvision.tv_tensors.Mask` tv_tensor) and
  41. ``"labels"``.
  42. * :class:`~torchvision.datasets.WIDERFace`: The value for key ``"bbox"`` in the target is converted to ``XYXY``
  43. coordinate format and wrapped into a :class:`~torchvision.tv_tensors.BoundingBoxes` tv_tensor.
  44. Image classification datasets
  45. This wrapper is a no-op for image classification datasets, since they were already fully supported by
  46. :mod:`torchvision.transforms` and thus no change is needed for :mod:`torchvision.transforms.v2`.
  47. Segmentation datasets
  48. Segmentation datasets, e.g. :class:`~torchvision.datasets.VOCSegmentation`, return a two-tuple of
  49. :class:`PIL.Image.Image`'s. This wrapper leaves the image as is (first item), while wrapping the
  50. segmentation mask into a :class:`~torchvision.tv_tensors.Mask` (second item).
  51. Video classification datasets
  52. Video classification datasets, e.g. :class:`~torchvision.datasets.Kinetics`, return a three-tuple containing a
  53. :class:`torch.Tensor` for the video and audio and a :class:`int` as label. This wrapper wraps the video into a
  54. :class:`~torchvision.tv_tensors.Video` while leaving the other items as is.
  55. .. note::
  56. Only datasets constructed with ``output_format="TCHW"`` are supported, since the alternative
  57. ``output_format="THWC"`` is not supported by :mod:`torchvision.transforms.v2`.
  58. Args:
  59. dataset: the dataset instance to wrap for compatibility with transforms v2.
  60. target_keys: Target keys to return in case the target is a dictionary. If ``None`` (default), selected keys are
  61. specific to the dataset. If ``"all"``, returns the full target. Can also be a collection of strings for
  62. fine grained access. Currently only supported for :class:`~torchvision.datasets.CocoDetection`,
  63. :class:`~torchvision.datasets.VOCDetection`, :class:`~torchvision.datasets.Kitti`, and
  64. :class:`~torchvision.datasets.WIDERFace`. See above for details.
  65. """
  66. if not (
  67. target_keys is None
  68. or target_keys == "all"
  69. or (isinstance(target_keys, collections.abc.Collection) and all(isinstance(key, str) for key in target_keys))
  70. ):
  71. raise ValueError(
  72. f"`target_keys` can be None, 'all', or a collection of strings denoting the keys to be returned, "
  73. f"but got {target_keys}"
  74. )
  75. # Imagine we have isinstance(dataset, datasets.ImageNet). This will create a new class with the name
  76. # "WrappedImageNet" at runtime that doubly inherits from VisionDatasetTVTensorWrapper (see below) as well as the
  77. # original ImageNet class. This allows the user to do regular isinstance(wrapped_dataset, datasets.ImageNet) checks,
  78. # while we can still inject everything that we need.
  79. wrapped_dataset_cls = type(f"Wrapped{type(dataset).__name__}", (VisionDatasetTVTensorWrapper, type(dataset)), {})
  80. # Since VisionDatasetTVTensorWrapper comes before ImageNet in the MRO, calling the class hits
  81. # VisionDatasetTVTensorWrapper.__init__ first. Since we are never doing super().__init__(...), the constructor of
  82. # ImageNet is never hit. That is by design, since we don't want to create the dataset instance again, but rather
  83. # have the existing instance as attribute on the new object.
  84. return wrapped_dataset_cls(dataset, target_keys)
  85. class WrapperFactories(dict):
  86. def register(self, dataset_cls):
  87. def decorator(wrapper_factory):
  88. self[dataset_cls] = wrapper_factory
  89. return wrapper_factory
  90. return decorator
  91. # We need this two-stage design, i.e. a wrapper factory producing the actual wrapper, since some wrappers depend on the
  92. # dataset instance rather than just the class, since they require the user defined instance attributes. Thus, we can
  93. # provide a wrapping from the dataset class to the factory here, but can only instantiate the wrapper at runtime when
  94. # we have access to the dataset instance.
  95. WRAPPER_FACTORIES = WrapperFactories()
  96. class VisionDatasetTVTensorWrapper:
  97. def __init__(self, dataset, target_keys):
  98. dataset_cls = type(dataset)
  99. if not isinstance(dataset, datasets.VisionDataset):
  100. raise TypeError(
  101. f"This wrapper is meant for subclasses of `torchvision.datasets.VisionDataset`, "
  102. f"but got a '{dataset_cls.__name__}' instead.\n"
  103. f"For an example of how to perform the wrapping for custom datasets, see\n\n"
  104. "https://pytorch.org/vision/main/auto_examples/plot_tv_tensors.html#do-i-have-to-wrap-the-output-of-the-datasets-myself"
  105. )
  106. for cls in dataset_cls.mro():
  107. if cls in WRAPPER_FACTORIES:
  108. wrapper_factory = WRAPPER_FACTORIES[cls]
  109. if target_keys is not None and cls not in {
  110. datasets.CocoDetection,
  111. datasets.VOCDetection,
  112. datasets.Kitti,
  113. datasets.WIDERFace,
  114. }:
  115. raise ValueError(
  116. f"`target_keys` is currently only supported for `CocoDetection`, `VOCDetection`, `Kitti`, "
  117. f"and `WIDERFace`, but got {cls.__name__}."
  118. )
  119. break
  120. elif cls is datasets.VisionDataset:
  121. # TODO: If we have documentation on how to do that, put a link in the error message.
  122. msg = f"No wrapper exists for dataset class {dataset_cls.__name__}. Please wrap the output yourself."
  123. if dataset_cls in datasets.__dict__.values():
  124. msg = (
  125. f"{msg} If an automated wrapper for this dataset would be useful for you, "
  126. f"please open an issue at https://github.com/pytorch/vision/issues."
  127. )
  128. raise TypeError(msg)
  129. self._dataset = dataset
  130. self._target_keys = target_keys
  131. self._wrapper = wrapper_factory(dataset, target_keys)
  132. # We need to disable the transforms on the dataset here to be able to inject the wrapping before we apply them.
  133. # Although internally, `datasets.VisionDataset` merges `transform` and `target_transform` into the joint
  134. # `transforms`
  135. # https://github.com/pytorch/vision/blob/135a0f9ea9841b6324b4fe8974e2543cbb95709a/torchvision/datasets/vision.py#L52-L54
  136. # some (if not most) datasets still use `transform` and `target_transform` individually. Thus, we need to
  137. # disable all three here to be able to extract the untransformed sample to wrap.
  138. self.transform, dataset.transform = dataset.transform, None
  139. self.target_transform, dataset.target_transform = dataset.target_transform, None
  140. self.transforms, dataset.transforms = dataset.transforms, None
  141. def __getattr__(self, item):
  142. with contextlib.suppress(AttributeError):
  143. return object.__getattribute__(self, item)
  144. return getattr(self._dataset, item)
  145. def __getitem__(self, idx):
  146. # This gets us the raw sample since we disabled the transforms for the underlying dataset in the constructor
  147. # of this class
  148. sample = self._dataset[idx]
  149. sample = self._wrapper(idx, sample)
  150. # Regardless of whether the user has supplied the transforms individually (`transform` and `target_transform`)
  151. # or joint (`transforms`), we can access the full functionality through `transforms`
  152. if self.transforms is not None:
  153. sample = self.transforms(*sample)
  154. return sample
  155. def __len__(self):
  156. return len(self._dataset)
  157. def __reduce__(self):
  158. return wrap_dataset_for_transforms_v2, (self._dataset, self._target_keys)
  159. def raise_not_supported(description):
  160. raise RuntimeError(
  161. f"{description} is currently not supported by this wrapper. "
  162. f"If this would be helpful for you, please open an issue at https://github.com/pytorch/vision/issues."
  163. )
  164. def identity(item):
  165. return item
  166. def identity_wrapper_factory(dataset, target_keys):
  167. def wrapper(idx, sample):
  168. return sample
  169. return wrapper
  170. def pil_image_to_mask(pil_image):
  171. return tv_tensors.Mask(pil_image)
  172. def parse_target_keys(target_keys, *, available, default):
  173. if target_keys is None:
  174. target_keys = default
  175. if target_keys == "all":
  176. target_keys = available
  177. else:
  178. target_keys = set(target_keys)
  179. extra = target_keys - available
  180. if extra:
  181. raise ValueError(f"Target keys {sorted(extra)} are not available")
  182. return target_keys
  183. def list_of_dicts_to_dict_of_lists(list_of_dicts):
  184. dict_of_lists = defaultdict(list)
  185. for dct in list_of_dicts:
  186. for key, value in dct.items():
  187. dict_of_lists[key].append(value)
  188. return dict(dict_of_lists)
  189. def wrap_target_by_type(target, *, target_types, type_wrappers):
  190. if not isinstance(target, (tuple, list)):
  191. target = [target]
  192. wrapped_target = tuple(
  193. type_wrappers.get(target_type, identity)(item) for target_type, item in zip(target_types, target)
  194. )
  195. if len(wrapped_target) == 1:
  196. wrapped_target = wrapped_target[0]
  197. return wrapped_target
  198. def classification_wrapper_factory(dataset, target_keys):
  199. return identity_wrapper_factory(dataset, target_keys)
  200. for dataset_cls in [
  201. datasets.Caltech256,
  202. datasets.CIFAR10,
  203. datasets.CIFAR100,
  204. datasets.ImageNet,
  205. datasets.MNIST,
  206. datasets.FashionMNIST,
  207. datasets.GTSRB,
  208. datasets.DatasetFolder,
  209. datasets.ImageFolder,
  210. ]:
  211. WRAPPER_FACTORIES.register(dataset_cls)(classification_wrapper_factory)
  212. def segmentation_wrapper_factory(dataset, target_keys):
  213. def wrapper(idx, sample):
  214. image, mask = sample
  215. return image, pil_image_to_mask(mask)
  216. return wrapper
  217. for dataset_cls in [
  218. datasets.VOCSegmentation,
  219. ]:
  220. WRAPPER_FACTORIES.register(dataset_cls)(segmentation_wrapper_factory)
  221. def video_classification_wrapper_factory(dataset, target_keys):
  222. if dataset.video_clips.output_format == "THWC":
  223. raise RuntimeError(
  224. f"{type(dataset).__name__} with `output_format='THWC'` is not supported by this wrapper, "
  225. f"since it is not compatible with the transformations. Please use `output_format='TCHW'` instead."
  226. )
  227. def wrapper(idx, sample):
  228. video, audio, label = sample
  229. video = tv_tensors.Video(video)
  230. return video, audio, label
  231. return wrapper
  232. for dataset_cls in [
  233. datasets.HMDB51,
  234. datasets.Kinetics,
  235. datasets.UCF101,
  236. ]:
  237. WRAPPER_FACTORIES.register(dataset_cls)(video_classification_wrapper_factory)
  238. @WRAPPER_FACTORIES.register(datasets.Caltech101)
  239. def caltech101_wrapper_factory(dataset, target_keys):
  240. if "annotation" in dataset.target_type:
  241. raise_not_supported("Caltech101 dataset with `target_type=['annotation', ...]`")
  242. return classification_wrapper_factory(dataset, target_keys)
  243. @WRAPPER_FACTORIES.register(datasets.CocoDetection)
  244. def coco_dectection_wrapper_factory(dataset, target_keys):
  245. target_keys = parse_target_keys(
  246. target_keys,
  247. available={
  248. # native
  249. "segmentation",
  250. "area",
  251. "iscrowd",
  252. "image_id",
  253. "bbox",
  254. "category_id",
  255. # added by the wrapper
  256. "boxes",
  257. "masks",
  258. "labels",
  259. },
  260. default={"image_id", "boxes", "labels"},
  261. )
  262. def segmentation_to_mask(segmentation, *, canvas_size):
  263. from pycocotools import mask
  264. segmentation = (
  265. mask.frPyObjects(segmentation, *canvas_size)
  266. if isinstance(segmentation, dict)
  267. else mask.merge(mask.frPyObjects(segmentation, *canvas_size))
  268. )
  269. return torch.from_numpy(mask.decode(segmentation))
  270. def wrapper(idx, sample):
  271. image_id = dataset.ids[idx]
  272. image, target = sample
  273. if not target:
  274. return image, dict(image_id=image_id)
  275. canvas_size = tuple(F.get_size(image))
  276. batched_target = list_of_dicts_to_dict_of_lists(target)
  277. target = {}
  278. if "image_id" in target_keys:
  279. target["image_id"] = image_id
  280. if "boxes" in target_keys:
  281. target["boxes"] = F.convert_bounding_box_format(
  282. tv_tensors.BoundingBoxes(
  283. batched_target["bbox"],
  284. format=tv_tensors.BoundingBoxFormat.XYWH,
  285. canvas_size=canvas_size,
  286. ),
  287. new_format=tv_tensors.BoundingBoxFormat.XYXY,
  288. )
  289. if "masks" in target_keys:
  290. target["masks"] = tv_tensors.Mask(
  291. torch.stack(
  292. [
  293. segmentation_to_mask(segmentation, canvas_size=canvas_size)
  294. for segmentation in batched_target["segmentation"]
  295. ]
  296. ),
  297. )
  298. if "labels" in target_keys:
  299. target["labels"] = torch.tensor(batched_target["category_id"])
  300. for target_key in target_keys - {"image_id", "boxes", "masks", "labels"}:
  301. target[target_key] = batched_target[target_key]
  302. return image, target
  303. return wrapper
  304. WRAPPER_FACTORIES.register(datasets.CocoCaptions)(identity_wrapper_factory)
  305. VOC_DETECTION_CATEGORIES = [
  306. "__background__",
  307. "aeroplane",
  308. "bicycle",
  309. "bird",
  310. "boat",
  311. "bottle",
  312. "bus",
  313. "car",
  314. "cat",
  315. "chair",
  316. "cow",
  317. "diningtable",
  318. "dog",
  319. "horse",
  320. "motorbike",
  321. "person",
  322. "pottedplant",
  323. "sheep",
  324. "sofa",
  325. "train",
  326. "tvmonitor",
  327. ]
  328. VOC_DETECTION_CATEGORY_TO_IDX = dict(zip(VOC_DETECTION_CATEGORIES, range(len(VOC_DETECTION_CATEGORIES))))
  329. @WRAPPER_FACTORIES.register(datasets.VOCDetection)
  330. def voc_detection_wrapper_factory(dataset, target_keys):
  331. target_keys = parse_target_keys(
  332. target_keys,
  333. available={
  334. # native
  335. "annotation",
  336. # added by the wrapper
  337. "boxes",
  338. "labels",
  339. },
  340. default={"boxes", "labels"},
  341. )
  342. def wrapper(idx, sample):
  343. image, target = sample
  344. batched_instances = list_of_dicts_to_dict_of_lists(target["annotation"]["object"])
  345. if "annotation" not in target_keys:
  346. target = {}
  347. if "boxes" in target_keys:
  348. target["boxes"] = tv_tensors.BoundingBoxes(
  349. [
  350. [int(bndbox[part]) for part in ("xmin", "ymin", "xmax", "ymax")]
  351. for bndbox in batched_instances["bndbox"]
  352. ],
  353. format=tv_tensors.BoundingBoxFormat.XYXY,
  354. canvas_size=(image.height, image.width),
  355. )
  356. if "labels" in target_keys:
  357. target["labels"] = torch.tensor(
  358. [VOC_DETECTION_CATEGORY_TO_IDX[category] for category in batched_instances["name"]]
  359. )
  360. return image, target
  361. return wrapper
  362. @WRAPPER_FACTORIES.register(datasets.SBDataset)
  363. def sbd_wrapper(dataset, target_keys):
  364. if dataset.mode == "boundaries":
  365. raise_not_supported("SBDataset with mode='boundaries'")
  366. return segmentation_wrapper_factory(dataset, target_keys)
  367. @WRAPPER_FACTORIES.register(datasets.CelebA)
  368. def celeba_wrapper_factory(dataset, target_keys):
  369. if any(target_type in dataset.target_type for target_type in ["attr", "landmarks"]):
  370. raise_not_supported("`CelebA` dataset with `target_type=['attr', 'landmarks', ...]`")
  371. def wrapper(idx, sample):
  372. image, target = sample
  373. target = wrap_target_by_type(
  374. target,
  375. target_types=dataset.target_type,
  376. type_wrappers={
  377. "bbox": lambda item: F.convert_bounding_box_format(
  378. tv_tensors.BoundingBoxes(
  379. item,
  380. format=tv_tensors.BoundingBoxFormat.XYWH,
  381. canvas_size=(image.height, image.width),
  382. ),
  383. new_format=tv_tensors.BoundingBoxFormat.XYXY,
  384. ),
  385. },
  386. )
  387. return image, target
  388. return wrapper
  389. KITTI_CATEGORIES = ["Car", "Van", "Truck", "Pedestrian", "Person_sitting", "Cyclist", "Tram", "Misc", "DontCare"]
  390. KITTI_CATEGORY_TO_IDX = dict(zip(KITTI_CATEGORIES, range(len(KITTI_CATEGORIES))))
  391. @WRAPPER_FACTORIES.register(datasets.Kitti)
  392. def kitti_wrapper_factory(dataset, target_keys):
  393. target_keys = parse_target_keys(
  394. target_keys,
  395. available={
  396. # native
  397. "type",
  398. "truncated",
  399. "occluded",
  400. "alpha",
  401. "bbox",
  402. "dimensions",
  403. "location",
  404. "rotation_y",
  405. # added by the wrapper
  406. "boxes",
  407. "labels",
  408. },
  409. default={"boxes", "labels"},
  410. )
  411. def wrapper(idx, sample):
  412. image, target = sample
  413. if target is None:
  414. return image, target
  415. batched_target = list_of_dicts_to_dict_of_lists(target)
  416. target = {}
  417. if "boxes" in target_keys:
  418. target["boxes"] = tv_tensors.BoundingBoxes(
  419. batched_target["bbox"],
  420. format=tv_tensors.BoundingBoxFormat.XYXY,
  421. canvas_size=(image.height, image.width),
  422. )
  423. if "labels" in target_keys:
  424. target["labels"] = torch.tensor([KITTI_CATEGORY_TO_IDX[category] for category in batched_target["type"]])
  425. for target_key in target_keys - {"boxes", "labels"}:
  426. target[target_key] = batched_target[target_key]
  427. return image, target
  428. return wrapper
  429. @WRAPPER_FACTORIES.register(datasets.OxfordIIITPet)
  430. def oxford_iiit_pet_wrapper_factor(dataset, target_keys):
  431. def wrapper(idx, sample):
  432. image, target = sample
  433. if target is not None:
  434. target = wrap_target_by_type(
  435. target,
  436. target_types=dataset._target_types,
  437. type_wrappers={
  438. "segmentation": pil_image_to_mask,
  439. },
  440. )
  441. return image, target
  442. return wrapper
  443. @WRAPPER_FACTORIES.register(datasets.Cityscapes)
  444. def cityscapes_wrapper_factory(dataset, target_keys):
  445. if any(target_type in dataset.target_type for target_type in ["polygon", "color"]):
  446. raise_not_supported("`Cityscapes` dataset with `target_type=['polygon', 'color', ...]`")
  447. def instance_segmentation_wrapper(mask):
  448. # See https://github.com/mcordts/cityscapesScripts/blob/8da5dd00c9069058ccc134654116aac52d4f6fa2/cityscapesscripts/preparation/json2instanceImg.py#L7-L21
  449. data = pil_image_to_mask(mask)
  450. masks = []
  451. labels = []
  452. for id in data.unique():
  453. masks.append(data == id)
  454. label = id
  455. if label >= 1_000:
  456. label //= 1_000
  457. labels.append(label)
  458. return dict(masks=tv_tensors.Mask(torch.stack(masks)), labels=torch.stack(labels))
  459. def wrapper(idx, sample):
  460. image, target = sample
  461. target = wrap_target_by_type(
  462. target,
  463. target_types=dataset.target_type,
  464. type_wrappers={
  465. "instance": instance_segmentation_wrapper,
  466. "semantic": pil_image_to_mask,
  467. },
  468. )
  469. return image, target
  470. return wrapper
  471. @WRAPPER_FACTORIES.register(datasets.WIDERFace)
  472. def widerface_wrapper(dataset, target_keys):
  473. target_keys = parse_target_keys(
  474. target_keys,
  475. available={
  476. "bbox",
  477. "blur",
  478. "expression",
  479. "illumination",
  480. "occlusion",
  481. "pose",
  482. "invalid",
  483. },
  484. default="all",
  485. )
  486. def wrapper(idx, sample):
  487. image, target = sample
  488. if target is None:
  489. return image, target
  490. target = {key: target[key] for key in target_keys}
  491. if "bbox" in target_keys:
  492. target["bbox"] = F.convert_bounding_box_format(
  493. tv_tensors.BoundingBoxes(
  494. target["bbox"], format=tv_tensors.BoundingBoxFormat.XYWH, canvas_size=(image.height, image.width)
  495. ),
  496. new_format=tv_tensors.BoundingBoxFormat.XYXY,
  497. )
  498. return image, target
  499. return wrapper