custom.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import os
  2. import cv2
  3. import time
  4. import random
  5. import numpy as np
  6. from torch.utils.data import Dataset
  7. from pycocotools.coco import COCO
  8. try:
  9. from .data_augment.strong_augment import MosaicAugment, MixupAugment
  10. except:
  11. from data_augment.strong_augment import MosaicAugment, MixupAugment
  12. custom_class_indexs = [0, 1, 2, 3, 4, 5, 6, 7, 8]
  13. custom_class_labels = ('bird', 'butterfly', 'cat', 'cow', 'dog', 'lion', 'person', 'pig', 'tiger', )
  14. class CustomDataset(Dataset):
  15. def __init__(self,
  16. cfg,
  17. data_dir :str = None,
  18. transform = None,
  19. is_train :bool =False,
  20. ):
  21. # ----------- Basic parameters -----------
  22. self.image_set = "train" if is_train else "val"
  23. self.is_train = is_train
  24. self.num_classes = len(custom_class_labels)
  25. # ----------- Path parameters -----------
  26. self.data_dir = data_dir
  27. self.json_file = '{}.json'.format(self.image_set)
  28. # ----------- Data parameters -----------
  29. self.coco = COCO(os.path.join(self.data_dir, self.image_set, 'annotations', self.json_file))
  30. self.ids = self.coco.getImgIds()
  31. self.class_ids = sorted(self.coco.getCatIds())
  32. self.dataset_size = len(self.ids)
  33. self.class_labels = custom_class_labels
  34. self.class_indexs = custom_class_indexs
  35. # ----------- Transform parameters -----------
  36. self.transform = transform
  37. if is_train:
  38. self.mosaic_prob = cfg.mosaic_prob
  39. self.mixup_prob = cfg.mixup_prob
  40. self.copy_paste = cfg.copy_paste
  41. self.mosaic_augment = None if cfg.mosaic_prob == 0. else MosaicAugment(cfg.train_img_size, cfg.affine_params, is_train)
  42. self.mixup_augment = None if cfg.mixup_prob == 0. and cfg.copy_paste == 0. else MixupAugment(cfg.train_img_size)
  43. else:
  44. self.mosaic_prob = 0.0
  45. self.mixup_prob = 0.0
  46. self.copy_paste = 0.0
  47. self.mosaic_augment = None
  48. self.mixup_augment = None
  49. print(' ============ Strong augmentation info. ============ ')
  50. print('use Mosaic Augmentation: {}'.format(self.mosaic_prob))
  51. print('use Mixup Augmentation: {}'.format(self.mixup_prob))
  52. print('use Copy-paste Augmentation: {}'.format(self.copy_paste))
  53. # ------------ Basic dataset function ------------
  54. def __len__(self):
  55. return len(self.ids)
  56. def __getitem__(self, index):
  57. return self.pull_item(index)
  58. # ------------ Mosaic & Mixup ------------
  59. def load_mosaic(self, index):
  60. # ------------ Prepare 4 indexes of images ------------
  61. ## Load 4x mosaic image
  62. index_list = np.arange(index).tolist() + np.arange(index+1, len(self.ids)).tolist()
  63. id1 = index
  64. id2, id3, id4 = random.sample(index_list, 3)
  65. indexs = [id1, id2, id3, id4]
  66. ## Load images and targets
  67. image_list = []
  68. target_list = []
  69. for index in indexs:
  70. img_i, target_i = self.load_image_target(index)
  71. image_list.append(img_i)
  72. target_list.append(target_i)
  73. # ------------ Mosaic augmentation ------------
  74. image, target = self.mosaic_augment(image_list, target_list)
  75. return image, target
  76. def load_mixup(self, origin_image, origin_target, yolox_style=False):
  77. # ------------ Load a new image & target ------------
  78. if yolox_style:
  79. new_index = np.random.randint(0, len(self.ids))
  80. new_image, new_target = self.load_image_target(new_index)
  81. else:
  82. new_index = np.random.randint(0, len(self.ids))
  83. new_image, new_target = self.load_mosaic(new_index)
  84. # ------------ Mixup augmentation ------------
  85. image, target = self.mixup_augment(origin_image, origin_target, new_image, new_target, yolox_style)
  86. return image, target
  87. # ------------ Load data function ------------
  88. def load_image_target(self, index):
  89. # load an image
  90. image, _ = self.pull_image(index)
  91. height, width, channels = image.shape
  92. # load a target
  93. bboxes, labels = self.pull_anno(index)
  94. target = {
  95. "boxes": bboxes,
  96. "labels": labels,
  97. "orig_size": [height, width]
  98. }
  99. return image, target
  100. def pull_item(self, index):
  101. if random.random() < self.mosaic_prob:
  102. # load a mosaic image
  103. mosaic = True
  104. image, target = self.load_mosaic(index)
  105. else:
  106. mosaic = False
  107. # load an image and target
  108. image, target = self.load_image_target(index)
  109. # Yolov5-MixUp
  110. mixup = False
  111. if random.random() < self.mixup_prob:
  112. mixup = True
  113. image, target = self.load_mixup(image, target)
  114. # Copy-paste (use Yolox-Mixup to approximate copy-paste)
  115. if not mixup and random.random() < self.copy_paste:
  116. image, target = self.load_mixup(image, target, yolox_style=True)
  117. # augment
  118. image, target, deltas = self.transform(image, target, mosaic)
  119. return image, target, deltas
  120. def pull_image(self, index):
  121. id_ = self.ids[index]
  122. im_ann = self.coco.loadImgs(id_)[0]
  123. img_file = os.path.join(
  124. self.data_dir, self.image_set, 'images', im_ann["file_name"])
  125. image = cv2.imread(img_file)
  126. return image, id_
  127. def pull_anno(self, index):
  128. img_id = self.ids[index]
  129. im_ann = self.coco.loadImgs(img_id)[0]
  130. anno_ids = self.coco.getAnnIds(imgIds=[int(img_id)], iscrowd=0)
  131. annotations = self.coco.loadAnns(anno_ids)
  132. # image infor
  133. width = im_ann['width']
  134. height = im_ann['height']
  135. #load a target
  136. bboxes = []
  137. labels = []
  138. for anno in annotations:
  139. if 'bbox' in anno and anno['area'] > 0:
  140. # bbox
  141. x1 = np.max((0, anno['bbox'][0]))
  142. y1 = np.max((0, anno['bbox'][1]))
  143. x2 = np.min((width - 1, x1 + np.max((0, anno['bbox'][2] - 1))))
  144. y2 = np.min((height - 1, y1 + np.max((0, anno['bbox'][3] - 1))))
  145. if x2 <= x1 or y2 <= y1:
  146. continue
  147. # class label
  148. cls_id = self.class_ids.index(anno['category_id'])
  149. bboxes.append([x1, y1, x2, y2])
  150. labels.append(cls_id)
  151. # guard against no boxes via resizing
  152. bboxes = np.array(bboxes).reshape(-1, 4)
  153. labels = np.array(labels).reshape(-1)
  154. return bboxes, labels
  155. if __name__ == "__main__":
  156. import time
  157. import argparse
  158. from build import build_transform
  159. parser = argparse.ArgumentParser(description='RT-ODLab')
  160. # opt
  161. parser.add_argument('--root', default='D:/python_work/dataset/COCO/',
  162. help='data root')
  163. parser.add_argument('--is_train', action="store_true", default=False,
  164. help='mixup augmentation.')
  165. parser.add_argument('--aug_type', default="yolo", type=str, choices=["yolo", "ssd"],
  166. help='yolo, ssd.')
  167. args = parser.parse_args()
  168. class YoloBaseConfig(object):
  169. def __init__(self) -> None:
  170. self.max_stride = 32
  171. # ---------------- Data process config ----------------
  172. self.box_format = 'xywh'
  173. self.normalize_coords = False
  174. self.mosaic_prob = 1.0
  175. self.mixup_prob = 0.15
  176. self.copy_paste = 0.3
  177. ## Pixel mean & std
  178. self.pixel_mean = [0., 0., 0.]
  179. self.pixel_std = [255., 255., 255.]
  180. ## Transforms
  181. self.train_img_size = 640
  182. self.test_img_size = 640
  183. self.use_ablu = True
  184. self.aug_type = 'yolo'
  185. self.affine_params = {
  186. 'degrees': 0.0,
  187. 'translate': 0.2,
  188. 'scale': [0.1, 2.0],
  189. 'shear': 0.0,
  190. 'perspective': 0.0,
  191. 'hsv_h': 0.015,
  192. 'hsv_s': 0.7,
  193. 'hsv_v': 0.4,
  194. }
  195. class SSDBaseConfig(object):
  196. def __init__(self) -> None:
  197. self.max_stride = 32
  198. # ---------------- Data process config ----------------
  199. self.box_format = 'xywh'
  200. self.normalize_coords = False
  201. self.mosaic_prob = 0.0
  202. self.mixup_prob = 0.0
  203. self.copy_paste = 0.0
  204. ## Pixel mean & std
  205. self.pixel_mean = [0., 0., 0.]
  206. self.pixel_std = [255., 255., 255.]
  207. ## Transforms
  208. self.train_img_size = 640
  209. self.test_img_size = 640
  210. self.aug_type = 'ssd'
  211. if args.aug_type == "yolo":
  212. cfg = YoloBaseConfig()
  213. elif args.aug_type == "ssd":
  214. cfg = SSDBaseConfig()
  215. transform = build_transform(cfg, args.is_train)
  216. dataset = CustomDataset(cfg, args.root, transform, args.is_train)
  217. np.random.seed(0)
  218. class_colors = [(np.random.randint(255),
  219. np.random.randint(255),
  220. np.random.randint(255)) for _ in range(80)]
  221. print('Data length: ', len(dataset))
  222. for i in range(1000):
  223. t0 = time.time()
  224. image, target = dataset.pull_item(i)
  225. print("Load data: {} s".format(time.time() - t0))
  226. # to numpy
  227. image = image.permute(1, 2, 0).numpy()
  228. # denormalize
  229. image = image * cfg.pixel_std + cfg.pixel_mean
  230. # rgb -> bgr
  231. if transform.color_format == 'rgb':
  232. image = image[..., (2, 1, 0)]
  233. # to uint8
  234. image = image.astype(np.uint8)
  235. image = image.copy()
  236. img_h, img_w = image.shape[:2]
  237. boxes = target["boxes"]
  238. labels = target["labels"]
  239. for box, label in zip(boxes, labels):
  240. if cfg.box_format == 'xyxy':
  241. x1, y1, x2, y2 = box
  242. elif cfg.box_format == 'xywh':
  243. cx, cy, bw, bh = box
  244. x1 = cx - 0.5 * bw
  245. y1 = cy - 0.5 * bh
  246. x2 = cx + 0.5 * bw
  247. y2 = cy + 0.5 * bh
  248. if cfg.normalize_coords:
  249. x1 *= img_w
  250. y1 *= img_h
  251. x2 *= img_w
  252. y2 *= img_h
  253. cls_id = int(label)
  254. color = class_colors[cls_id]
  255. # class name
  256. label = custom_class_labels[cls_id]
  257. image = cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)
  258. # put the test on the bbox
  259. cv2.putText(image, label, (int(x1), int(y1 - 5)), 0, 0.5, color, 1, lineType=cv2.LINE_AA)
  260. cv2.imshow('gt', image)
  261. # cv2.imwrite(str(i)+'.jpg', img)
  262. cv2.waitKey(0)