customed.py 11 KB

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