ourdataset.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 = ('cat',)
  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 = trans_config['mosaic_prob'] if trans_config else 0.0
  47. self.mixup_prob = trans_config['mixup_prob'] if trans_config else 0.0
  48. self.trans_config = trans_config
  49. print('==============================')
  50. print('use Mosaic Augmentation: {}'.format(self.mosaic_prob))
  51. print('use Mixup Augmentation: {}'.format(self.mixup_prob))
  52. print('==============================')
  53. def __len__(self):
  54. return len(self.ids)
  55. def __getitem__(self, index):
  56. return self.pull_item(index)
  57. def load_image_target(self, index):
  58. # load an image
  59. image, _ = self.pull_image(index)
  60. height, width, channels = image.shape
  61. # load a target
  62. bboxes, labels = self.pull_anno(index)
  63. target = {
  64. "boxes": bboxes,
  65. "labels": labels,
  66. "orig_size": [height, width]
  67. }
  68. return image, target
  69. def load_mosaic(self, index):
  70. # load 4x mosaic image
  71. index_list = np.arange(index).tolist() + np.arange(index+1, len(self.ids)).tolist()
  72. id1 = index
  73. id2, id3, id4 = random.sample(index_list, 3)
  74. indexs = [id1, id2, id3, id4]
  75. # load images and targets
  76. image_list = []
  77. target_list = []
  78. for index in indexs:
  79. img_i, target_i = self.load_image_target(index)
  80. image_list.append(img_i)
  81. target_list.append(target_i)
  82. # Mosaic Augment
  83. if self.trans_config['mosaic_type'] == 'yolov5_mosaic':
  84. image, target = yolov5_mosaic_augment(
  85. image_list, target_list, self.img_size, self.trans_config)
  86. return image, target
  87. def load_mixup(self, origin_image, origin_target):
  88. # YOLOv5 type Mixup
  89. if self.trans_config['mixup_type'] == 'yolov5_mixup':
  90. new_index = np.random.randint(0, len(self.ids))
  91. new_image, new_target = self.load_mosaic(new_index)
  92. image, target = yolov5_mixup_augment(
  93. origin_image, origin_target, new_image, new_target)
  94. # YOLOX type Mixup
  95. elif self.trans_config['mixup_type'] == 'yolox_mixup':
  96. new_index = np.random.randint(0, len(self.ids))
  97. new_image, new_target = self.load_image_target(new_index)
  98. image, target = yolox_mixup_augment(
  99. origin_image, origin_target, new_image, new_target, self.img_size, self.trans_config['mixup_scale'])
  100. return image, target
  101. def pull_item(self, index):
  102. if random.random() < self.mosaic_prob:
  103. # load a mosaic image
  104. mosaic = True
  105. image, target = self.load_mosaic(index)
  106. else:
  107. mosaic = False
  108. # load an image and target
  109. image, target = self.load_image_target(index)
  110. # MixUp
  111. if random.random() < self.mixup_prob:
  112. image, target = self.load_mixup(image, target)
  113. # augment
  114. image, target, deltas = self.transform(image, target, mosaic)
  115. return image, target, deltas
  116. def pull_image(self, index):
  117. id_ = self.ids[index]
  118. im_ann = self.coco.loadImgs(id_)[0]
  119. img_file = os.path.join(
  120. self.data_dir, self.image_set, 'images', im_ann["file_name"])
  121. image = cv2.imread(img_file)
  122. return image, id_
  123. def pull_anno(self, index):
  124. id_ = self.ids[index]
  125. anno_ids = self.coco.getAnnIds(imgIds=[int(id_)], iscrowd=None)
  126. annotations = self.coco.loadAnns(anno_ids)
  127. #load a target
  128. bboxes = []
  129. labels = []
  130. for anno in annotations:
  131. if 'bbox' in anno and anno['area'] > 0:
  132. # bbox
  133. x1 = np.max((0, anno['bbox'][0]))
  134. y1 = np.max((0, anno['bbox'][1]))
  135. x2 = x1 + anno['bbox'][2]
  136. y2 = y1 + anno['bbox'][3]
  137. if x2 < x1 or y2 < y1:
  138. continue
  139. # class label
  140. cls_id = self.class_ids.index(anno['category_id'])
  141. bboxes.append([x1, y1, x2, y2])
  142. labels.append(cls_id)
  143. # guard against no boxes via resizing
  144. bboxes = np.array(bboxes).reshape(-1, 4)
  145. labels = np.array(labels).reshape(-1)
  146. return bboxes, labels
  147. if __name__ == "__main__":
  148. import argparse
  149. import sys
  150. from build import build_transform
  151. parser = argparse.ArgumentParser(description='Our-Dataset')
  152. # opt
  153. parser.add_argument('--root', default='OurDataset',
  154. help='data root')
  155. parser.add_argument('--split', default='train',
  156. help='data split')
  157. args = parser.parse_args()
  158. is_train = False
  159. img_size = 640
  160. yolov5_trans_config = {
  161. 'aug_type': 'yolov5',
  162. # Basic Augment
  163. 'degrees': 0.0,
  164. 'translate': 0.2,
  165. 'scale': 0.9,
  166. 'shear': 0.0,
  167. 'perspective': 0.0,
  168. 'hsv_h': 0.015,
  169. 'hsv_s': 0.7,
  170. 'hsv_v': 0.4,
  171. # Mosaic & Mixup
  172. 'mosaic_prob': 1.0,
  173. 'mixup_prob': 0.15,
  174. 'mosaic_type': 'yolov5_mosaic',
  175. 'mixup_type': 'yolov5_mixup',
  176. 'mixup_scale': [0.5, 1.5]
  177. }
  178. ssd_trans_config = {
  179. 'aug_type': 'ssd',
  180. 'mosaic_prob': 0.0,
  181. 'mixup_prob': 0.0
  182. }
  183. transform = build_transform(img_size, yolov5_trans_config, is_train)
  184. dataset = OurDataset(
  185. img_size=img_size,
  186. data_dir=args.root,
  187. image_set='train',
  188. trans_config=yolov5_trans_config,
  189. transform=transform,
  190. is_train=is_train
  191. )
  192. np.random.seed(0)
  193. class_colors = [(np.random.randint(255),
  194. np.random.randint(255),
  195. np.random.randint(255)) for _ in range(80)]
  196. print('Data length: ', len(dataset))
  197. for i in range(1000):
  198. image, target, deltas = dataset.pull_item(i)
  199. # to numpy
  200. image = image.permute(1, 2, 0).numpy()
  201. # to uint8
  202. image = image.astype(np.uint8)
  203. image = image.copy()
  204. img_h, img_w = image.shape[:2]
  205. boxes = target["boxes"]
  206. labels = target["labels"]
  207. for box, label in zip(boxes, labels):
  208. x1, y1, x2, y2 = box
  209. cls_id = int(label)
  210. color = class_colors[cls_id]
  211. # class name
  212. label = our_class_labels[cls_id]
  213. image = cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), (0,0,255), 2)
  214. # put the test on the bbox
  215. cv2.putText(image, label, (int(x1), int(y1 - 5)), 0, 0.5, color, 1, lineType=cv2.LINE_AA)
  216. cv2.imshow('gt', image)
  217. # cv2.imwrite(str(i)+'.jpg', img)
  218. cv2.waitKey(0)