ssd_augment.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. # ------------------------------------------------------------
  2. # Data preprocessor for SSD
  3. # ------------------------------------------------------------
  4. import cv2
  5. import numpy as np
  6. import torch
  7. from numpy import random
  8. # ------------------------- Augmentations -------------------------
  9. class Compose(object):
  10. """Composes several augmentations together.
  11. Args:
  12. transforms (List[Transform]): list of transforms to compose.
  13. Example:
  14. >>> augmentations.Compose([
  15. >>> transforms.CenterCrop(10),
  16. >>> transforms.ToTensor(),
  17. >>> ])
  18. """
  19. def __init__(self, transforms):
  20. self.transforms = transforms
  21. def __call__(self, img, boxes=None, labels=None):
  22. for t in self.transforms:
  23. img, boxes, labels = t(img, boxes, labels)
  24. return img, boxes, labels
  25. ## Convert Image to float type
  26. class ConvertFromInts(object):
  27. def __call__(self, image, boxes=None, labels=None):
  28. return image.astype(np.float32), boxes, labels
  29. ## Convert color format
  30. class ConvertColor(object):
  31. def __init__(self, current='BGR', transform='HSV'):
  32. self.transform = transform
  33. self.current = current
  34. def __call__(self, image, boxes=None, labels=None):
  35. if self.current == 'BGR' and self.transform == 'HSV':
  36. image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  37. elif self.current == 'HSV' and self.transform == 'BGR':
  38. image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)
  39. else:
  40. raise NotImplementedError
  41. return image, boxes, labels
  42. ## Resize image
  43. class Resize(object):
  44. def __init__(self, img_size=640):
  45. self.img_size = img_size
  46. def __call__(self, image, boxes=None, labels=None):
  47. orig_h, orig_w = image.shape[:2]
  48. # resize
  49. image = cv2.resize(image, (self.img_size, self.img_size)).astype(np.float32)
  50. img_h, img_w = image.shape[:2]
  51. # rescale bbox
  52. if boxes is not None:
  53. boxes[..., [0, 2]] = boxes[..., [0, 2]] / orig_w * img_w
  54. boxes[..., [1, 3]] = boxes[..., [1, 3]] / orig_h * img_h
  55. return image, boxes, labels
  56. ## Random Saturation
  57. class RandomSaturation(object):
  58. def __init__(self, lower=0.5, upper=1.5):
  59. self.lower = lower
  60. self.upper = upper
  61. assert self.upper >= self.lower, "contrast upper must be >= lower."
  62. assert self.lower >= 0, "contrast lower must be non-negative."
  63. def __call__(self, image, boxes=None, labels=None):
  64. if random.randint(2):
  65. image[:, :, 1] *= random.uniform(self.lower, self.upper)
  66. return image, boxes, labels
  67. ## Random Hue
  68. class RandomHue(object):
  69. def __init__(self, delta=18.0):
  70. assert delta >= 0.0 and delta <= 360.0
  71. self.delta = delta
  72. def __call__(self, image, boxes=None, labels=None):
  73. if random.randint(2):
  74. image[:, :, 0] += random.uniform(-self.delta, self.delta)
  75. image[:, :, 0][image[:, :, 0] > 360.0] -= 360.0
  76. image[:, :, 0][image[:, :, 0] < 0.0] += 360.0
  77. return image, boxes, labels
  78. ## Random Lighting noise
  79. class RandomLightingNoise(object):
  80. def __init__(self):
  81. self.perms = ((0, 1, 2), (0, 2, 1),
  82. (1, 0, 2), (1, 2, 0),
  83. (2, 0, 1), (2, 1, 0))
  84. def __call__(self, image, boxes=None, labels=None):
  85. if random.randint(2):
  86. swap = self.perms[random.randint(len(self.perms))]
  87. shuffle = SwapChannels(swap) # shuffle channels
  88. image = shuffle(image)
  89. return image, boxes, labels
  90. ## Random Contrast
  91. class RandomContrast(object):
  92. def __init__(self, lower=0.5, upper=1.5):
  93. self.lower = lower
  94. self.upper = upper
  95. assert self.upper >= self.lower, "contrast upper must be >= lower."
  96. assert self.lower >= 0, "contrast lower must be non-negative."
  97. # expects float image
  98. def __call__(self, image, boxes=None, labels=None):
  99. if random.randint(2):
  100. alpha = random.uniform(self.lower, self.upper)
  101. image *= alpha
  102. return image, boxes, labels
  103. ## Random Brightness
  104. class RandomBrightness(object):
  105. def __init__(self, delta=32):
  106. assert delta >= 0.0
  107. assert delta <= 255.0
  108. self.delta = delta
  109. def __call__(self, image, boxes=None, labels=None):
  110. if random.randint(2):
  111. delta = random.uniform(-self.delta, self.delta)
  112. image += delta
  113. return image, boxes, labels
  114. ## Random SampleCrop
  115. class RandomSampleCrop(object):
  116. """Crop
  117. Arguments:
  118. img (Image): the image being input during training
  119. boxes (Tensor): the original bounding boxes in pt form
  120. labels (Tensor): the class labels for each bbox
  121. mode (float tuple): the min and max jaccard overlaps
  122. Return:
  123. (img, boxes, classes)
  124. img (Image): the cropped image
  125. boxes (Tensor): the adjusted bounding boxes in pt form
  126. labels (Tensor): the class labels for each bbox
  127. """
  128. def __init__(self):
  129. self.sample_options = (
  130. # using entire original input image
  131. None,
  132. # sample a patch s.t. MIN jaccard w/ obj in .1,.3,.4,.7,.9
  133. (0.1, None),
  134. (0.3, None),
  135. (0.7, None),
  136. (0.9, None),
  137. # randomly sample a patch
  138. (None, None),
  139. )
  140. def intersect(self, box_a, box_b):
  141. max_xy = np.minimum(box_a[:, 2:], box_b[2:])
  142. min_xy = np.maximum(box_a[:, :2], box_b[:2])
  143. inter = np.clip((max_xy - min_xy), a_min=0, a_max=np.inf)
  144. return inter[:, 0] * inter[:, 1]
  145. def compute_iou(self, box_a, box_b):
  146. inter = self.intersect(box_a, box_b)
  147. area_a = ((box_a[:, 2]-box_a[:, 0]) *
  148. (box_a[:, 3]-box_a[:, 1])) # [A,B]
  149. area_b = ((box_b[2]-box_b[0]) *
  150. (box_b[3]-box_b[1])) # [A,B]
  151. union = area_a + area_b - inter
  152. return inter / union # [A,B]
  153. def __call__(self, image, boxes=None, labels=None):
  154. height, width, _ = image.shape
  155. # check
  156. if len(boxes) == 0:
  157. return image, boxes, labels
  158. while True:
  159. # randomly choose a mode
  160. sample_id = np.random.randint(len(self.sample_options))
  161. mode = self.sample_options[sample_id]
  162. if mode is None:
  163. return image, boxes, labels
  164. min_iou, max_iou = mode
  165. if min_iou is None:
  166. min_iou = float('-inf')
  167. if max_iou is None:
  168. max_iou = float('inf')
  169. # max trails (50)
  170. for _ in range(50):
  171. current_image = image
  172. w = random.uniform(0.3 * width, width)
  173. h = random.uniform(0.3 * height, height)
  174. # aspect ratio constraint b/t .5 & 2
  175. if h / w < 0.5 or h / w > 2:
  176. continue
  177. left = random.uniform(width - w)
  178. top = random.uniform(height - h)
  179. # convert to integer rect x1,y1,x2,y2
  180. rect = np.array([int(left), int(top), int(left+w), int(top+h)])
  181. # calculate IoU (jaccard overlap) b/t the cropped and gt boxes
  182. overlap = self.compute_iou(boxes, rect)
  183. # is min and max overlap constraint satisfied? if not try again
  184. if overlap.min() < min_iou and max_iou < overlap.max():
  185. continue
  186. # cut the crop from the image
  187. current_image = current_image[rect[1]:rect[3], rect[0]:rect[2],
  188. :]
  189. # keep overlap with gt box IF center in sampled patch
  190. centers = (boxes[:, :2] + boxes[:, 2:]) / 2.0
  191. # mask in all gt boxes that above and to the left of centers
  192. m1 = (rect[0] < centers[:, 0]) * (rect[1] < centers[:, 1])
  193. # mask in all gt boxes that under and to the right of centers
  194. m2 = (rect[2] > centers[:, 0]) * (rect[3] > centers[:, 1])
  195. # mask in that both m1 and m2 are true
  196. mask = m1 * m2
  197. # have any valid boxes? try again if not
  198. if not mask.any():
  199. continue
  200. # take only matching gt boxes
  201. current_boxes = boxes[mask, :].copy()
  202. # take only matching gt labels
  203. current_labels = labels[mask]
  204. # should we use the box left and top corner or the crop's
  205. current_boxes[:, :2] = np.maximum(current_boxes[:, :2],
  206. rect[:2])
  207. # adjust to crop (by substracting crop's left,top)
  208. current_boxes[:, :2] -= rect[:2]
  209. current_boxes[:, 2:] = np.minimum(current_boxes[:, 2:],
  210. rect[2:])
  211. # adjust to crop (by substracting crop's left,top)
  212. current_boxes[:, 2:] -= rect[:2]
  213. return current_image, current_boxes, current_labels
  214. ## Random scaling
  215. class Expand(object):
  216. def __call__(self, image, boxes, labels):
  217. if random.randint(2):
  218. return image, boxes, labels
  219. height, width, depth = image.shape
  220. ratio = random.uniform(1, 4)
  221. left = random.uniform(0, width*ratio - width)
  222. top = random.uniform(0, height*ratio - height)
  223. expand_image = np.zeros(
  224. (int(height*ratio), int(width*ratio), depth),
  225. dtype=image.dtype)
  226. expand_image[int(top):int(top + height),
  227. int(left):int(left + width)] = image
  228. image = expand_image
  229. boxes = boxes.copy()
  230. boxes[:, :2] += (int(left), int(top))
  231. boxes[:, 2:] += (int(left), int(top))
  232. return image, boxes, labels
  233. ## Random HFlip
  234. class RandomHorizontalFlip(object):
  235. def __call__(self, image, boxes, classes):
  236. _, width, _ = image.shape
  237. if random.randint(2):
  238. image = image[:, ::-1]
  239. boxes = boxes.copy()
  240. boxes[:, 0::2] = width - boxes[:, 2::-2]
  241. return image, boxes, classes
  242. ## Random swap channels
  243. class SwapChannels(object):
  244. """Transforms a tensorized image by swapping the channels in the order
  245. specified in the swap tuple.
  246. Args:
  247. swaps (int triple): final order of channels
  248. eg: (2, 1, 0)
  249. """
  250. def __init__(self, swaps):
  251. self.swaps = swaps
  252. def __call__(self, image):
  253. """
  254. Args:
  255. image (Tensor): image tensor to be transformed
  256. Return:
  257. a tensor with channels swapped according to swap
  258. """
  259. # if torch.is_tensor(image):
  260. # image = image.data.cpu().numpy()
  261. # else:
  262. # image = np.array(image)
  263. image = image[:, :, self.swaps]
  264. return image
  265. ## Random color jitter
  266. class PhotometricDistort(object):
  267. def __init__(self):
  268. self.pd = [
  269. RandomContrast(),
  270. ConvertColor(transform='HSV'),
  271. RandomSaturation(),
  272. RandomHue(),
  273. ConvertColor(current='HSV', transform='BGR'),
  274. RandomContrast()
  275. ]
  276. self.rand_brightness = RandomBrightness()
  277. def __call__(self, image, boxes, labels):
  278. im = image.copy()
  279. im, boxes, labels = self.rand_brightness(im, boxes, labels)
  280. if random.randint(2):
  281. distort = Compose(self.pd[:-1])
  282. else:
  283. distort = Compose(self.pd[1:])
  284. im, boxes, labels = distort(im, boxes, labels)
  285. return im, boxes, labels
  286. # ------------------------- Preprocessers -------------------------
  287. ## SSD-style Augmentation
  288. class SSDAugmentation(object):
  289. def __init__(self, img_size=640):
  290. self.img_size = img_size
  291. self.pixel_mean = [0., 0., 0.]
  292. self.pixel_std = [255., 255., 255.]
  293. self.color_format = 'bgr'
  294. self.augment = Compose([
  295. ConvertFromInts(), # 将int类型转换为float32类型
  296. PhotometricDistort(), # 图像颜色增强
  297. Expand(), # 扩充增强
  298. RandomSampleCrop(), # 随机剪裁
  299. RandomHorizontalFlip(), # 随机水平翻转
  300. Resize(self.img_size) # resize操作
  301. ])
  302. def __call__(self, image, target, mosaic=False):
  303. orig_h, orig_w = image.shape[:2]
  304. ratio = [self.img_size / orig_w, self.img_size / orig_h]
  305. # augment
  306. boxes = target['boxes'].copy()
  307. labels = target['labels'].copy()
  308. image, boxes, labels = self.augment(image, boxes, labels)
  309. # to tensor
  310. img_tensor = torch.from_numpy(image).permute(2, 0, 1).contiguous().float()
  311. target['boxes'] = torch.from_numpy(boxes).float()
  312. target['labels'] = torch.from_numpy(labels).float()
  313. # normalize image
  314. img_tensor /= 255.
  315. return img_tensor, target, ratio
  316. ## SSD-style valTransform
  317. class SSDBaseTransform(object):
  318. def __init__(self, img_size):
  319. self.img_size = img_size
  320. self.pixel_mean = [0., 0., 0.]
  321. self.pixel_std = [255., 255., 255.]
  322. self.color_format = 'bgr'
  323. def __call__(self, image, target=None, mosaic=False):
  324. # resize
  325. orig_h, orig_w = image.shape[:2]
  326. ratio = [self.img_size / orig_w, self.img_size / orig_h]
  327. image = cv2.resize(image, (self.img_size, self.img_size)).astype(np.float32)
  328. # scale targets
  329. if target is not None:
  330. boxes = target['boxes'].copy()
  331. labels = target['labels'].copy()
  332. img_h, img_w = image.shape[:2]
  333. boxes[..., [0, 2]] = boxes[..., [0, 2]] / orig_w * img_w
  334. boxes[..., [1, 3]] = boxes[..., [1, 3]] / orig_h * img_h
  335. target['boxes'] = boxes
  336. # to tensor
  337. img_tensor = torch.from_numpy(image).permute(2, 0, 1).contiguous().float()
  338. if target is not None:
  339. target['boxes'] = torch.from_numpy(boxes).float()
  340. target['labels'] = torch.from_numpy(labels).float()
  341. # normalize image
  342. img_tensor /= 255.
  343. return img_tensor, target, ratio