crowdhuman.py 9.7 KB

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