ssd_augment.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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. None,
  171. )
  172. def intersect(self, box_a, box_b):
  173. max_xy = np.minimum(box_a[:, 2:], box_b[2:])
  174. min_xy = np.maximum(box_a[:, :2], box_b[:2])
  175. inter = np.clip((max_xy - min_xy), a_min=0, a_max=np.inf)
  176. return inter[:, 0] * inter[:, 1]
  177. def compute_iou(self, box_a, box_b):
  178. inter = self.intersect(box_a, box_b)
  179. area_a = ((box_a[:, 2]-box_a[:, 0]) *
  180. (box_a[:, 3]-box_a[:, 1])) # [A,B]
  181. area_b = ((box_b[2]-box_b[0]) *
  182. (box_b[3]-box_b[1])) # [A,B]
  183. union = area_a + area_b - inter
  184. return inter / union # [A,B]
  185. def __call__(self, image, target=None):
  186. height, width, _ = image.shape
  187. # check target
  188. if len(target["boxes"]) == 0 or random.random() > self.p:
  189. return image, target
  190. while True:
  191. # randomly choose a mode
  192. sample_id = np.random.randint(len(self.sample_options))
  193. mode = self.sample_options[sample_id]
  194. if mode is None:
  195. return image, target
  196. boxes = target["boxes"]
  197. labels = target["labels"]
  198. min_iou, max_iou = mode
  199. if min_iou is None:
  200. min_iou = float('-inf')
  201. if max_iou is None:
  202. max_iou = float('inf')
  203. # max trails (50)
  204. for _ in range(50):
  205. current_image = image
  206. w = random.uniform(0.3 * width, width)
  207. h = random.uniform(0.3 * height, height)
  208. # aspect ratio constraint b/t .5 & 2
  209. if h / w < 0.5 or h / w > 2:
  210. continue
  211. left = random.uniform(width - w)
  212. top = random.uniform(height - h)
  213. # convert to integer rect x1,y1,x2,y2
  214. rect = np.array([int(left), int(top), int(left+w), int(top+h)])
  215. # calculate IoU (jaccard overlap) b/t the cropped and gt boxes
  216. overlap = self.compute_iou(boxes, rect)
  217. # is min and max overlap constraint satisfied? if not try again
  218. if overlap.min() < min_iou and max_iou < overlap.max():
  219. continue
  220. # cut the crop from the image
  221. current_image = current_image[rect[1]:rect[3], rect[0]:rect[2],
  222. :]
  223. # keep overlap with gt box IF center in sampled patch
  224. centers = (boxes[:, :2] + boxes[:, 2:]) / 2.0
  225. # mask in all gt boxes that above and to the left of centers
  226. m1 = (rect[0] < centers[:, 0]) * (rect[1] < centers[:, 1])
  227. # mask in all gt boxes that under and to the right of centers
  228. m2 = (rect[2] > centers[:, 0]) * (rect[3] > centers[:, 1])
  229. # mask in that both m1 and m2 are true
  230. mask = m1 * m2
  231. # have any valid boxes? try again if not
  232. if not mask.any():
  233. continue
  234. # take only matching gt boxes
  235. current_boxes = boxes[mask, :].copy()
  236. # take only matching gt labels
  237. current_labels = labels[mask]
  238. # should we use the box left and top corner or the crop's
  239. current_boxes[:, :2] = np.maximum(current_boxes[:, :2],
  240. rect[:2])
  241. # adjust to crop (by substracting crop's left,top)
  242. current_boxes[:, :2] -= rect[:2]
  243. current_boxes[:, 2:] = np.minimum(current_boxes[:, 2:],
  244. rect[2:])
  245. # adjust to crop (by substracting crop's left,top)
  246. current_boxes[:, 2:] -= rect[:2]
  247. # update target
  248. target["boxes"] = current_boxes
  249. target["labels"] = current_labels
  250. return current_image, target
  251. ## Random JitterCrop
  252. class RandomJitterCrop(object):
  253. """Jitter and crop the image and box."""
  254. def __init__(self, fill_value, p=0.5, jitter_ratio=0.3):
  255. super().__init__()
  256. self.p = p
  257. self.jitter_ratio = jitter_ratio
  258. self.fill_value = fill_value
  259. def crop(self, image, pleft, pright, ptop, pbot, output_size):
  260. oh, ow = image.shape[:2]
  261. swidth, sheight = output_size
  262. src_rect = [pleft, ptop, swidth + pleft,
  263. sheight + ptop] # x1,y1,x2,y2
  264. img_rect = [0, 0, ow, oh]
  265. # rect intersection
  266. new_src_rect = [max(src_rect[0], img_rect[0]),
  267. max(src_rect[1], img_rect[1]),
  268. min(src_rect[2], img_rect[2]),
  269. min(src_rect[3], img_rect[3])]
  270. dst_rect = [max(0, -pleft),
  271. max(0, -ptop),
  272. max(0, -pleft) + new_src_rect[2] - new_src_rect[0],
  273. max(0, -ptop) + new_src_rect[3] - new_src_rect[1]]
  274. # crop the image
  275. cropped = np.ones([sheight, swidth, 3], dtype=image.dtype) * self.fill_value
  276. # cropped[:, :, ] = np.mean(image, axis=(0, 1))
  277. cropped[dst_rect[1]:dst_rect[3], dst_rect[0]:dst_rect[2]] = \
  278. image[new_src_rect[1]:new_src_rect[3],
  279. new_src_rect[0]:new_src_rect[2]]
  280. return cropped
  281. def __call__(self, image, target=None):
  282. if random.random() > self.p:
  283. return image, target
  284. else:
  285. oh, ow = image.shape[:2]
  286. dw = int(ow * self.jitter_ratio)
  287. dh = int(oh * self.jitter_ratio)
  288. pleft = np.random.randint(-dw, dw)
  289. pright = np.random.randint(-dw, dw)
  290. ptop = np.random.randint(-dh, dh)
  291. pbot = np.random.randint(-dh, dh)
  292. swidth = ow - pleft - pright
  293. sheight = oh - ptop - pbot
  294. output_size = (swidth, sheight)
  295. # crop image
  296. cropped_image = self.crop(image=image,
  297. pleft=pleft,
  298. pright=pright,
  299. ptop=ptop,
  300. pbot=pbot,
  301. output_size=output_size)
  302. # crop bbox
  303. if target is not None:
  304. bboxes = target['boxes'].copy()
  305. coords_offset = np.array([pleft, ptop], dtype=np.float32)
  306. bboxes[..., [0, 2]] = bboxes[..., [0, 2]] - coords_offset[0]
  307. bboxes[..., [1, 3]] = bboxes[..., [1, 3]] - coords_offset[1]
  308. swidth, sheight = output_size
  309. bboxes[..., [0, 2]] = np.clip(bboxes[..., [0, 2]], 0, swidth - 1)
  310. bboxes[..., [1, 3]] = np.clip(bboxes[..., [1, 3]], 0, sheight - 1)
  311. target['boxes'] = bboxes
  312. return cropped_image, target
  313. ## Random HFlip
  314. class RandomHorizontalFlip(object):
  315. def __init__(self, p=0.5):
  316. self.p = p
  317. def __call__(self, image, target=None):
  318. if random.random() < self.p:
  319. orig_h, orig_w = image.shape[:2]
  320. image = image[:, ::-1]
  321. if target is not None:
  322. if "boxes" in target:
  323. boxes = target["boxes"].copy()
  324. boxes[..., [0, 2]] = orig_w - boxes[..., [2, 0]]
  325. target["boxes"] = boxes
  326. return image, target
  327. ## Resize tensor image
  328. class Resize(object):
  329. def __init__(self, img_size=640):
  330. self.img_size = img_size
  331. def __call__(self, image, target=None):
  332. orig_h, orig_w = image.shape[:2]
  333. # resize
  334. image = cv2.resize(image, (self.img_size, self.img_size)).astype(np.float32)
  335. img_h, img_w = image.shape[:2]
  336. # rescale bboxes
  337. if target is not None:
  338. boxes = target["boxes"].astype(np.float32)
  339. boxes[:, [0, 2]] = boxes[:, [0, 2]] / orig_w * img_w
  340. boxes[:, [1, 3]] = boxes[:, [1, 3]] / orig_h * img_h
  341. target["boxes"] = boxes
  342. return image, target
  343. ## Normalize tensor image
  344. class Normalize(object):
  345. def __init__(self, pixel_mean, pixel_std, normalize_coords=False):
  346. self.pixel_mean = pixel_mean
  347. self.pixel_std = pixel_std
  348. self.normalize_coords = normalize_coords
  349. def __call__(self, image, target=None):
  350. # normalize image
  351. image = (image - self.pixel_mean) / self.pixel_std
  352. # normalize bbox
  353. if target is not None and self.normalize_coords:
  354. img_h, img_w = image.shape[:2]
  355. target["boxes"][..., [0, 2]] = target["boxes"][..., [0, 2]] / float(img_w)
  356. target["boxes"][..., [1, 3]] = target["boxes"][..., [1, 3]] / float(img_h)
  357. return image, target
  358. ## Convert ndarray to torch.Tensor
  359. class ToTensor(object):
  360. def __call__(self, image, target=None):
  361. # Convert torch.Tensor
  362. image = torch.from_numpy(image).permute(2, 0, 1).contiguous().float()
  363. if target is not None:
  364. target["boxes"] = torch.as_tensor(target["boxes"]).float()
  365. target["labels"] = torch.as_tensor(target["labels"]).long()
  366. return image, target
  367. ## Convert BBox foramt
  368. class ConvertBoxFormat(object):
  369. def __init__(self, box_format="xyxy"):
  370. self.box_format = box_format
  371. def __call__(self, image, target=None):
  372. # convert box format
  373. if self.box_format == "xyxy" or target is None:
  374. pass
  375. elif self.box_format == "xywh":
  376. target = target.copy()
  377. if "boxes" in target:
  378. boxes_xyxy = target["boxes"]
  379. boxes_xywh = torch.zeros_like(boxes_xyxy)
  380. boxes_xywh[..., :2] = (boxes_xyxy[..., :2] + boxes_xyxy[..., 2:]) * 0.5 # cxcy
  381. boxes_xywh[..., 2:] = boxes_xyxy[..., 2:] - boxes_xyxy[..., :2] # bwbh
  382. target["boxes"] = boxes_xywh
  383. else:
  384. raise NotImplementedError("Unknown box format: {}".format(self.box_format))
  385. return image, target
  386. # ------------------------- Preprocessers -------------------------
  387. ## Transform for Train
  388. class SSDAugmentation(object):
  389. def __init__(self,
  390. img_size = 640,
  391. pixel_mean = [123.675, 116.28, 103.53],
  392. pixel_std = [58.395, 57.12, 57.375],
  393. box_format = 'xywh',
  394. normalize_coords = False):
  395. # ----------------- Basic parameters -----------------
  396. self.img_size = img_size
  397. self.box_format = box_format
  398. self.pixel_mean = pixel_mean # RGB format
  399. self.pixel_std = pixel_std # RGB format
  400. self.normalize_coords = normalize_coords
  401. self.color_format = 'rgb'
  402. print("================= Pixel Statistics =================")
  403. print("Pixel mean: {}".format(self.pixel_mean))
  404. print("Pixel std: {}".format(self.pixel_std))
  405. # ----------------- Transforms -----------------
  406. self.augment = Compose([
  407. RandomDistort(prob=0.5),
  408. RandomExpand(fill_value=self.pixel_mean[::-1]),
  409. RandomIoUCrop(p=0.8),
  410. RandomHorizontalFlip(p=0.5),
  411. Resize(img_size=self.img_size),
  412. ConvertColorFormat(self.color_format),
  413. Normalize(self.pixel_mean, self.pixel_std, normalize_coords),
  414. ToTensor(),
  415. ConvertBoxFormat(self.box_format),
  416. ])
  417. def __call__(self, image, target, mosaic=False):
  418. orig_h, orig_w = image.shape[:2]
  419. ratio = [self.img_size / orig_w, self.img_size / orig_h]
  420. image, target = self.augment(image, target)
  421. return image, target, ratio
  422. ## Transform for Eval
  423. class SSDBaseTransform(object):
  424. def __init__(self,
  425. img_size = 640,
  426. pixel_mean = [123.675, 116.28, 103.53],
  427. pixel_std = [58.395, 57.12, 57.375],
  428. box_format = 'xywh',
  429. normalize_coords = False):
  430. # ----------------- Basic parameters -----------------
  431. self.img_size = img_size
  432. self.box_format = box_format
  433. self.pixel_mean = pixel_mean # RGB format
  434. self.pixel_std = pixel_std # RGB format
  435. self.normalize_coords = normalize_coords
  436. self.color_format = 'rgb'
  437. print("================= Pixel Statistics =================")
  438. print("Pixel mean: {}".format(self.pixel_mean))
  439. print("Pixel std: {}".format(self.pixel_std))
  440. # ----------------- Transforms -----------------
  441. self.transform = Compose([
  442. Resize(img_size=self.img_size),
  443. ConvertColorFormat(self.color_format),
  444. Normalize(self.pixel_mean, self.pixel_std, self.normalize_coords),
  445. ToTensor(),
  446. ConvertBoxFormat(self.box_format),
  447. ])
  448. def __call__(self, image, target=None, mosaic=False):
  449. orig_h, orig_w = image.shape[:2]
  450. ratio = [self.img_size / orig_w, self.img_size / orig_h]
  451. image, target = self.transform(image, target)
  452. return image, target, ratio
  453. if __name__ == "__main__":
  454. image_path = "voc_image.jpg"
  455. is_train = True
  456. if is_train:
  457. ssd_augment = SSDAugmentation(img_size=512,
  458. pixel_mean=[0., 0., 0.],
  459. pixel_std=[255., 255., 255.],
  460. box_format="xyxy",
  461. normalize_coords=False,
  462. )
  463. else:
  464. ssd_augment = SSDBaseTransform(img_size=512,
  465. pixel_mean=[0., 0., 0.],
  466. pixel_std=[255., 255., 255.],
  467. box_format="xyxy",
  468. normalize_coords=False,
  469. )
  470. image = cv2.imread(image_path)
  471. cv2.imshow("original image", image)
  472. cv2.waitKey(0)
  473. target = {
  474. "boxes": np.array([[86, 96, 256, 425], [132, 71, 243, 282]], dtype=np.float32),
  475. "labels": np.array([12, 14], dtype=np.int32),
  476. }
  477. image, target, _ = ssd_augment(image, target)
  478. # [c, h, w] -> [h, w, c]
  479. image = image.permute(1, 2, 0).contiguous().numpy()
  480. image = np.clip(image * 255, 0, 255).astype(np.uint8)
  481. # to bgr
  482. image = image[:, :, (2, 1, 0)]
  483. cv2.imshow("processed image", image)
  484. cv2.waitKey(0)