widerface.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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) if self.mosaic_prob > 0. else None
  47. self.mixup_augment = MixupAugment(img_size, trans_config) if self.mixup_prob > 0. else None
  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. # ------------ Basic dataset function ------------
  57. def __len__(self):
  58. return len(self.ids)
  59. def __getitem__(self, index):
  60. return self.pull_item(index)
  61. # ------------ Mosaic & Mixup ------------
  62. def load_mosaic(self, index):
  63. # ------------ Prepare 4 indexes of images ------------
  64. ## Load 4x mosaic image
  65. index_list = np.arange(index).tolist() + np.arange(index+1, len(self.ids)).tolist()
  66. id1 = index
  67. id2, id3, id4 = random.sample(index_list, 3)
  68. indexs = [id1, id2, id3, id4]
  69. ## Load images and targets
  70. image_list = []
  71. target_list = []
  72. for index in indexs:
  73. img_i, target_i = self.load_image_target(index)
  74. image_list.append(img_i)
  75. target_list.append(target_i)
  76. # ------------ Mosaic augmentation ------------
  77. image, target = self.mosaic_augment(image_list, target_list)
  78. return image, target
  79. def load_mixup(self, origin_image, origin_target):
  80. # ------------ Load a new image & target ------------
  81. if self.mixup_augment.mixup_type == 'yolov5':
  82. new_index = np.random.randint(0, len(self.ids))
  83. new_image, new_target = self.load_mosaic(new_index)
  84. elif self.mixup_augment.mixup_type == 'yolox':
  85. new_index = np.random.randint(0, len(self.ids))
  86. new_image, new_target = self.load_image_target(new_index)
  87. # ------------ Mixup augmentation ------------
  88. image, target = self.mixup_augment(origin_image, origin_target, new_image, new_target)
  89. return image, target
  90. # ------------ Load data function ------------
  91. def load_image_target(self, index):
  92. # load an image
  93. image, _ = self.pull_image(index)
  94. height, width, channels = image.shape
  95. # load a target
  96. bboxes, labels = self.pull_anno(index)
  97. target = {
  98. "boxes": bboxes,
  99. "labels": labels,
  100. "orig_size": [height, width]
  101. }
  102. return image, target
  103. def pull_item(self, index):
  104. if random.random() < self.mosaic_prob:
  105. # load a mosaic image
  106. mosaic = True
  107. image, target = self.load_mosaic(index)
  108. else:
  109. mosaic = False
  110. # load an image and target
  111. image, target = self.load_image_target(index)
  112. # MixUp
  113. if random.random() < self.mixup_prob:
  114. image, target = self.load_mixup(image, target)
  115. # augment
  116. image, target, deltas = self.transform(image, target, mosaic)
  117. return image, target, deltas
  118. def pull_image(self, index):
  119. id_ = self.ids[index]
  120. im_ann = self.coco.loadImgs(id_)[0]
  121. img_file = os.path.join(
  122. self.data_dir, 'WIDER_{}'.format(self.image_set), 'images', im_ann["file_name"])
  123. image = cv2.imread(img_file)
  124. return image, id_
  125. def pull_anno(self, index):
  126. img_id = self.ids[index]
  127. im_ann = self.coco.loadImgs(img_id)[0]
  128. anno_ids = self.coco.getAnnIds(imgIds=[int(img_id)], iscrowd=0)
  129. annotations = self.coco.loadAnns(anno_ids)
  130. # image infor
  131. width = im_ann['width']
  132. height = im_ann['height']
  133. #load a target
  134. bboxes = []
  135. labels = []
  136. for anno in annotations:
  137. if 'bbox' in anno and anno['area'] > 0:
  138. # bbox
  139. x1 = np.max((0, anno['bbox'][0]))
  140. y1 = np.max((0, anno['bbox'][1]))
  141. x2 = np.min((width - 1, x1 + np.max((0, anno['bbox'][2] - 1))))
  142. y2 = np.min((height - 1, y1 + np.max((0, anno['bbox'][3] - 1))))
  143. if x2 <= x1 or y2 <= y1:
  144. continue
  145. # class label
  146. cls_id = self.class_ids.index(anno['category_id'])
  147. bboxes.append([x1, y1, x2, y2])
  148. labels.append(cls_id)
  149. # guard against no boxes via resizing
  150. bboxes = np.array(bboxes).reshape(-1, 4)
  151. labels = np.array(labels).reshape(-1)
  152. return bboxes, labels
  153. if __name__ == "__main__":
  154. import time
  155. import argparse
  156. from build import build_transform
  157. parser = argparse.ArgumentParser(description='WiderFace-Dataset')
  158. # opt
  159. parser.add_argument('--root', default='/Users/liuhaoran/Desktop/python_work/object-detection/dataset/WiderFace/',
  160. help='data root')
  161. parser.add_argument('-size', '--img_size', default=640, type=int,
  162. help='input image size.')
  163. parser.add_argument('--aug_type', type=str, default='ssd',
  164. help='augmentation type')
  165. parser.add_argument('--mosaic', default=0., type=float,
  166. help='mosaic augmentation.')
  167. parser.add_argument('--mixup', default=0., type=float,
  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, yolo
  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',
  190. 'mixup_type': 'yolov5', # optional: yolov5, yolox
  191. 'mixup_scale': [0.5, 1.5]
  192. }
  193. transform, trans_cfg = build_transform(args, trans_config, 32, args.is_train)
  194. pixel_mean = transform.pixel_mean
  195. pixel_std = transform.pixel_std
  196. color_format = transform.color_format
  197. dataset = WiderFaceDataset(
  198. img_size=args.img_size,
  199. data_dir=args.root,
  200. image_set='val',
  201. transform=transform,
  202. trans_config=trans_config,
  203. )
  204. np.random.seed(0)
  205. class_colors = [(np.random.randint(255),
  206. np.random.randint(255),
  207. np.random.randint(255)) for _ in range(80)]
  208. print('Data length: ', len(dataset))
  209. for i in range(1000):
  210. t0 = time.time()
  211. image, target, deltas = dataset.pull_item(i)
  212. print("Load data: {} s".format(time.time() - t0))
  213. # to numpy
  214. image = image.permute(1, 2, 0).numpy()
  215. # denormalize
  216. image = image * pixel_std + pixel_mean
  217. if color_format == 'rgb':
  218. # RGB to BGR
  219. image = image[..., (2, 1, 0)]
  220. # to uint8
  221. image = image.astype(np.uint8)
  222. image = image.copy()
  223. img_h, img_w = image.shape[:2]
  224. boxes = target["boxes"]
  225. labels = target["labels"]
  226. for box, label in zip(boxes, labels):
  227. x1, y1, x2, y2 = box
  228. cls_id = int(label)
  229. color = class_colors[cls_id]
  230. # class name
  231. label = widerface_class_labels[cls_id]
  232. image = cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), (0,0,255), 2)
  233. # put the test on the bbox
  234. cv2.putText(image, label, (int(x1), int(y1 - 5)), 0, 0.5, color, 1, lineType=cv2.LINE_AA)
  235. cv2.imshow('gt', image)
  236. # cv2.imwrite(str(i)+'.jpg', img)
  237. cv2.waitKey(0)