widerface.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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.strong_augment import MosaicAugment, MixupAugment
  13. except:
  14. from data_augment.strong_augment import MosaicAugment, MixupAugment
  15. widerface_class_labels = ('face',)
  16. class WiderFaceDataset(Dataset):
  17. """
  18. CrowdHuman dataset class.
  19. """
  20. def __init__(self,
  21. img_size :int = 640,
  22. data_dir :str = None,
  23. image_set :str = 'train',
  24. trans_config = None,
  25. transform = None,
  26. is_train :bool = False
  27. ):
  28. # ----------- Basic parameters -----------
  29. self.img_size = img_size
  30. self.image_set = image_set
  31. self.is_train = is_train
  32. # ----------- Path parameters -----------
  33. self.data_dir = data_dir
  34. self.json_file = '{}.json'.format(image_set)
  35. # ----------- Data parameters -----------
  36. self.coco = COCO(os.path.join(self.data_dir, 'annotations', self.json_file))
  37. self.ids = self.coco.getImgIds()
  38. self.class_ids = sorted(self.coco.getCatIds())
  39. # ----------- Transform parameters -----------
  40. self.trans_config = trans_config
  41. self.transform = transform
  42. # ----------- Strong augmentation -----------
  43. if is_train:
  44. self.mosaic_prob = trans_config['mosaic_prob'] if trans_config else 0.0
  45. self.mixup_prob = trans_config['mixup_prob'] if trans_config else 0.0
  46. self.mosaic_augment = MosaicAugment(img_size, trans_config, is_train)
  47. self.mixup_augment = MixupAugment(img_size, trans_config)
  48. else:
  49. self.mosaic_prob = 0.0
  50. self.mixup_prob = 0.0
  51. self.mosaic_augment = None
  52. self.mixup_augment = None
  53. print('==============================')
  54. print('use Mosaic Augmentation: {}'.format(self.mosaic_prob))
  55. print('use Mixup Augmentation: {}'.format(self.mixup_prob))
  56. print('==============================')
  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):
  81. # ------------ Load a new image & target ------------
  82. if self.mixup_augment.mixup_type == 'yolov5':
  83. new_index = np.random.randint(0, len(self.ids))
  84. new_image, new_target = self.load_mosaic(new_index)
  85. elif self.mixup_augment.mixup_type == 'yolox':
  86. new_index = np.random.randint(0, len(self.ids))
  87. new_image, new_target = self.load_image_target(new_index)
  88. # ------------ Mixup augmentation ------------
  89. image, target = self.mixup_augment(origin_image, origin_target, new_image, new_target)
  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. # MixUp
  114. if random.random() < self.mixup_prob:
  115. image, target = self.load_mixup(image, target)
  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, 'WIDER_{}'.format(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='WiderFace-Dataset')
  159. # opt
  160. parser.add_argument('--root', default='/Users/liuhaoran/Desktop/python_work/object-detection/dataset/WiderFace/',
  161. help='data root')
  162. parser.add_argument('-size', '--img_size', default=640, type=int,
  163. help='input image size.')
  164. parser.add_argument('--aug_type', type=str, default='ssd',
  165. help='augmentation type')
  166. parser.add_argument('--mosaic', default=0., type=float,
  167. help='mosaic augmentation.')
  168. parser.add_argument('--mixup', default=0., type=float,
  169. help='mixup augmentation.')
  170. parser.add_argument('--mixup_type', type=str, default='yolov5_mixup',
  171. help='mixup augmentation.')
  172. parser.add_argument('--is_train', action="store_true", default=False,
  173. help='mixup augmentation.')
  174. args = parser.parse_args()
  175. trans_config = {
  176. 'aug_type': args.aug_type, # optional: ssd, yolov5
  177. 'pixel_mean': [0., 0., 0.],
  178. 'pixel_std': [255., 255., 255.],
  179. # Basic Augment
  180. 'degrees': 0.0,
  181. 'translate': 0.2,
  182. 'scale': [0.1, 2.0],
  183. 'shear': 0.0,
  184. 'perspective': 0.0,
  185. 'hsv_h': 0.015,
  186. 'hsv_s': 0.7,
  187. 'hsv_v': 0.4,
  188. 'use_ablu': True,
  189. # Mosaic & Mixup
  190. 'mosaic_prob': args.mosaic,
  191. 'mixup_prob': args.mixup,
  192. 'mosaic_type': 'yolov5_mosaic',
  193. 'mixup_type': args.mixup_type, # optional: yolov5_mixup, yolox_mixup
  194. 'mosaic_keep_ratio': False,
  195. 'mixup_scale': [0.5, 1.5]
  196. }
  197. transform, trans_cfg = build_transform(args, trans_config, 32, args.is_train)
  198. pixel_mean = transform.pixel_mean
  199. pixel_std = transform.pixel_std
  200. color_format = transform.color_format
  201. dataset = WiderFaceDataset(
  202. img_size=args.img_size,
  203. data_dir=args.root,
  204. image_set='val',
  205. transform=transform,
  206. trans_config=trans_config,
  207. )
  208. np.random.seed(0)
  209. class_colors = [(np.random.randint(255),
  210. np.random.randint(255),
  211. np.random.randint(255)) for _ in range(80)]
  212. print('Data length: ', len(dataset))
  213. for i in range(1000):
  214. t0 = time.time()
  215. image, target, deltas = dataset.pull_item(i)
  216. print("Load data: {} s".format(time.time() - t0))
  217. # to numpy
  218. image = image.permute(1, 2, 0).numpy()
  219. # denormalize
  220. image = image * pixel_std + pixel_mean
  221. if color_format == 'rgb':
  222. # RGB to BGR
  223. image = image[..., (2, 1, 0)]
  224. # to uint8
  225. image = image.astype(np.uint8)
  226. image = image.copy()
  227. img_h, img_w = image.shape[:2]
  228. boxes = target["boxes"]
  229. labels = target["labels"]
  230. for box, label in zip(boxes, labels):
  231. x1, y1, x2, y2 = box
  232. cls_id = int(label)
  233. color = class_colors[cls_id]
  234. # class name
  235. label = widerface_class_labels[cls_id]
  236. image = cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), (0,0,255), 2)
  237. # put the test on the bbox
  238. cv2.putText(image, label, (int(x1), int(y1 - 5)), 0, 0.5, color, 1, lineType=cv2.LINE_AA)
  239. cv2.imshow('gt', image)
  240. # cv2.imwrite(str(i)+'.jpg', img)
  241. cv2.waitKey(0)