custom.py 11 KB

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