transforms.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. from typing import Dict, List, Optional, Tuple, Union
  2. import torch
  3. import torchvision
  4. from torch import nn, Tensor
  5. from torchvision import ops
  6. from torchvision.transforms import functional as F, InterpolationMode, transforms as T
  7. def _flip_coco_person_keypoints(kps, width):
  8. flip_inds = [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]
  9. flipped_data = kps[:, flip_inds]
  10. flipped_data[..., 0] = width - flipped_data[..., 0]
  11. # Maintain COCO convention that if visibility == 0, then x, y = 0
  12. inds = flipped_data[..., 2] == 0
  13. flipped_data[inds] = 0
  14. return flipped_data
  15. class Compose:
  16. def __init__(self, transforms):
  17. self.transforms = transforms
  18. def __call__(self, image, target):
  19. for t in self.transforms:
  20. image, target = t(image, target)
  21. return image, target
  22. class RandomHorizontalFlip(T.RandomHorizontalFlip):
  23. def forward(
  24. self, image: Tensor, target: Optional[Dict[str, Tensor]] = None
  25. ) -> Tuple[Tensor, Optional[Dict[str, Tensor]]]:
  26. if torch.rand(1) < self.p:
  27. image = F.hflip(image)
  28. if target is not None:
  29. _, _, width = F.get_dimensions(image)
  30. target["boxes"][:, [0, 2]] = width - target["boxes"][:, [2, 0]]
  31. if "masks" in target:
  32. target["masks"] = target["masks"].flip(-1)
  33. if "keypoints" in target:
  34. keypoints = target["keypoints"]
  35. keypoints = _flip_coco_person_keypoints(keypoints, width)
  36. target["keypoints"] = keypoints
  37. return image, target
  38. class PILToTensor(nn.Module):
  39. def forward(
  40. self, image: Tensor, target: Optional[Dict[str, Tensor]] = None
  41. ) -> Tuple[Tensor, Optional[Dict[str, Tensor]]]:
  42. image = F.pil_to_tensor(image)
  43. return image, target
  44. class ToDtype(nn.Module):
  45. def __init__(self, dtype: torch.dtype, scale: bool = False) -> None:
  46. super().__init__()
  47. self.dtype = dtype
  48. self.scale = scale
  49. def forward(
  50. self, image: Tensor, target: Optional[Dict[str, Tensor]] = None
  51. ) -> Tuple[Tensor, Optional[Dict[str, Tensor]]]:
  52. if not self.scale:
  53. return image.to(dtype=self.dtype), target
  54. image = F.convert_image_dtype(image, self.dtype)
  55. return image, target
  56. class RandomIoUCrop(nn.Module):
  57. def __init__(
  58. self,
  59. min_scale: float = 0.3,
  60. max_scale: float = 1.0,
  61. min_aspect_ratio: float = 0.5,
  62. max_aspect_ratio: float = 2.0,
  63. sampler_options: Optional[List[float]] = None,
  64. trials: int = 40,
  65. ):
  66. super().__init__()
  67. # Configuration similar to https://github.com/weiliu89/caffe/blob/ssd/examples/ssd/ssd_coco.py#L89-L174
  68. self.min_scale = min_scale
  69. self.max_scale = max_scale
  70. self.min_aspect_ratio = min_aspect_ratio
  71. self.max_aspect_ratio = max_aspect_ratio
  72. if sampler_options is None:
  73. sampler_options = [0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0]
  74. self.options = sampler_options
  75. self.trials = trials
  76. def forward(
  77. self, image: Tensor, target: Optional[Dict[str, Tensor]] = None
  78. ) -> Tuple[Tensor, Optional[Dict[str, Tensor]]]:
  79. if target is None:
  80. raise ValueError("The targets can't be None for this transform.")
  81. if isinstance(image, torch.Tensor):
  82. if image.ndimension() not in {2, 3}:
  83. raise ValueError(f"image should be 2/3 dimensional. Got {image.ndimension()} dimensions.")
  84. elif image.ndimension() == 2:
  85. image = image.unsqueeze(0)
  86. _, orig_h, orig_w = F.get_dimensions(image)
  87. while True:
  88. # sample an option
  89. idx = int(torch.randint(low=0, high=len(self.options), size=(1,)))
  90. min_jaccard_overlap = self.options[idx]
  91. if min_jaccard_overlap >= 1.0: # a value larger than 1 encodes the leave as-is option
  92. return image, target
  93. for _ in range(self.trials):
  94. # check the aspect ratio limitations
  95. r = self.min_scale + (self.max_scale - self.min_scale) * torch.rand(2)
  96. new_w = int(orig_w * r[0])
  97. new_h = int(orig_h * r[1])
  98. aspect_ratio = new_w / new_h
  99. if not (self.min_aspect_ratio <= aspect_ratio <= self.max_aspect_ratio):
  100. continue
  101. # check for 0 area crops
  102. r = torch.rand(2)
  103. left = int((orig_w - new_w) * r[0])
  104. top = int((orig_h - new_h) * r[1])
  105. right = left + new_w
  106. bottom = top + new_h
  107. if left == right or top == bottom:
  108. continue
  109. # check for any valid boxes with centers within the crop area
  110. cx = 0.5 * (target["boxes"][:, 0] + target["boxes"][:, 2])
  111. cy = 0.5 * (target["boxes"][:, 1] + target["boxes"][:, 3])
  112. is_within_crop_area = (left < cx) & (cx < right) & (top < cy) & (cy < bottom)
  113. if not is_within_crop_area.any():
  114. continue
  115. # check at least 1 box with jaccard limitations
  116. boxes = target["boxes"][is_within_crop_area]
  117. ious = torchvision.ops.boxes.box_iou(
  118. boxes, torch.tensor([[left, top, right, bottom]], dtype=boxes.dtype, device=boxes.device)
  119. )
  120. if ious.max() < min_jaccard_overlap:
  121. continue
  122. # keep only valid boxes and perform cropping
  123. target["boxes"] = boxes
  124. target["labels"] = target["labels"][is_within_crop_area]
  125. target["boxes"][:, 0::2] -= left
  126. target["boxes"][:, 1::2] -= top
  127. target["boxes"][:, 0::2].clamp_(min=0, max=new_w)
  128. target["boxes"][:, 1::2].clamp_(min=0, max=new_h)
  129. image = F.crop(image, top, left, new_h, new_w)
  130. return image, target
  131. class RandomZoomOut(nn.Module):
  132. def __init__(
  133. self, fill: Optional[List[float]] = None, side_range: Tuple[float, float] = (1.0, 4.0), p: float = 0.5
  134. ):
  135. super().__init__()
  136. if fill is None:
  137. fill = [0.0, 0.0, 0.0]
  138. self.fill = fill
  139. self.side_range = side_range
  140. if side_range[0] < 1.0 or side_range[0] > side_range[1]:
  141. raise ValueError(f"Invalid canvas side range provided {side_range}.")
  142. self.p = p
  143. @torch.jit.unused
  144. def _get_fill_value(self, is_pil):
  145. # type: (bool) -> int
  146. # We fake the type to make it work on JIT
  147. return tuple(int(x) for x in self.fill) if is_pil else 0
  148. def forward(
  149. self, image: Tensor, target: Optional[Dict[str, Tensor]] = None
  150. ) -> Tuple[Tensor, Optional[Dict[str, Tensor]]]:
  151. if isinstance(image, torch.Tensor):
  152. if image.ndimension() not in {2, 3}:
  153. raise ValueError(f"image should be 2/3 dimensional. Got {image.ndimension()} dimensions.")
  154. elif image.ndimension() == 2:
  155. image = image.unsqueeze(0)
  156. if torch.rand(1) >= self.p:
  157. return image, target
  158. _, orig_h, orig_w = F.get_dimensions(image)
  159. r = self.side_range[0] + torch.rand(1) * (self.side_range[1] - self.side_range[0])
  160. canvas_width = int(orig_w * r)
  161. canvas_height = int(orig_h * r)
  162. r = torch.rand(2)
  163. left = int((canvas_width - orig_w) * r[0])
  164. top = int((canvas_height - orig_h) * r[1])
  165. right = canvas_width - (left + orig_w)
  166. bottom = canvas_height - (top + orig_h)
  167. if torch.jit.is_scripting():
  168. fill = 0
  169. else:
  170. fill = self._get_fill_value(F._is_pil_image(image))
  171. image = F.pad(image, [left, top, right, bottom], fill=fill)
  172. if isinstance(image, torch.Tensor):
  173. # PyTorch's pad supports only integers on fill. So we need to overwrite the colour
  174. v = torch.tensor(self.fill, device=image.device, dtype=image.dtype).view(-1, 1, 1)
  175. image[..., :top, :] = image[..., :, :left] = image[..., (top + orig_h) :, :] = image[
  176. ..., :, (left + orig_w) :
  177. ] = v
  178. if target is not None:
  179. target["boxes"][:, 0::2] += left
  180. target["boxes"][:, 1::2] += top
  181. return image, target
  182. class RandomPhotometricDistort(nn.Module):
  183. def __init__(
  184. self,
  185. contrast: Tuple[float, float] = (0.5, 1.5),
  186. saturation: Tuple[float, float] = (0.5, 1.5),
  187. hue: Tuple[float, float] = (-0.05, 0.05),
  188. brightness: Tuple[float, float] = (0.875, 1.125),
  189. p: float = 0.5,
  190. ):
  191. super().__init__()
  192. self._brightness = T.ColorJitter(brightness=brightness)
  193. self._contrast = T.ColorJitter(contrast=contrast)
  194. self._hue = T.ColorJitter(hue=hue)
  195. self._saturation = T.ColorJitter(saturation=saturation)
  196. self.p = p
  197. def forward(
  198. self, image: Tensor, target: Optional[Dict[str, Tensor]] = None
  199. ) -> Tuple[Tensor, Optional[Dict[str, Tensor]]]:
  200. if isinstance(image, torch.Tensor):
  201. if image.ndimension() not in {2, 3}:
  202. raise ValueError(f"image should be 2/3 dimensional. Got {image.ndimension()} dimensions.")
  203. elif image.ndimension() == 2:
  204. image = image.unsqueeze(0)
  205. r = torch.rand(7)
  206. if r[0] < self.p:
  207. image = self._brightness(image)
  208. contrast_before = r[1] < 0.5
  209. if contrast_before:
  210. if r[2] < self.p:
  211. image = self._contrast(image)
  212. if r[3] < self.p:
  213. image = self._saturation(image)
  214. if r[4] < self.p:
  215. image = self._hue(image)
  216. if not contrast_before:
  217. if r[5] < self.p:
  218. image = self._contrast(image)
  219. if r[6] < self.p:
  220. channels, _, _ = F.get_dimensions(image)
  221. permutation = torch.randperm(channels)
  222. is_pil = F._is_pil_image(image)
  223. if is_pil:
  224. image = F.pil_to_tensor(image)
  225. image = F.convert_image_dtype(image)
  226. image = image[..., permutation, :, :]
  227. if is_pil:
  228. image = F.to_pil_image(image)
  229. return image, target
  230. class ScaleJitter(nn.Module):
  231. """Randomly resizes the image and its bounding boxes within the specified scale range.
  232. The class implements the Scale Jitter augmentation as described in the paper
  233. `"Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation" <https://arxiv.org/abs/2012.07177>`_.
  234. Args:
  235. target_size (tuple of ints): The target size for the transform provided in (height, weight) format.
  236. scale_range (tuple of ints): scaling factor interval, e.g (a, b), then scale is randomly sampled from the
  237. range a <= scale <= b.
  238. interpolation (InterpolationMode): Desired interpolation enum defined by
  239. :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
  240. """
  241. def __init__(
  242. self,
  243. target_size: Tuple[int, int],
  244. scale_range: Tuple[float, float] = (0.1, 2.0),
  245. interpolation: InterpolationMode = InterpolationMode.BILINEAR,
  246. antialias=True,
  247. ):
  248. super().__init__()
  249. self.target_size = target_size
  250. self.scale_range = scale_range
  251. self.interpolation = interpolation
  252. self.antialias = antialias
  253. def forward(
  254. self, image: Tensor, target: Optional[Dict[str, Tensor]] = None
  255. ) -> Tuple[Tensor, Optional[Dict[str, Tensor]]]:
  256. if isinstance(image, torch.Tensor):
  257. if image.ndimension() not in {2, 3}:
  258. raise ValueError(f"image should be 2/3 dimensional. Got {image.ndimension()} dimensions.")
  259. elif image.ndimension() == 2:
  260. image = image.unsqueeze(0)
  261. _, orig_height, orig_width = F.get_dimensions(image)
  262. scale = self.scale_range[0] + torch.rand(1) * (self.scale_range[1] - self.scale_range[0])
  263. r = min(self.target_size[1] / orig_height, self.target_size[0] / orig_width) * scale
  264. new_width = int(orig_width * r)
  265. new_height = int(orig_height * r)
  266. image = F.resize(image, [new_height, new_width], interpolation=self.interpolation, antialias=self.antialias)
  267. if target is not None:
  268. target["boxes"][:, 0::2] *= new_width / orig_width
  269. target["boxes"][:, 1::2] *= new_height / orig_height
  270. if "masks" in target:
  271. target["masks"] = F.resize(
  272. target["masks"],
  273. [new_height, new_width],
  274. interpolation=InterpolationMode.NEAREST,
  275. antialias=self.antialias,
  276. )
  277. return image, target
  278. class FixedSizeCrop(nn.Module):
  279. def __init__(self, size, fill=0, padding_mode="constant"):
  280. super().__init__()
  281. size = tuple(T._setup_size(size, error_msg="Please provide only two dimensions (h, w) for size."))
  282. self.crop_height = size[0]
  283. self.crop_width = size[1]
  284. self.fill = fill # TODO: Fill is currently respected only on PIL. Apply tensor patch.
  285. self.padding_mode = padding_mode
  286. def _pad(self, img, target, padding):
  287. # Taken from the functional_tensor.py pad
  288. if isinstance(padding, int):
  289. pad_left = pad_right = pad_top = pad_bottom = padding
  290. elif len(padding) == 1:
  291. pad_left = pad_right = pad_top = pad_bottom = padding[0]
  292. elif len(padding) == 2:
  293. pad_left = pad_right = padding[0]
  294. pad_top = pad_bottom = padding[1]
  295. else:
  296. pad_left = padding[0]
  297. pad_top = padding[1]
  298. pad_right = padding[2]
  299. pad_bottom = padding[3]
  300. padding = [pad_left, pad_top, pad_right, pad_bottom]
  301. img = F.pad(img, padding, self.fill, self.padding_mode)
  302. if target is not None:
  303. target["boxes"][:, 0::2] += pad_left
  304. target["boxes"][:, 1::2] += pad_top
  305. if "masks" in target:
  306. target["masks"] = F.pad(target["masks"], padding, 0, "constant")
  307. return img, target
  308. def _crop(self, img, target, top, left, height, width):
  309. img = F.crop(img, top, left, height, width)
  310. if target is not None:
  311. boxes = target["boxes"]
  312. boxes[:, 0::2] -= left
  313. boxes[:, 1::2] -= top
  314. boxes[:, 0::2].clamp_(min=0, max=width)
  315. boxes[:, 1::2].clamp_(min=0, max=height)
  316. is_valid = (boxes[:, 0] < boxes[:, 2]) & (boxes[:, 1] < boxes[:, 3])
  317. target["boxes"] = boxes[is_valid]
  318. target["labels"] = target["labels"][is_valid]
  319. if "masks" in target:
  320. target["masks"] = F.crop(target["masks"][is_valid], top, left, height, width)
  321. return img, target
  322. def forward(self, img, target=None):
  323. _, height, width = F.get_dimensions(img)
  324. new_height = min(height, self.crop_height)
  325. new_width = min(width, self.crop_width)
  326. if new_height != height or new_width != width:
  327. offset_height = max(height - self.crop_height, 0)
  328. offset_width = max(width - self.crop_width, 0)
  329. r = torch.rand(1)
  330. top = int(offset_height * r)
  331. left = int(offset_width * r)
  332. img, target = self._crop(img, target, top, left, new_height, new_width)
  333. pad_bottom = max(self.crop_height - new_height, 0)
  334. pad_right = max(self.crop_width - new_width, 0)
  335. if pad_bottom != 0 or pad_right != 0:
  336. img, target = self._pad(img, target, [0, 0, pad_right, pad_bottom])
  337. return img, target
  338. class RandomShortestSize(nn.Module):
  339. def __init__(
  340. self,
  341. min_size: Union[List[int], Tuple[int], int],
  342. max_size: int,
  343. interpolation: InterpolationMode = InterpolationMode.BILINEAR,
  344. ):
  345. super().__init__()
  346. self.min_size = [min_size] if isinstance(min_size, int) else list(min_size)
  347. self.max_size = max_size
  348. self.interpolation = interpolation
  349. def forward(
  350. self, image: Tensor, target: Optional[Dict[str, Tensor]] = None
  351. ) -> Tuple[Tensor, Optional[Dict[str, Tensor]]]:
  352. _, orig_height, orig_width = F.get_dimensions(image)
  353. min_size = self.min_size[torch.randint(len(self.min_size), (1,)).item()]
  354. r = min(min_size / min(orig_height, orig_width), self.max_size / max(orig_height, orig_width))
  355. new_width = int(orig_width * r)
  356. new_height = int(orig_height * r)
  357. image = F.resize(image, [new_height, new_width], interpolation=self.interpolation)
  358. if target is not None:
  359. target["boxes"][:, 0::2] *= new_width / orig_width
  360. target["boxes"][:, 1::2] *= new_height / orig_height
  361. if "masks" in target:
  362. target["masks"] = F.resize(
  363. target["masks"], [new_height, new_width], interpolation=InterpolationMode.NEAREST
  364. )
  365. return image, target
  366. def _copy_paste(
  367. image: torch.Tensor,
  368. target: Dict[str, Tensor],
  369. paste_image: torch.Tensor,
  370. paste_target: Dict[str, Tensor],
  371. blending: bool = True,
  372. resize_interpolation: F.InterpolationMode = F.InterpolationMode.BILINEAR,
  373. ) -> Tuple[torch.Tensor, Dict[str, Tensor]]:
  374. # Random paste targets selection:
  375. num_masks = len(paste_target["masks"])
  376. if num_masks < 1:
  377. # Such degerante case with num_masks=0 can happen with LSJ
  378. # Let's just return (image, target)
  379. return image, target
  380. # We have to please torch script by explicitly specifying dtype as torch.long
  381. random_selection = torch.randint(0, num_masks, (num_masks,), device=paste_image.device)
  382. random_selection = torch.unique(random_selection).to(torch.long)
  383. paste_masks = paste_target["masks"][random_selection]
  384. paste_boxes = paste_target["boxes"][random_selection]
  385. paste_labels = paste_target["labels"][random_selection]
  386. masks = target["masks"]
  387. # We resize source and paste data if they have different sizes
  388. # This is something we introduced here as originally the algorithm works
  389. # on equal-sized data (for example, coming from LSJ data augmentations)
  390. size1 = image.shape[-2:]
  391. size2 = paste_image.shape[-2:]
  392. if size1 != size2:
  393. paste_image = F.resize(paste_image, size1, interpolation=resize_interpolation)
  394. paste_masks = F.resize(paste_masks, size1, interpolation=F.InterpolationMode.NEAREST)
  395. # resize bboxes:
  396. ratios = torch.tensor((size1[1] / size2[1], size1[0] / size2[0]), device=paste_boxes.device)
  397. paste_boxes = paste_boxes.view(-1, 2, 2).mul(ratios).view(paste_boxes.shape)
  398. paste_alpha_mask = paste_masks.sum(dim=0) > 0
  399. if blending:
  400. paste_alpha_mask = F.gaussian_blur(
  401. paste_alpha_mask.unsqueeze(0),
  402. kernel_size=(5, 5),
  403. sigma=[
  404. 2.0,
  405. ],
  406. )
  407. # Copy-paste images:
  408. image = (image * (~paste_alpha_mask)) + (paste_image * paste_alpha_mask)
  409. # Copy-paste masks:
  410. masks = masks * (~paste_alpha_mask)
  411. non_all_zero_masks = masks.sum((-1, -2)) > 0
  412. masks = masks[non_all_zero_masks]
  413. # Do a shallow copy of the target dict
  414. out_target = {k: v for k, v in target.items()}
  415. out_target["masks"] = torch.cat([masks, paste_masks])
  416. # Copy-paste boxes and labels
  417. boxes = ops.masks_to_boxes(masks)
  418. out_target["boxes"] = torch.cat([boxes, paste_boxes])
  419. labels = target["labels"][non_all_zero_masks]
  420. out_target["labels"] = torch.cat([labels, paste_labels])
  421. # Update additional optional keys: area and iscrowd if exist
  422. if "area" in target:
  423. out_target["area"] = out_target["masks"].sum((-1, -2)).to(torch.float32)
  424. if "iscrowd" in target and "iscrowd" in paste_target:
  425. # target['iscrowd'] size can be differ from mask size (non_all_zero_masks)
  426. # For example, if previous transforms geometrically modifies masks/boxes/labels but
  427. # does not update "iscrowd"
  428. if len(target["iscrowd"]) == len(non_all_zero_masks):
  429. iscrowd = target["iscrowd"][non_all_zero_masks]
  430. paste_iscrowd = paste_target["iscrowd"][random_selection]
  431. out_target["iscrowd"] = torch.cat([iscrowd, paste_iscrowd])
  432. # Check for degenerated boxes and remove them
  433. boxes = out_target["boxes"]
  434. degenerate_boxes = boxes[:, 2:] <= boxes[:, :2]
  435. if degenerate_boxes.any():
  436. valid_targets = ~degenerate_boxes.any(dim=1)
  437. out_target["boxes"] = boxes[valid_targets]
  438. out_target["masks"] = out_target["masks"][valid_targets]
  439. out_target["labels"] = out_target["labels"][valid_targets]
  440. if "area" in out_target:
  441. out_target["area"] = out_target["area"][valid_targets]
  442. if "iscrowd" in out_target and len(out_target["iscrowd"]) == len(valid_targets):
  443. out_target["iscrowd"] = out_target["iscrowd"][valid_targets]
  444. return image, out_target
  445. class SimpleCopyPaste(torch.nn.Module):
  446. def __init__(self, blending=True, resize_interpolation=F.InterpolationMode.BILINEAR):
  447. super().__init__()
  448. self.resize_interpolation = resize_interpolation
  449. self.blending = blending
  450. def forward(
  451. self, images: List[torch.Tensor], targets: List[Dict[str, Tensor]]
  452. ) -> Tuple[List[torch.Tensor], List[Dict[str, Tensor]]]:
  453. torch._assert(
  454. isinstance(images, (list, tuple)) and all([isinstance(v, torch.Tensor) for v in images]),
  455. "images should be a list of tensors",
  456. )
  457. torch._assert(
  458. isinstance(targets, (list, tuple)) and len(images) == len(targets),
  459. "targets should be a list of the same size as images",
  460. )
  461. for target in targets:
  462. # Can not check for instance type dict with inside torch.jit.script
  463. # torch._assert(isinstance(target, dict), "targets item should be a dict")
  464. for k in ["masks", "boxes", "labels"]:
  465. torch._assert(k in target, f"Key {k} should be present in targets")
  466. torch._assert(isinstance(target[k], torch.Tensor), f"Value for the key {k} should be a tensor")
  467. # images = [t1, t2, ..., tN]
  468. # Let's define paste_images as shifted list of input images
  469. # paste_images = [t2, t3, ..., tN, t1]
  470. # FYI: in TF they mix data on the dataset level
  471. images_rolled = images[-1:] + images[:-1]
  472. targets_rolled = targets[-1:] + targets[:-1]
  473. output_images: List[torch.Tensor] = []
  474. output_targets: List[Dict[str, Tensor]] = []
  475. for image, target, paste_image, paste_target in zip(images, targets, images_rolled, targets_rolled):
  476. output_image, output_data = _copy_paste(
  477. image,
  478. target,
  479. paste_image,
  480. paste_target,
  481. blending=self.blending,
  482. resize_interpolation=self.resize_interpolation,
  483. )
  484. output_images.append(output_image)
  485. output_targets.append(output_data)
  486. return output_images, output_targets
  487. def __repr__(self) -> str:
  488. s = f"{self.__class__.__name__}(blending={self.blending}, resize_interpolation={self.resize_interpolation})"
  489. return s