transforms.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import torch
  2. import torchvision.transforms as T
  3. import torchvision.transforms.functional as F
  4. class ValidateModelInput(torch.nn.Module):
  5. # Pass-through transform that checks the shape and dtypes to make sure the model gets what it expects
  6. def forward(self, img1, img2, flow, valid_flow_mask):
  7. if not all(isinstance(arg, torch.Tensor) for arg in (img1, img2, flow, valid_flow_mask) if arg is not None):
  8. raise TypeError("This method expects all input arguments to be of type torch.Tensor.")
  9. if not all(arg.dtype == torch.float32 for arg in (img1, img2, flow) if arg is not None):
  10. raise TypeError("This method expects the tensors img1, img2 and flow of be of dtype torch.float32.")
  11. if img1.shape != img2.shape:
  12. raise ValueError("img1 and img2 should have the same shape.")
  13. h, w = img1.shape[-2:]
  14. if flow is not None and flow.shape != (2, h, w):
  15. raise ValueError(f"flow.shape should be (2, {h}, {w}) instead of {flow.shape}")
  16. if valid_flow_mask is not None:
  17. if valid_flow_mask.shape != (h, w):
  18. raise ValueError(f"valid_flow_mask.shape should be ({h}, {w}) instead of {valid_flow_mask.shape}")
  19. if valid_flow_mask.dtype != torch.bool:
  20. raise TypeError("valid_flow_mask should be of dtype torch.bool instead of {valid_flow_mask.dtype}")
  21. return img1, img2, flow, valid_flow_mask
  22. class MakeValidFlowMask(torch.nn.Module):
  23. # This transform generates a valid_flow_mask if it doesn't exist.
  24. # The flow is considered valid if ||flow||_inf < threshold
  25. # This is a noop for Kitti and HD1K which already come with a built-in flow mask.
  26. def __init__(self, threshold=1000):
  27. super().__init__()
  28. self.threshold = threshold
  29. def forward(self, img1, img2, flow, valid_flow_mask):
  30. if flow is not None and valid_flow_mask is None:
  31. valid_flow_mask = (flow.abs() < self.threshold).all(axis=0)
  32. return img1, img2, flow, valid_flow_mask
  33. class ConvertImageDtype(torch.nn.Module):
  34. def __init__(self, dtype):
  35. super().__init__()
  36. self.dtype = dtype
  37. def forward(self, img1, img2, flow, valid_flow_mask):
  38. img1 = F.convert_image_dtype(img1, dtype=self.dtype)
  39. img2 = F.convert_image_dtype(img2, dtype=self.dtype)
  40. img1 = img1.contiguous()
  41. img2 = img2.contiguous()
  42. return img1, img2, flow, valid_flow_mask
  43. class Normalize(torch.nn.Module):
  44. def __init__(self, mean, std):
  45. super().__init__()
  46. self.mean = mean
  47. self.std = std
  48. def forward(self, img1, img2, flow, valid_flow_mask):
  49. img1 = F.normalize(img1, mean=self.mean, std=self.std)
  50. img2 = F.normalize(img2, mean=self.mean, std=self.std)
  51. return img1, img2, flow, valid_flow_mask
  52. class PILToTensor(torch.nn.Module):
  53. # Converts all inputs to tensors
  54. # Technically the flow and the valid mask are numpy arrays, not PIL images, but we keep that naming
  55. # for consistency with the rest, e.g. the segmentation reference.
  56. def forward(self, img1, img2, flow, valid_flow_mask):
  57. img1 = F.pil_to_tensor(img1)
  58. img2 = F.pil_to_tensor(img2)
  59. if flow is not None:
  60. flow = torch.from_numpy(flow)
  61. if valid_flow_mask is not None:
  62. valid_flow_mask = torch.from_numpy(valid_flow_mask)
  63. return img1, img2, flow, valid_flow_mask
  64. class AsymmetricColorJitter(T.ColorJitter):
  65. # p determines the proba of doing asymmertric vs symmetric color jittering
  66. def __init__(self, brightness=0, contrast=0, saturation=0, hue=0, p=0.2):
  67. super().__init__(brightness=brightness, contrast=contrast, saturation=saturation, hue=hue)
  68. self.p = p
  69. def forward(self, img1, img2, flow, valid_flow_mask):
  70. if torch.rand(1) < self.p:
  71. # asymmetric: different transform for img1 and img2
  72. img1 = super().forward(img1)
  73. img2 = super().forward(img2)
  74. else:
  75. # symmetric: same transform for img1 and img2
  76. batch = torch.stack([img1, img2])
  77. batch = super().forward(batch)
  78. img1, img2 = batch[0], batch[1]
  79. return img1, img2, flow, valid_flow_mask
  80. class RandomErasing(T.RandomErasing):
  81. # This only erases img2, and with an extra max_erase param
  82. # This max_erase is needed because in the RAFT training ref does:
  83. # 0 erasing with .5 proba
  84. # 1 erase with .25 proba
  85. # 2 erase with .25 proba
  86. # and there's no accurate way to achieve this otherwise.
  87. def __init__(self, p=0.5, scale=(0.02, 0.33), ratio=(0.3, 3.3), value=0, inplace=False, max_erase=1):
  88. super().__init__(p=p, scale=scale, ratio=ratio, value=value, inplace=inplace)
  89. self.max_erase = max_erase
  90. if self.max_erase <= 0:
  91. raise ValueError("max_raise should be greater than 0")
  92. def forward(self, img1, img2, flow, valid_flow_mask):
  93. if torch.rand(1) > self.p:
  94. return img1, img2, flow, valid_flow_mask
  95. for _ in range(torch.randint(self.max_erase, size=(1,)).item()):
  96. x, y, h, w, v = self.get_params(img2, scale=self.scale, ratio=self.ratio, value=[self.value])
  97. img2 = F.erase(img2, x, y, h, w, v, self.inplace)
  98. return img1, img2, flow, valid_flow_mask
  99. class RandomHorizontalFlip(T.RandomHorizontalFlip):
  100. def forward(self, img1, img2, flow, valid_flow_mask):
  101. if torch.rand(1) > self.p:
  102. return img1, img2, flow, valid_flow_mask
  103. img1 = F.hflip(img1)
  104. img2 = F.hflip(img2)
  105. flow = F.hflip(flow) * torch.tensor([-1, 1])[:, None, None]
  106. if valid_flow_mask is not None:
  107. valid_flow_mask = F.hflip(valid_flow_mask)
  108. return img1, img2, flow, valid_flow_mask
  109. class RandomVerticalFlip(T.RandomVerticalFlip):
  110. def forward(self, img1, img2, flow, valid_flow_mask):
  111. if torch.rand(1) > self.p:
  112. return img1, img2, flow, valid_flow_mask
  113. img1 = F.vflip(img1)
  114. img2 = F.vflip(img2)
  115. flow = F.vflip(flow) * torch.tensor([1, -1])[:, None, None]
  116. if valid_flow_mask is not None:
  117. valid_flow_mask = F.vflip(valid_flow_mask)
  118. return img1, img2, flow, valid_flow_mask
  119. class RandomResizeAndCrop(torch.nn.Module):
  120. # This transform will resize the input with a given proba, and then crop it.
  121. # These are the reversed operations of the built-in RandomResizedCrop,
  122. # although the order of the operations doesn't matter too much: resizing a
  123. # crop would give the same result as cropping a resized image, up to
  124. # interpolation artifact at the borders of the output.
  125. #
  126. # The reason we don't rely on RandomResizedCrop is because of a significant
  127. # difference in the parametrization of both transforms, in particular,
  128. # because of the way the random parameters are sampled in both transforms,
  129. # which leads to fairly different results (and different epe). For more details see
  130. # https://github.com/pytorch/vision/pull/5026/files#r762932579
  131. def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, stretch_prob=0.8):
  132. super().__init__()
  133. self.crop_size = crop_size
  134. self.min_scale = min_scale
  135. self.max_scale = max_scale
  136. self.stretch_prob = stretch_prob
  137. self.resize_prob = 0.8
  138. self.max_stretch = 0.2
  139. def forward(self, img1, img2, flow, valid_flow_mask):
  140. # randomly sample scale
  141. h, w = img1.shape[-2:]
  142. # Note: in original code, they use + 1 instead of + 8 for sparse datasets (e.g. Kitti)
  143. # It shouldn't matter much
  144. min_scale = max((self.crop_size[0] + 8) / h, (self.crop_size[1] + 8) / w)
  145. scale = 2 ** torch.empty(1, dtype=torch.float32).uniform_(self.min_scale, self.max_scale).item()
  146. scale_x = scale
  147. scale_y = scale
  148. if torch.rand(1) < self.stretch_prob:
  149. scale_x *= 2 ** torch.empty(1, dtype=torch.float32).uniform_(-self.max_stretch, self.max_stretch).item()
  150. scale_y *= 2 ** torch.empty(1, dtype=torch.float32).uniform_(-self.max_stretch, self.max_stretch).item()
  151. scale_x = max(scale_x, min_scale)
  152. scale_y = max(scale_y, min_scale)
  153. new_h, new_w = round(h * scale_y), round(w * scale_x)
  154. if torch.rand(1).item() < self.resize_prob:
  155. # rescale the images
  156. # We hard-code antialias=False to preserve results after we changed
  157. # its default from None to True (see
  158. # https://github.com/pytorch/vision/pull/7160)
  159. # TODO: we could re-train the OF models with antialias=True?
  160. img1 = F.resize(img1, size=(new_h, new_w), antialias=False)
  161. img2 = F.resize(img2, size=(new_h, new_w), antialias=False)
  162. if valid_flow_mask is None:
  163. flow = F.resize(flow, size=(new_h, new_w))
  164. flow = flow * torch.tensor([scale_x, scale_y])[:, None, None]
  165. else:
  166. flow, valid_flow_mask = self._resize_sparse_flow(
  167. flow, valid_flow_mask, scale_x=scale_x, scale_y=scale_y
  168. )
  169. # Note: For sparse datasets (Kitti), the original code uses a "margin"
  170. # See e.g. https://github.com/princeton-vl/RAFT/blob/master/core/utils/augmentor.py#L220:L220
  171. # We don't, not sure if it matters much
  172. y0 = torch.randint(0, img1.shape[1] - self.crop_size[0], size=(1,)).item()
  173. x0 = torch.randint(0, img1.shape[2] - self.crop_size[1], size=(1,)).item()
  174. img1 = F.crop(img1, y0, x0, self.crop_size[0], self.crop_size[1])
  175. img2 = F.crop(img2, y0, x0, self.crop_size[0], self.crop_size[1])
  176. flow = F.crop(flow, y0, x0, self.crop_size[0], self.crop_size[1])
  177. if valid_flow_mask is not None:
  178. valid_flow_mask = F.crop(valid_flow_mask, y0, x0, self.crop_size[0], self.crop_size[1])
  179. return img1, img2, flow, valid_flow_mask
  180. def _resize_sparse_flow(self, flow, valid_flow_mask, scale_x=1.0, scale_y=1.0):
  181. # This resizes both the flow and the valid_flow_mask mask (which is assumed to be reasonably sparse)
  182. # There are as-many non-zero values in the original flow as in the resized flow (up to OOB)
  183. # So for example if scale_x = scale_y = 2, the sparsity of the output flow is multiplied by 4
  184. h, w = flow.shape[-2:]
  185. h_new = int(round(h * scale_y))
  186. w_new = int(round(w * scale_x))
  187. flow_new = torch.zeros(size=[2, h_new, w_new], dtype=flow.dtype)
  188. valid_new = torch.zeros(size=[h_new, w_new], dtype=valid_flow_mask.dtype)
  189. jj, ii = torch.meshgrid(torch.arange(w), torch.arange(h), indexing="xy")
  190. ii_valid, jj_valid = ii[valid_flow_mask], jj[valid_flow_mask]
  191. ii_valid_new = torch.round(ii_valid.to(float) * scale_y).to(torch.long)
  192. jj_valid_new = torch.round(jj_valid.to(float) * scale_x).to(torch.long)
  193. within_bounds_mask = (0 <= ii_valid_new) & (ii_valid_new < h_new) & (0 <= jj_valid_new) & (jj_valid_new < w_new)
  194. ii_valid = ii_valid[within_bounds_mask]
  195. jj_valid = jj_valid[within_bounds_mask]
  196. ii_valid_new = ii_valid_new[within_bounds_mask]
  197. jj_valid_new = jj_valid_new[within_bounds_mask]
  198. valid_flow_new = flow[:, ii_valid, jj_valid]
  199. valid_flow_new[0] *= scale_x
  200. valid_flow_new[1] *= scale_y
  201. flow_new[:, ii_valid_new, jj_valid_new] = valid_flow_new
  202. valid_new[ii_valid_new, jj_valid_new] = 1
  203. return flow_new, valid_new
  204. class Compose(torch.nn.Module):
  205. def __init__(self, transforms):
  206. super().__init__()
  207. self.transforms = transforms
  208. def forward(self, img1, img2, flow, valid_flow_mask):
  209. for t in self.transforms:
  210. img1, img2, flow, valid_flow_mask = t(img1, img2, flow, valid_flow_mask)
  211. return img1, img2, flow, valid_flow_mask