rtdetr_augment.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. # ------------------------------------------------------------
  2. # Data preprocessor for Real-time DETR
  3. # ------------------------------------------------------------
  4. import cv2
  5. import numpy as np
  6. from numpy import random
  7. import torch
  8. import torch.nn.functional as F
  9. # ------------------------- Augmentations -------------------------
  10. class Compose(object):
  11. """Composes several augmentations together.
  12. Args:
  13. transforms (List[Transform]): list of transforms to compose.
  14. Example:
  15. >>> augmentations.Compose([
  16. >>> transforms.CenterCrop(10),
  17. >>> transforms.ToTensor(),
  18. >>> ])
  19. """
  20. def __init__(self, transforms):
  21. self.transforms = transforms
  22. def __call__(self, image, target=None):
  23. for t in self.transforms:
  24. image, target = t(image, target)
  25. return image, target
  26. ## Convert color format
  27. class ConvertColorFormat(object):
  28. def __init__(self, color_format='rgb'):
  29. self.color_format = color_format
  30. def __call__(self, image, target=None):
  31. """
  32. Input:
  33. image: (np.array) a OpenCV image with BGR color format.
  34. target: None
  35. Output:
  36. image: (np.array) a OpenCV image with given color format.
  37. target: None
  38. """
  39. # Convert color format
  40. if self.color_format == 'rgb':
  41. image = image[..., (2, 1, 0)] # BGR -> RGB
  42. elif self.color_format == 'bgr':
  43. image = image
  44. else:
  45. raise NotImplementedError("Unknown color format: <{}>".format(self.color_format))
  46. return image, target
  47. ## Random Photometric Distort
  48. class RandomPhotometricDistort(object):
  49. """
  50. Distort image w.r.t hue, saturation and exposure.
  51. """
  52. def __init__(self, hue=0.1, saturation=1.5, exposure=1.5):
  53. super().__init__()
  54. self.hue = hue
  55. self.saturation = saturation
  56. self.exposure = exposure
  57. def __call__(self, image: np.ndarray, target=None) -> np.ndarray:
  58. """
  59. Args:
  60. img (ndarray): of shape HxW, HxWxC, or NxHxWxC. The array can be
  61. of type uint8 in range [0, 255], or floating point in range
  62. [0, 1] or [0, 255].
  63. Returns:
  64. ndarray: the distorted image(s).
  65. """
  66. if random.random() < 0.5:
  67. dhue = np.random.uniform(low=-self.hue, high=self.hue)
  68. dsat = self._rand_scale(self.saturation)
  69. dexp = self._rand_scale(self.exposure)
  70. image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  71. image = np.asarray(image, dtype=np.float32) / 255.
  72. image[:, :, 1] *= dsat
  73. image[:, :, 2] *= dexp
  74. H = image[:, :, 0] + dhue * 179 / 255.
  75. if dhue > 0:
  76. H[H > 1.0] -= 1.0
  77. else:
  78. H[H < 0.0] += 1.0
  79. image[:, :, 0] = H
  80. image = (image * 255).clip(0, 255).astype(np.uint8)
  81. image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)
  82. image = np.asarray(image, dtype=np.uint8)
  83. return image, target
  84. def _rand_scale(self, upper_bound):
  85. """
  86. Calculate random scaling factor.
  87. Args:
  88. upper_bound (float): range of the random scale.
  89. Returns:
  90. random scaling factor (float) whose range is
  91. from 1 / s to s .
  92. """
  93. scale = np.random.uniform(low=1, high=upper_bound)
  94. if np.random.rand() > 0.5:
  95. return scale
  96. return 1 / scale
  97. ## Random IoU based Sample Crop
  98. class RandomSampleCrop(object):
  99. def __init__(self):
  100. self.sample_options = (
  101. # using entire original input image
  102. None,
  103. # sample a patch s.t. MIN jaccard w/ obj in .1,.3,.4,.7,.9
  104. (0.1, None),
  105. (0.3, None),
  106. (0.7, None),
  107. (0.9, None),
  108. )
  109. def intersect(self, box_a, box_b):
  110. max_xy = np.minimum(box_a[:, 2:], box_b[2:])
  111. min_xy = np.maximum(box_a[:, :2], box_b[:2])
  112. inter = np.clip((max_xy - min_xy), a_min=0, a_max=np.inf)
  113. return inter[:, 0] * inter[:, 1]
  114. def compute_iou(self, box_a, box_b):
  115. inter = self.intersect(box_a, box_b)
  116. area_a = ((box_a[:, 2]-box_a[:, 0]) *
  117. (box_a[:, 3]-box_a[:, 1])) # [A,B]
  118. area_b = ((box_b[2]-box_b[0]) *
  119. (box_b[3]-box_b[1])) # [A,B]
  120. union = area_a + area_b - inter
  121. return inter / union # [A,B]
  122. def __call__(self, image, target=None):
  123. height, width, _ = image.shape
  124. # check target
  125. if len(target["boxes"]) == 0:
  126. return image, target
  127. while True:
  128. # randomly choose a mode
  129. sample_id = np.random.randint(len(self.sample_options))
  130. mode = self.sample_options[sample_id]
  131. if mode is None:
  132. return image, target
  133. boxes = target["boxes"]
  134. labels = target["labels"]
  135. min_iou, max_iou = mode
  136. if min_iou is None:
  137. min_iou = float('-inf')
  138. if max_iou is None:
  139. max_iou = float('inf')
  140. # max trails (50)
  141. for _ in range(50):
  142. current_image = image
  143. w = random.uniform(0.3 * width, width)
  144. h = random.uniform(0.3 * height, height)
  145. # aspect ratio constraint b/t .5 & 2
  146. if h / w < 0.5 or h / w > 2:
  147. continue
  148. left = random.uniform(width - w)
  149. top = random.uniform(height - h)
  150. # convert to integer rect x1,y1,x2,y2
  151. rect = np.array([int(left), int(top), int(left+w), int(top+h)])
  152. # calculate IoU (jaccard overlap) b/t the cropped and gt boxes
  153. overlap = self.compute_iou(boxes, rect)
  154. # is min and max overlap constraint satisfied? if not try again
  155. if overlap.min() < min_iou and max_iou < overlap.max():
  156. continue
  157. # cut the crop from the image
  158. current_image = current_image[rect[1]:rect[3], rect[0]:rect[2],
  159. :]
  160. # keep overlap with gt box IF center in sampled patch
  161. centers = (boxes[:, :2] + boxes[:, 2:]) / 2.0
  162. # mask in all gt boxes that above and to the left of centers
  163. m1 = (rect[0] < centers[:, 0]) * (rect[1] < centers[:, 1])
  164. # mask in all gt boxes that under and to the right of centers
  165. m2 = (rect[2] > centers[:, 0]) * (rect[3] > centers[:, 1])
  166. # mask in that both m1 and m2 are true
  167. mask = m1 * m2
  168. # have any valid boxes? try again if not
  169. if not mask.any():
  170. continue
  171. # take only matching gt boxes
  172. current_boxes = boxes[mask, :].copy()
  173. # take only matching gt labels
  174. current_labels = labels[mask]
  175. # should we use the box left and top corner or the crop's
  176. current_boxes[:, :2] = np.maximum(current_boxes[:, :2],
  177. rect[:2])
  178. # adjust to crop (by substracting crop's left,top)
  179. current_boxes[:, :2] -= rect[:2]
  180. current_boxes[:, 2:] = np.minimum(current_boxes[:, 2:],
  181. rect[2:])
  182. # adjust to crop (by substracting crop's left,top)
  183. current_boxes[:, 2:] -= rect[:2]
  184. # update target
  185. target["boxes"] = current_boxes
  186. target["labels"] = current_labels
  187. return current_image, target
  188. ## Random HFlip
  189. class RandomHorizontalFlip(object):
  190. def __init__(self, p=0.5):
  191. self.p = p
  192. def __call__(self, image, target=None):
  193. if random.random() < self.p:
  194. orig_h, orig_w = image.shape[:2]
  195. image = image[:, ::-1]
  196. if target is not None:
  197. if "boxes" in target:
  198. boxes = target["boxes"].copy()
  199. boxes[..., [0, 2]] = orig_w - boxes[..., [2, 0]]
  200. target["boxes"] = boxes
  201. return image, target
  202. ## Resize tensor image
  203. class Resize(object):
  204. def __init__(self, img_size=640):
  205. self.img_size = img_size
  206. def __call__(self, image, target=None):
  207. orig_h, orig_w = image.shape[:2]
  208. # resize
  209. image = cv2.resize(image, (self.img_size, self.img_size)).astype(np.float32)
  210. img_h, img_w = image.shape[:2]
  211. # rescale bboxes
  212. if target is not None:
  213. boxes = target["boxes"]
  214. boxes[:, [0, 2]] = boxes[:, [0, 2]] / orig_w * img_w
  215. boxes[:, [1, 3]] = boxes[:, [1, 3]] / orig_h * img_h
  216. target["boxes"] = boxes
  217. return image, target
  218. ## Normalize tensor image
  219. class Normalize(object):
  220. def __init__(self, pixel_mean, pixel_std):
  221. self.pixel_mean = pixel_mean
  222. self.pixel_std = pixel_std
  223. def __call__(self, image, target=None):
  224. # normalize image
  225. image = (image - self.pixel_mean) / self.pixel_std
  226. return image, target
  227. ## Convert ndarray to torch.Tensor
  228. class ToTensor(object):
  229. def __call__(self, image, target=None):
  230. # Convert torch.Tensor
  231. image = torch.from_numpy(image).permute(2, 0, 1).contiguous().float()
  232. if target is not None:
  233. target["boxes"] = torch.as_tensor(target["boxes"]).float()
  234. target["labels"] = torch.as_tensor(target["labels"]).long()
  235. return image, target
  236. # ------------------------- Preprocessers -------------------------
  237. ## Transform for Train
  238. class RTDetrAugmentation(object):
  239. def __init__(self, img_size=640, pixel_mean=[123.675, 116.28, 103.53], pixel_std=[58.395, 57.12, 57.375], use_mosaic=False):
  240. # ----------------- Basic parameters -----------------
  241. self.img_size = img_size
  242. self.use_mosaic = use_mosaic
  243. self.pixel_mean = pixel_mean # RGB format
  244. self.pixel_std = pixel_std # RGB format
  245. self.color_format = 'rgb'
  246. print("================= Pixel Statistics =================")
  247. print("Pixel mean: {}".format(self.pixel_mean))
  248. print("Pixel std: {}".format(self.pixel_std))
  249. # ----------------- Transforms -----------------
  250. if use_mosaic:
  251. # For use-mosaic setting, we do not use RandomSampleCrop processor.
  252. self.augment = Compose([
  253. RandomPhotometricDistort(hue=0.5, saturation=1.5, exposure=1.5),
  254. RandomHorizontalFlip(p=0.5),
  255. Resize(img_size=self.img_size),
  256. ConvertColorFormat(self.color_format),
  257. Normalize(self.pixel_mean, self.pixel_std),
  258. ToTensor()
  259. ])
  260. else:
  261. # For no-mosaic setting, we use RandomSampleCrop processor.
  262. self.augment = Compose([
  263. RandomPhotometricDistort(hue=0.5, saturation=1.5, exposure=1.5),
  264. RandomSampleCrop(),
  265. RandomHorizontalFlip(p=0.5),
  266. Resize(img_size=self.img_size),
  267. ConvertColorFormat(self.color_format),
  268. Normalize(self.pixel_mean, self.pixel_std),
  269. ToTensor()
  270. ])
  271. def __call__(self, image, target, mosaic=False):
  272. orig_h, orig_w = image.shape[:2]
  273. ratio = [self.img_size / orig_w, self.img_size / orig_h]
  274. image, target = self.augment(image, target)
  275. return image, target, ratio
  276. ## Transform for Eval
  277. class RTDetrBaseTransform(object):
  278. def __init__(self, img_size=640, pixel_mean=[123.675, 116.28, 103.53], pixel_std=[58.395, 57.12, 57.375]):
  279. # ----------------- Basic parameters -----------------
  280. self.img_size = img_size
  281. self.pixel_mean = pixel_mean # RGB format
  282. self.pixel_std = pixel_std # RGB format
  283. self.color_format = 'rgb'
  284. print("================= Pixel Statistics =================")
  285. print("Pixel mean: {}".format(self.pixel_mean))
  286. print("Pixel std: {}".format(self.pixel_std))
  287. # ----------------- Transforms -----------------
  288. self.transform = Compose([
  289. Resize(img_size=self.img_size),
  290. ConvertColorFormat(self.color_format),
  291. Normalize(self.pixel_mean, self.pixel_std),
  292. ToTensor()
  293. ])
  294. def __call__(self, image, target=None, mosaic=False):
  295. orig_h, orig_w = image.shape[:2]
  296. ratio = [self.img_size / orig_w, self.img_size / orig_h]
  297. image, target = self.transform(image, target)
  298. return image, target, ratio