ssd_augment.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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 color jitter
  48. class RandomDistort(object):
  49. def __init__(self,
  50. hue=[-18, 18, 0.5],
  51. saturation=[0.5, 1.5, 0.5],
  52. contrast=[0.5, 1.5, 0.5],
  53. brightness=[0.5, 1.5, 0.5],
  54. random_apply=True,
  55. count=4,
  56. random_channel=False,
  57. prob=1.0):
  58. super(RandomDistort, self).__init__()
  59. self.hue = hue
  60. self.saturation = saturation
  61. self.contrast = contrast
  62. self.brightness = brightness
  63. self.random_apply = random_apply
  64. self.count = count
  65. self.random_channel = random_channel
  66. self.prob = prob
  67. def apply_hue(self, image, target=None):
  68. if np.random.uniform(0., 1.) < self.prob:
  69. return image, target
  70. low, high, prob = self.hue
  71. image = image.astype(np.float32)
  72. # it works, but result differ from HSV version
  73. delta = np.random.uniform(low, high)
  74. u = np.cos(delta * np.pi)
  75. w = np.sin(delta * np.pi)
  76. bt = np.array([[1.0, 0.0, 0.0], [0.0, u, -w], [0.0, w, u]])
  77. tyiq = np.array([[0.299, 0.587, 0.114], [0.596, -0.274, -0.321],
  78. [0.211, -0.523, 0.311]])
  79. ityiq = np.array([[1.0, 0.956, 0.621], [1.0, -0.272, -0.647],
  80. [1.0, -1.107, 1.705]])
  81. t = np.dot(np.dot(ityiq, bt), tyiq).T
  82. image = np.dot(image, t)
  83. return image, target
  84. def apply_saturation(self, image, target=None):
  85. low, high, prob = self.saturation
  86. if np.random.uniform(0., 1.) < self.prob:
  87. return image, target
  88. delta = np.random.uniform(low, high)
  89. image = image.astype(np.float32)
  90. # it works, but result differ from HSV version
  91. gray = image * np.array([[[0.299, 0.587, 0.114]]], dtype=np.float32)
  92. gray = gray.sum(axis=2, keepdims=True)
  93. gray *= (1.0 - delta)
  94. image *= delta
  95. image += gray
  96. return image, target
  97. def apply_contrast(self, image, target=None):
  98. if np.random.uniform(0., 1.) < self.prob:
  99. return image, target
  100. low, high, prob = self.contrast
  101. delta = np.random.uniform(low, high)
  102. image = image.astype(np.float32)
  103. image *= delta
  104. return image, target
  105. def apply_brightness(self, image, target=None):
  106. if np.random.uniform(0., 1.) < self.prob:
  107. return image, target
  108. low, high, prob = self.brightness
  109. delta = np.random.uniform(low, high)
  110. image = image.astype(np.float32)
  111. image += delta
  112. return image, target
  113. def __call__(self, image, target=None):
  114. if random.random() > self.prob:
  115. return image, target
  116. if self.random_apply:
  117. functions = [
  118. self.apply_brightness, self.apply_contrast,
  119. self.apply_saturation, self.apply_hue
  120. ]
  121. distortions = np.random.permutation(functions)[:self.count]
  122. for func in distortions:
  123. image, target = func(image, target)
  124. return image, target
  125. image, target = self.apply_brightness(image, target)
  126. mode = np.random.randint(0, 2)
  127. if mode:
  128. image, target = self.apply_contrast(image, target)
  129. image, target = self.apply_saturation(image, target)
  130. image, target = self.apply_hue(image, target)
  131. if not mode:
  132. image, target = self.apply_contrast(image, target)
  133. if self.random_channel:
  134. if np.random.randint(0, 2):
  135. image = image[..., np.random.permutation(3)]
  136. return image, target
  137. ## Random scaling
  138. class RandomExpand(object):
  139. def __init__(self, fill_value) -> None:
  140. self.fill_value = fill_value
  141. def __call__(self, image, target=None):
  142. if random.randint(2):
  143. return image, target
  144. height, width, channels = image.shape
  145. ratio = random.uniform(1, 4)
  146. left = random.uniform(0, width*ratio - width)
  147. top = random.uniform(0, height*ratio - height)
  148. expand_image = np.ones(
  149. (int(height*ratio), int(width*ratio), channels),
  150. dtype=image.dtype) * self.fill_value
  151. expand_image[int(top):int(top + height),
  152. int(left):int(left + width)] = image
  153. image = expand_image
  154. boxes = target['boxes'].copy()
  155. boxes[:, :2] += (int(left), int(top))
  156. boxes[:, 2:] += (int(left), int(top))
  157. target['boxes'] = boxes
  158. return image, target
  159. ## Random IoU based Sample Crop
  160. class RandomIoUCrop(object):
  161. def __init__(self, p=0.5):
  162. self.p = p
  163. self.sample_options = (
  164. # sample a patch s.t. MIN jaccard w/ obj in .1,.3,.4,.7,.9
  165. (0.1, None),
  166. (0.3, None),
  167. (0.5, None),
  168. (0.7, None),
  169. (0.9, None),
  170. )
  171. def intersect(self, box_a, box_b):
  172. max_xy = np.minimum(box_a[:, 2:], box_b[2:])
  173. min_xy = np.maximum(box_a[:, :2], box_b[:2])
  174. inter = np.clip((max_xy - min_xy), a_min=0, a_max=np.inf)
  175. return inter[:, 0] * inter[:, 1]
  176. def compute_iou(self, box_a, box_b):
  177. inter = self.intersect(box_a, box_b)
  178. area_a = ((box_a[:, 2]-box_a[:, 0]) *
  179. (box_a[:, 3]-box_a[:, 1])) # [A,B]
  180. area_b = ((box_b[2]-box_b[0]) *
  181. (box_b[3]-box_b[1])) # [A,B]
  182. union = area_a + area_b - inter
  183. return inter / union # [A,B]
  184. def __call__(self, image, target=None):
  185. height, width, _ = image.shape
  186. # check target
  187. if len(target["boxes"]) == 0 or random.random() > self.p:
  188. return image, target
  189. while True:
  190. # randomly choose a mode
  191. sample_id = np.random.randint(len(self.sample_options))
  192. mode = self.sample_options[sample_id]
  193. if mode is None:
  194. return image, target
  195. boxes = target["boxes"]
  196. labels = target["labels"]
  197. min_iou, max_iou = mode
  198. if min_iou is None:
  199. min_iou = float('-inf')
  200. if max_iou is None:
  201. max_iou = float('inf')
  202. # max trails (50)
  203. for _ in range(50):
  204. current_image = image
  205. w = random.uniform(0.3 * width, width)
  206. h = random.uniform(0.3 * height, height)
  207. # aspect ratio constraint b/t .5 & 2
  208. if h / w < 0.5 or h / w > 2:
  209. continue
  210. left = random.uniform(width - w)
  211. top = random.uniform(height - h)
  212. # convert to integer rect x1,y1,x2,y2
  213. rect = np.array([int(left), int(top), int(left+w), int(top+h)])
  214. # calculate IoU (jaccard overlap) b/t the cropped and gt boxes
  215. overlap = self.compute_iou(boxes, rect)
  216. # is min and max overlap constraint satisfied? if not try again
  217. if overlap.min() < min_iou and max_iou < overlap.max():
  218. continue
  219. # cut the crop from the image
  220. current_image = current_image[rect[1]:rect[3], rect[0]:rect[2],
  221. :]
  222. # keep overlap with gt box IF center in sampled patch
  223. centers = (boxes[:, :2] + boxes[:, 2:]) / 2.0
  224. # mask in all gt boxes that above and to the left of centers
  225. m1 = (rect[0] < centers[:, 0]) * (rect[1] < centers[:, 1])
  226. # mask in all gt boxes that under and to the right of centers
  227. m2 = (rect[2] > centers[:, 0]) * (rect[3] > centers[:, 1])
  228. # mask in that both m1 and m2 are true
  229. mask = m1 * m2
  230. # have any valid boxes? try again if not
  231. if not mask.any():
  232. continue
  233. # take only matching gt boxes
  234. current_boxes = boxes[mask, :].copy()
  235. # take only matching gt labels
  236. current_labels = labels[mask]
  237. # should we use the box left and top corner or the crop's
  238. current_boxes[:, :2] = np.maximum(current_boxes[:, :2],
  239. rect[:2])
  240. # adjust to crop (by substracting crop's left,top)
  241. current_boxes[:, :2] -= rect[:2]
  242. current_boxes[:, 2:] = np.minimum(current_boxes[:, 2:],
  243. rect[2:])
  244. # adjust to crop (by substracting crop's left,top)
  245. current_boxes[:, 2:] -= rect[:2]
  246. # update target
  247. target["boxes"] = current_boxes
  248. target["labels"] = current_labels
  249. return current_image, target
  250. ## Random JitterCrop
  251. class RandomJitterCrop(object):
  252. """Jitter and crop the image and box."""
  253. def __init__(self, fill_value, p=0.5, jitter_ratio=0.3):
  254. super().__init__()
  255. self.p = p
  256. self.jitter_ratio = jitter_ratio
  257. self.fill_value = fill_value
  258. def crop(self, image, pleft, pright, ptop, pbot, output_size):
  259. oh, ow = image.shape[:2]
  260. swidth, sheight = output_size
  261. src_rect = [pleft, ptop, swidth + pleft,
  262. sheight + ptop] # x1,y1,x2,y2
  263. img_rect = [0, 0, ow, oh]
  264. # rect intersection
  265. new_src_rect = [max(src_rect[0], img_rect[0]),
  266. max(src_rect[1], img_rect[1]),
  267. min(src_rect[2], img_rect[2]),
  268. min(src_rect[3], img_rect[3])]
  269. dst_rect = [max(0, -pleft),
  270. max(0, -ptop),
  271. max(0, -pleft) + new_src_rect[2] - new_src_rect[0],
  272. max(0, -ptop) + new_src_rect[3] - new_src_rect[1]]
  273. # crop the image
  274. cropped = np.ones([sheight, swidth, 3], dtype=image.dtype) * self.fill_value
  275. # cropped[:, :, ] = np.mean(image, axis=(0, 1))
  276. cropped[dst_rect[1]:dst_rect[3], dst_rect[0]:dst_rect[2]] = \
  277. image[new_src_rect[1]:new_src_rect[3],
  278. new_src_rect[0]:new_src_rect[2]]
  279. return cropped
  280. def __call__(self, image, target=None):
  281. if random.random() > self.p:
  282. return image, target
  283. else:
  284. oh, ow = image.shape[:2]
  285. dw = int(ow * self.jitter_ratio)
  286. dh = int(oh * self.jitter_ratio)
  287. pleft = np.random.randint(-dw, dw)
  288. pright = np.random.randint(-dw, dw)
  289. ptop = np.random.randint(-dh, dh)
  290. pbot = np.random.randint(-dh, dh)
  291. swidth = ow - pleft - pright
  292. sheight = oh - ptop - pbot
  293. output_size = (swidth, sheight)
  294. # crop image
  295. cropped_image = self.crop(image=image,
  296. pleft=pleft,
  297. pright=pright,
  298. ptop=ptop,
  299. pbot=pbot,
  300. output_size=output_size)
  301. # crop bbox
  302. if target is not None:
  303. bboxes = target['boxes'].copy()
  304. coords_offset = np.array([pleft, ptop], dtype=np.float32)
  305. bboxes[..., [0, 2]] = bboxes[..., [0, 2]] - coords_offset[0]
  306. bboxes[..., [1, 3]] = bboxes[..., [1, 3]] - coords_offset[1]
  307. swidth, sheight = output_size
  308. bboxes[..., [0, 2]] = np.clip(bboxes[..., [0, 2]], 0, swidth - 1)
  309. bboxes[..., [1, 3]] = np.clip(bboxes[..., [1, 3]], 0, sheight - 1)
  310. target['boxes'] = bboxes
  311. return cropped_image, target
  312. ## Random HFlip
  313. class RandomHorizontalFlip(object):
  314. def __init__(self, p=0.5):
  315. self.p = p
  316. def __call__(self, image, target=None):
  317. if random.random() < self.p:
  318. orig_h, orig_w = image.shape[:2]
  319. image = image[:, ::-1]
  320. if target is not None:
  321. if "boxes" in target:
  322. boxes = target["boxes"].copy()
  323. boxes[..., [0, 2]] = orig_w - boxes[..., [2, 0]]
  324. target["boxes"] = boxes
  325. return image, target
  326. ## Resize tensor image
  327. class Resize(object):
  328. def __init__(self, img_size=640):
  329. self.img_size = img_size
  330. def __call__(self, image, target=None):
  331. orig_h, orig_w = image.shape[:2]
  332. # resize
  333. image = cv2.resize(image, (self.img_size, self.img_size)).astype(np.float32)
  334. img_h, img_w = image.shape[:2]
  335. # rescale bboxes
  336. if target is not None:
  337. boxes = target["boxes"].astype(np.float32)
  338. boxes[:, [0, 2]] = boxes[:, [0, 2]] / orig_w * img_w
  339. boxes[:, [1, 3]] = boxes[:, [1, 3]] / orig_h * img_h
  340. target["boxes"] = boxes
  341. return image, target
  342. ## Normalize tensor image
  343. class Normalize(object):
  344. def __init__(self, pixel_mean, pixel_std, normalize_coords=False):
  345. self.pixel_mean = pixel_mean
  346. self.pixel_std = pixel_std
  347. self.normalize_coords = normalize_coords
  348. def __call__(self, image, target=None):
  349. # normalize image
  350. image = (image - self.pixel_mean) / self.pixel_std
  351. # normalize bbox
  352. if target is not None and self.normalize_coords:
  353. img_h, img_w = image.shape[:2]
  354. target["boxes"][..., [0, 2]] = target["boxes"][..., [0, 2]] / float(img_w)
  355. target["boxes"][..., [1, 3]] = target["boxes"][..., [1, 3]] / float(img_h)
  356. return image, target
  357. ## Convert ndarray to torch.Tensor
  358. class ToTensor(object):
  359. def __call__(self, image, target=None):
  360. # Convert torch.Tensor
  361. image = torch.from_numpy(image).permute(2, 0, 1).contiguous().float()
  362. if target is not None:
  363. target["boxes"] = torch.as_tensor(target["boxes"]).float()
  364. target["labels"] = torch.as_tensor(target["labels"]).long()
  365. return image, target
  366. ## Convert BBox foramt
  367. class ConvertBoxFormat(object):
  368. def __init__(self, box_format="xyxy"):
  369. self.box_format = box_format
  370. def __call__(self, image, target=None):
  371. # convert box format
  372. if self.box_format == "xyxy" or target is None:
  373. pass
  374. elif self.box_format == "xywh":
  375. target = target.copy()
  376. if "boxes" in target:
  377. boxes_xyxy = target["boxes"]
  378. boxes_xywh = torch.zeros_like(boxes_xyxy)
  379. boxes_xywh[..., :2] = (boxes_xyxy[..., :2] + boxes_xyxy[..., 2:]) * 0.5 # cxcy
  380. boxes_xywh[..., 2:] = boxes_xyxy[..., 2:] - boxes_xyxy[..., :2] # bwbh
  381. target["boxes"] = boxes_xywh
  382. else:
  383. raise NotImplementedError("Unknown box format: {}".format(self.box_format))
  384. return image, target
  385. # ------------------------- Preprocessers -------------------------
  386. ## Transform for Train
  387. class SSDAugmentation(object):
  388. def __init__(self,
  389. img_size = 640,
  390. pixel_mean = [123.675, 116.28, 103.53],
  391. pixel_std = [58.395, 57.12, 57.375],
  392. box_format = 'xywh',
  393. normalize_coords = False):
  394. # ----------------- Basic parameters -----------------
  395. self.img_size = img_size
  396. self.box_format = box_format
  397. self.pixel_mean = pixel_mean # RGB format
  398. self.pixel_std = pixel_std # RGB format
  399. self.normalize_coords = normalize_coords
  400. self.color_format = 'rgb'
  401. print("================= Pixel Statistics =================")
  402. print("Pixel mean: {}".format(self.pixel_mean))
  403. print("Pixel std: {}".format(self.pixel_std))
  404. # ----------------- Transforms -----------------
  405. self.augment = Compose([
  406. RandomDistort(prob=0.8),
  407. RandomExpand(fill_value=self.pixel_mean[::-1]),
  408. RandomIoUCrop(p=0.8),
  409. RandomHorizontalFlip(p=0.5),
  410. Resize(img_size=self.img_size),
  411. ConvertColorFormat(self.color_format),
  412. Normalize(self.pixel_mean, self.pixel_std, normalize_coords),
  413. ToTensor(),
  414. ConvertBoxFormat(self.box_format),
  415. ])
  416. def __call__(self, image, target, mosaic=False):
  417. orig_h, orig_w = image.shape[:2]
  418. ratio = [self.img_size / orig_w, self.img_size / orig_h]
  419. image, target = self.augment(image, target)
  420. return image, target, ratio
  421. ## Transform for Eval
  422. class SSDBaseTransform(object):
  423. def __init__(self,
  424. img_size = 640,
  425. pixel_mean = [123.675, 116.28, 103.53],
  426. pixel_std = [58.395, 57.12, 57.375],
  427. box_format = 'xywh',
  428. normalize_coords = False):
  429. # ----------------- Basic parameters -----------------
  430. self.img_size = img_size
  431. self.box_format = box_format
  432. self.pixel_mean = pixel_mean # RGB format
  433. self.pixel_std = pixel_std # RGB format
  434. self.normalize_coords = normalize_coords
  435. self.color_format = 'rgb'
  436. print("================= Pixel Statistics =================")
  437. print("Pixel mean: {}".format(self.pixel_mean))
  438. print("Pixel std: {}".format(self.pixel_std))
  439. # ----------------- Transforms -----------------
  440. self.transform = Compose([
  441. Resize(img_size=self.img_size),
  442. ConvertColorFormat(self.color_format),
  443. Normalize(self.pixel_mean, self.pixel_std, self.normalize_coords),
  444. ToTensor(),
  445. ConvertBoxFormat(self.box_format),
  446. ])
  447. def __call__(self, image, target=None, mosaic=False):
  448. orig_h, orig_w = image.shape[:2]
  449. ratio = [self.img_size / orig_w, self.img_size / orig_h]
  450. image, target = self.transform(image, target)
  451. return image, target, ratio