widerface.py 9.6 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. 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.transform = transform
  41. self.mosaic_prob = trans_config['mosaic_prob'] if trans_config else 0.0
  42. self.mixup_prob = trans_config['mixup_prob'] if trans_config else 0.0
  43. self.trans_config = trans_config
  44. print('==============================')
  45. print('use Mosaic Augmentation: {}'.format(self.mosaic_prob))
  46. print('use Mixup Augmentation: {}'.format(self.mixup_prob))
  47. print('==============================')
  48. # ------------ Basic dataset function ------------
  49. def __len__(self):
  50. return len(self.ids)
  51. def __getitem__(self, index):
  52. return self.pull_item(index)
  53. # ------------ Mosaic & Mixup ------------
  54. def load_mosaic(self, index):
  55. # load 4x mosaic image
  56. index_list = np.arange(index).tolist() + np.arange(index+1, len(self.ids)).tolist()
  57. id1 = index
  58. id2, id3, id4 = random.sample(index_list, 3)
  59. indexs = [id1, id2, id3, id4]
  60. # load images and targets
  61. image_list = []
  62. target_list = []
  63. for index in indexs:
  64. img_i, target_i = self.load_image_target(index)
  65. image_list.append(img_i)
  66. target_list.append(target_i)
  67. # Mosaic
  68. if self.trans_config['mosaic_type'] == 'yolov5_mosaic':
  69. image, target = yolov5_mosaic_augment(
  70. image_list, target_list, self.img_size, self.trans_config, self.trans_config['mosaic_keep_ratio'], self.is_train)
  71. return image, target
  72. def load_mixup(self, origin_image, origin_target):
  73. # YOLOv5 type Mixup
  74. if self.trans_config['mixup_type'] == 'yolov5_mixup':
  75. new_index = np.random.randint(0, len(self.ids))
  76. new_image, new_target = self.load_mosaic(new_index)
  77. image, target = yolov5_mixup_augment(
  78. origin_image, origin_target, new_image, new_target)
  79. # YOLOX type Mixup
  80. elif self.trans_config['mixup_type'] == 'yolox_mixup':
  81. new_index = np.random.randint(0, len(self.ids))
  82. new_image, new_target = self.load_image_target(new_index)
  83. image, target = yolox_mixup_augment(
  84. origin_image, origin_target, new_image, new_target, self.img_size, self.trans_config['mixup_scale'])
  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. # MixUp
  109. if random.random() < self.mixup_prob:
  110. image, target = self.load_mixup(image, target)
  111. # augment
  112. image, target, deltas = self.transform(image, target, mosaic)
  113. return image, target, deltas
  114. def pull_image(self, index):
  115. id_ = self.ids[index]
  116. im_ann = self.coco.loadImgs(id_)[0]
  117. img_file = os.path.join(
  118. self.data_dir, 'WIDER_{}'.format(self.image_set), 'images', im_ann["file_name"])
  119. image = cv2.imread(img_file)
  120. return image, id_
  121. def pull_anno(self, index):
  122. img_id = self.ids[index]
  123. im_ann = self.coco.loadImgs(img_id)[0]
  124. anno_ids = self.coco.getAnnIds(imgIds=[int(img_id)], iscrowd=0)
  125. annotations = self.coco.loadAnns(anno_ids)
  126. # image infor
  127. width = im_ann['width']
  128. height = im_ann['height']
  129. #load a target
  130. bboxes = []
  131. labels = []
  132. for anno in annotations:
  133. if 'bbox' in anno and anno['area'] > 0:
  134. # bbox
  135. x1 = np.max((0, anno['bbox'][0]))
  136. y1 = np.max((0, anno['bbox'][1]))
  137. x2 = np.min((width - 1, x1 + np.max((0, anno['bbox'][2] - 1))))
  138. y2 = np.min((height - 1, y1 + np.max((0, anno['bbox'][3] - 1))))
  139. if x2 <= x1 or y2 <= y1:
  140. continue
  141. # class label
  142. cls_id = self.class_ids.index(anno['category_id'])
  143. bboxes.append([x1, y1, x2, y2])
  144. labels.append(cls_id)
  145. # guard against no boxes via resizing
  146. bboxes = np.array(bboxes).reshape(-1, 4)
  147. labels = np.array(labels).reshape(-1)
  148. return bboxes, labels
  149. if __name__ == "__main__":
  150. import time
  151. import argparse
  152. from build import build_transform
  153. parser = argparse.ArgumentParser(description='WiderFace-Dataset')
  154. # opt
  155. parser.add_argument('--root', default='/Users/liuhaoran/Desktop/python_work/object-detection/dataset/WiderFace/',
  156. help='data root')
  157. parser.add_argument('-size', '--img_size', default=640, type=int,
  158. help='input image size.')
  159. parser.add_argument('--aug_type', type=str, default='ssd',
  160. help='augmentation type')
  161. parser.add_argument('--mosaic', default=0., type=float,
  162. help='mosaic augmentation.')
  163. parser.add_argument('--mixup', default=0., type=float,
  164. help='mixup augmentation.')
  165. parser.add_argument('--mixup_type', type=str, default='yolov5_mixup',
  166. help='mixup augmentation.')
  167. parser.add_argument('--is_train', action="store_true", default=False,
  168. help='mixup augmentation.')
  169. args = parser.parse_args()
  170. trans_config = {
  171. 'aug_type': args.aug_type, # optional: ssd, yolov5
  172. 'pixel_mean': [0., 0., 0.],
  173. 'pixel_std': [255., 255., 255.],
  174. # Basic Augment
  175. 'degrees': 0.0,
  176. 'translate': 0.2,
  177. 'scale': [0.1, 2.0],
  178. 'shear': 0.0,
  179. 'perspective': 0.0,
  180. 'hsv_h': 0.015,
  181. 'hsv_s': 0.7,
  182. 'hsv_v': 0.4,
  183. 'use_ablu': True,
  184. # Mosaic & Mixup
  185. 'mosaic_prob': args.mosaic,
  186. 'mixup_prob': args.mixup,
  187. 'mosaic_type': 'yolov5_mosaic',
  188. 'mixup_type': args.mixup_type, # optional: yolov5_mixup, yolox_mixup
  189. 'mosaic_keep_ratio': False,
  190. 'mixup_scale': [0.5, 1.5]
  191. }
  192. transform, trans_cfg = build_transform(args, trans_config, 32, args.is_train)
  193. pixel_mean = transform.pixel_mean
  194. pixel_std = transform.pixel_std
  195. color_format = transform.color_format
  196. dataset = WiderFaceDataset(
  197. img_size=args.img_size,
  198. data_dir=args.root,
  199. image_set='val',
  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. t0 = time.time()
  210. image, target, deltas = dataset.pull_item(i)
  211. print("Load data: {} s".format(time.time() - t0))
  212. # to numpy
  213. image = image.permute(1, 2, 0).numpy()
  214. # denormalize
  215. image = image * pixel_std + pixel_mean
  216. if color_format == 'rgb':
  217. # RGB to BGR
  218. image = image[..., (2, 1, 0)]
  219. # to uint8
  220. image = image.astype(np.uint8)
  221. image = image.copy()
  222. img_h, img_w = image.shape[:2]
  223. boxes = target["boxes"]
  224. labels = target["labels"]
  225. for box, label in zip(boxes, labels):
  226. x1, y1, x2, y2 = box
  227. cls_id = int(label)
  228. color = class_colors[cls_id]
  229. # class name
  230. label = widerface_class_labels[cls_id]
  231. image = cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), (0,0,255), 2)
  232. # put the test on the bbox
  233. cv2.putText(image, label, (int(x1), int(y1 - 5)), 0, 0.5, color, 1, lineType=cv2.LINE_AA)
  234. cv2.imshow('gt', image)
  235. # cv2.imwrite(str(i)+'.jpg', img)
  236. cv2.waitKey(0)