ourdataset.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import os
  2. import cv2
  3. import random
  4. import numpy as np
  5. import time
  6. from torch.utils.data import Dataset
  7. try:
  8. from pycocotools.coco import COCO
  9. except:
  10. print("It seems that the COCOAPI is not installed.")
  11. try:
  12. from .data_augment.yolov5_augment import yolov5_mosaic_augment, yolov5_mixup_augment, yolox_mixup_augment
  13. except:
  14. from data_augment.yolov5_augment import yolov5_mosaic_augment, yolov5_mixup_augment, yolox_mixup_augment
  15. # please define our class labels
  16. our_class_labels = ('bird', 'butterfly', 'cat', 'cow', 'dog', 'lion', 'person', 'pig', 'tiger', )
  17. class OurDataset(Dataset):
  18. """
  19. Our dataset class.
  20. """
  21. def __init__(self,
  22. img_size=640,
  23. data_dir=None,
  24. image_set='train',
  25. transform=None,
  26. trans_config=None,
  27. is_train=False):
  28. """
  29. COCO dataset initialization. Annotation data are read into memory by COCO API.
  30. Args:
  31. data_dir (str): dataset root directory
  32. json_file (str): COCO json file name
  33. name (str): COCO data name (e.g. 'train2017' or 'val2017')
  34. debug (bool): if True, only one data id is selected from the dataset
  35. """
  36. self.img_size = img_size
  37. self.image_set = image_set
  38. self.json_file = '{}.json'.format(image_set)
  39. self.data_dir = data_dir
  40. self.coco = COCO(os.path.join(self.data_dir, image_set, 'annotations', self.json_file))
  41. self.ids = self.coco.getImgIds()
  42. self.class_ids = sorted(self.coco.getCatIds())
  43. self.is_train = is_train
  44. # augmentation
  45. self.transform = transform
  46. self.mosaic_prob = 0
  47. self.mixup_prob = 0
  48. self.trans_config = trans_config
  49. if trans_config is not None:
  50. self.mosaic_prob = trans_config['mosaic_prob']
  51. self.mixup_prob = trans_config['mixup_prob']
  52. print('==============================')
  53. print('Image Set: {}'.format(image_set))
  54. print('Json file: {}'.format(self.json_file))
  55. print('use Mosaic Augmentation: {}'.format(self.mosaic_prob))
  56. print('use Mixup Augmentation: {}'.format(self.mixup_prob))
  57. print('==============================')
  58. def __len__(self):
  59. return len(self.ids)
  60. def __getitem__(self, index):
  61. return self.pull_item(index)
  62. def load_image_target(self, index):
  63. # load an image
  64. image, _ = self.pull_image(index)
  65. height, width, channels = image.shape
  66. # load a target
  67. bboxes, labels = self.pull_anno(index)
  68. target = {
  69. "boxes": bboxes,
  70. "labels": labels,
  71. "orig_size": [height, width]
  72. }
  73. return image, target
  74. def load_mosaic(self, index):
  75. # load 4x mosaic image
  76. index_list = np.arange(index).tolist() + np.arange(index+1, len(self.ids)).tolist()
  77. id1 = index
  78. id2, id3, id4 = random.sample(index_list, 3)
  79. indexs = [id1, id2, id3, id4]
  80. # load images and targets
  81. image_list = []
  82. target_list = []
  83. for index in indexs:
  84. img_i, target_i = self.load_image_target(index)
  85. image_list.append(img_i)
  86. target_list.append(target_i)
  87. # Mosaic
  88. if self.trans_config['mosaic_type'] == 'yolov5_mosaic':
  89. image, target = yolov5_mosaic_augment(
  90. image_list, target_list, self.img_size, self.trans_config, self.is_train)
  91. return image, target
  92. def load_mixup(self, origin_image, origin_target):
  93. # YOLOv5 type Mixup
  94. if self.trans_config['mixup_type'] == 'yolov5_mixup':
  95. new_index = np.random.randint(0, len(self.ids))
  96. new_image, new_target = self.load_mosaic(new_index)
  97. image, target = yolov5_mixup_augment(
  98. origin_image, origin_target, new_image, new_target)
  99. # YOLOX type Mixup
  100. elif self.trans_config['mixup_type'] == 'yolox_mixup':
  101. new_index = np.random.randint(0, len(self.ids))
  102. new_image, new_target = self.load_image_target(new_index)
  103. image, target = yolox_mixup_augment(
  104. origin_image, origin_target, new_image, new_target, self.img_size, self.trans_config['mixup_scale'])
  105. return image, target
  106. def pull_item(self, index):
  107. if random.random() < self.mosaic_prob:
  108. # load a mosaic image
  109. mosaic = True
  110. image, target = self.load_mosaic(index)
  111. else:
  112. mosaic = False
  113. # load an image and target
  114. image, target = self.load_image_target(index)
  115. # MixUp
  116. if random.random() < self.mixup_prob:
  117. image, target = self.load_mixup(image, target)
  118. # augment
  119. image, target, deltas = self.transform(image, target, mosaic)
  120. return image, target, deltas
  121. def pull_image(self, index):
  122. id_ = self.ids[index]
  123. im_ann = self.coco.loadImgs(id_)[0]
  124. img_file = os.path.join(
  125. self.data_dir, self.image_set, 'images', im_ann["file_name"])
  126. image = cv2.imread(img_file)
  127. return image, id_
  128. def pull_anno(self, index):
  129. img_id = self.ids[index]
  130. im_ann = self.coco.loadImgs(img_id)[0]
  131. anno_ids = self.coco.getAnnIds(imgIds=[int(img_id)], iscrowd=0)
  132. annotations = self.coco.loadAnns(anno_ids)
  133. # image infor
  134. width = im_ann['width']
  135. height = im_ann['height']
  136. #load a target
  137. bboxes = []
  138. labels = []
  139. for anno in annotations:
  140. if 'bbox' in anno and anno['area'] > 0:
  141. # bbox
  142. x1 = np.max((0, anno['bbox'][0]))
  143. y1 = np.max((0, anno['bbox'][1]))
  144. x2 = np.min((width - 1, x1 + np.max((0, anno['bbox'][2] - 1))))
  145. y2 = np.min((height - 1, y1 + np.max((0, anno['bbox'][3] - 1))))
  146. if x2 <= x1 or y2 <= y1:
  147. continue
  148. # class label
  149. cls_id = self.class_ids.index(anno['category_id'])
  150. bboxes.append([x1, y1, x2, y2])
  151. labels.append(cls_id)
  152. # guard against no boxes via resizing
  153. bboxes = np.array(bboxes).reshape(-1, 4)
  154. labels = np.array(labels).reshape(-1)
  155. return bboxes, labels
  156. if __name__ == "__main__":
  157. import argparse
  158. from build import build_transform
  159. parser = argparse.ArgumentParser(description='FreeYOLOv2')
  160. # opt
  161. parser.add_argument('--root', default='AnimalDataset',
  162. help='data root')
  163. parser.add_argument('--split', default='train',
  164. help='data split')
  165. parser.add_argument('-size', '--img_size', default=640, type=int,
  166. help='input image size')
  167. parser.add_argument('--min_box_size', default=8.0, type=float,
  168. help='min size of target bounding box.')
  169. parser.add_argument('--mosaic', default=None, type=float,
  170. help='mosaic augmentation.')
  171. parser.add_argument('--mixup', default=None, type=float,
  172. help='mixup augmentation.')
  173. args = parser.parse_args()
  174. img_size = 640
  175. is_train = True
  176. trans_config = {
  177. 'aug_type': 'yolov5',
  178. # Basic Augment
  179. 'degrees': 0.0,
  180. 'translate': 0.2,
  181. 'scale': 0.9,
  182. 'shear': 0.0,
  183. 'perspective': 0.0,
  184. 'hsv_h': 0.015,
  185. 'hsv_s': 0.7,
  186. 'hsv_v': 0.4,
  187. # Mosaic & Mixup
  188. 'mosaic_prob': 1.0,
  189. 'mosaic_9x_prob': 0.2,
  190. 'mixup_prob': 0.15,
  191. 'mosaic_type': 'yolov5_mosaic',
  192. 'mixup_type': 'yolov5_mixup',
  193. 'mixup_scale': [0.5, 1.5]
  194. }
  195. transform, trans_config = build_transform(args, trans_config, max_stride=32, is_train=is_train)
  196. dataset = OurDataset(
  197. img_size=img_size,
  198. data_dir=args.root,
  199. image_set=args.split,
  200. transform=transform,
  201. trans_config=trans_config,
  202. )
  203. np.random.seed(0)
  204. class_colors = [(np.random.randint(255),
  205. np.random.randint(255),
  206. np.random.randint(255)) for _ in range(80)]
  207. print('Data length: ', len(dataset))
  208. for i in range(1000):
  209. image, target, deltas = dataset.pull_item(i)
  210. # to numpy
  211. image = image.permute(1, 2, 0).numpy()
  212. image = image.astype(np.uint8)
  213. image = image.copy()
  214. img_h, img_w = image.shape[:2]
  215. boxes = target["boxes"]
  216. labels = target["labels"]
  217. for box, label in zip(boxes, labels):
  218. x1, y1, x2, y2 = box
  219. cls_id = int(label)
  220. color = class_colors[cls_id]
  221. # class name
  222. label = our_class_labels[cls_id]
  223. if x2 - x1 > 0. and y2 - y1 > 0.:
  224. # draw bbox
  225. image = cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)
  226. # put the test on the bbox
  227. cv2.putText(image, label, (int(x1), int(y1 - 5)), 0, 0.5, color, 1, lineType=cv2.LINE_AA)
  228. cv2.imshow('gt', image)
  229. # cv2.imwrite(str(i)+'.jpg', img)
  230. cv2.waitKey(0)