customed.py 11 KB

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