voc.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import cv2
  2. import random
  3. import numpy as np
  4. import os.path as osp
  5. import xml.etree.ElementTree as ET
  6. import torch.utils.data as data
  7. try:
  8. from .data_augment.strong_augment import MosaicAugment, MixupAugment
  9. except:
  10. from data_augment.strong_augment import MosaicAugment, MixupAugment
  11. # VOC class names
  12. VOC_CLASSES = ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor')
  13. class VOCAnnotationTransform(object):
  14. """Transforms a VOC annotation into a Tensor of bbox coords and label index
  15. Initilized with a dictionary lookup of classnames to indexes
  16. Arguments:
  17. class_to_ind (dict, optional): dictionary lookup of classnames -> indexes
  18. (default: alphabetic indexing of VOC's 20 classes)
  19. keep_difficult (bool, optional): keep difficult instances or not
  20. (default: False)
  21. height (int): height
  22. width (int): width
  23. """
  24. def __init__(self, class_to_ind=None, keep_difficult=False):
  25. self.class_to_ind = class_to_ind or dict(
  26. zip(VOC_CLASSES, range(len(VOC_CLASSES))))
  27. self.keep_difficult = keep_difficult
  28. def __call__(self, target):
  29. """
  30. Arguments:
  31. target (annotation) : the target annotation to be made usable
  32. will be an ET.Element
  33. Returns:
  34. a list containing lists of bounding boxes [bbox coords, class name]
  35. """
  36. res = []
  37. for obj in target.iter('object'):
  38. difficult = int(obj.find('difficult').text) == 1
  39. if not self.keep_difficult and difficult:
  40. continue
  41. name = obj.find('name').text.lower().strip()
  42. bbox = obj.find('bndbox')
  43. pts = ['xmin', 'ymin', 'xmax', 'ymax']
  44. bndbox = []
  45. for i, pt in enumerate(pts):
  46. cur_pt = int(bbox.find(pt).text) - 1
  47. # scale height or width
  48. cur_pt = cur_pt if i % 2 == 0 else cur_pt
  49. bndbox.append(cur_pt)
  50. label_idx = self.class_to_ind[name]
  51. bndbox.append(label_idx)
  52. res += [bndbox] # [x1, y1, x2, y2, label_ind]
  53. return res # [[x1, y1, x2, y2, label_ind], ... ]
  54. class VOCDataset(data.Dataset):
  55. def __init__(self,
  56. img_size :int = 640,
  57. data_dir :str = None,
  58. image_sets = [('2007', 'trainval'), ('2012', 'trainval')],
  59. trans_config = None,
  60. transform = None,
  61. is_train :bool = False,
  62. ):
  63. # ----------- Basic parameters -----------
  64. self.img_size = img_size
  65. self.image_set = image_sets
  66. self.is_train = is_train
  67. self.target_transform = VOCAnnotationTransform()
  68. # ----------- Path parameters -----------
  69. self.root = data_dir
  70. self._annopath = osp.join('%s', 'Annotations', '%s.xml')
  71. self._imgpath = osp.join('%s', 'JPEGImages', '%s.jpg')
  72. # ----------- Data parameters -----------
  73. self.ids = list()
  74. for (year, name) in image_sets:
  75. rootpath = osp.join(self.root, 'VOC' + year)
  76. for line in open(osp.join(rootpath, 'ImageSets', 'Main', name + '.txt')):
  77. self.ids.append((rootpath, line.strip()))
  78. self.dataset_size = len(self.ids)
  79. # ----------- Transform parameters -----------
  80. self.trans_config = trans_config
  81. self.transform = transform
  82. # ----------- Strong augmentation -----------
  83. if is_train:
  84. self.mosaic_prob = trans_config['mosaic_prob'] if trans_config else 0.0
  85. self.mixup_prob = trans_config['mixup_prob'] if trans_config else 0.0
  86. self.mosaic_augment = MosaicAugment(img_size, trans_config, is_train) if self.mosaic_prob > 0. else None
  87. self.mixup_augment = MixupAugment(img_size, trans_config) if self.mixup_prob > 0. else None
  88. else:
  89. self.mosaic_prob = 0.0
  90. self.mixup_prob = 0.0
  91. self.mosaic_augment = None
  92. self.mixup_augment = None
  93. print('==============================')
  94. print('use Mosaic Augmentation: {}'.format(self.mosaic_prob))
  95. print('use Mixup Augmentation: {}'.format(self.mixup_prob))
  96. # ------------ Basic dataset function ------------
  97. def __getitem__(self, index):
  98. image, target, deltas = self.pull_item(index)
  99. return image, target, deltas
  100. def __len__(self):
  101. return self.dataset_size
  102. # ------------ Mosaic & Mixup ------------
  103. def load_mosaic(self, index):
  104. # ------------ Prepare 4 indexes of images ------------
  105. ## Load 4x mosaic image
  106. index_list = np.arange(index).tolist() + np.arange(index+1, len(self.ids)).tolist()
  107. id1 = index
  108. id2, id3, id4 = random.sample(index_list, 3)
  109. indexs = [id1, id2, id3, id4]
  110. ## Load images and targets
  111. image_list = []
  112. target_list = []
  113. for index in indexs:
  114. img_i, target_i = self.load_image_target(index)
  115. image_list.append(img_i)
  116. target_list.append(target_i)
  117. # ------------ Mosaic augmentation ------------
  118. image, target = self.mosaic_augment(image_list, target_list)
  119. return image, target
  120. def load_mixup(self, origin_image, origin_target):
  121. # ------------ Load a new image & target ------------
  122. if self.mixup_augment.mixup_type == 'yolov5':
  123. new_index = np.random.randint(0, len(self.ids))
  124. new_image, new_target = self.load_mosaic(new_index)
  125. elif self.mixup_augment.mixup_type == 'yolox':
  126. new_index = np.random.randint(0, len(self.ids))
  127. new_image, new_target = self.load_image_target(new_index)
  128. # ------------ Mixup augmentation ------------
  129. image, target = self.mixup_augment(origin_image, origin_target, new_image, new_target)
  130. return image, target
  131. # ------------ Load data function ------------
  132. def load_image_target(self, index):
  133. # load an image
  134. image, _ = self.pull_image(index)
  135. height, width, channels = image.shape
  136. # laod an annotation
  137. anno, _ = self.pull_anno(index)
  138. # guard against no boxes via resizing
  139. anno = np.array(anno).reshape(-1, 5)
  140. target = {
  141. "boxes": anno[:, :4],
  142. "labels": anno[:, 4],
  143. "orig_size": [height, width]
  144. }
  145. return image, target
  146. def pull_item(self, index):
  147. if random.random() < self.mosaic_prob:
  148. # load a mosaic image
  149. mosaic = True
  150. image, target = self.load_mosaic(index)
  151. else:
  152. mosaic = False
  153. # load an image and target
  154. image, target = self.load_image_target(index)
  155. # MixUp
  156. if random.random() < self.mixup_prob:
  157. image, target = self.load_mixup(image, target)
  158. # augment
  159. image, target, deltas = self.transform(image, target, mosaic)
  160. return image, target, deltas
  161. def pull_image(self, index):
  162. img_id = self.ids[index]
  163. image = cv2.imread(self._imgpath % img_id, cv2.IMREAD_COLOR)
  164. return image, img_id
  165. def pull_anno(self, index):
  166. img_id = self.ids[index]
  167. anno = ET.parse(self._annopath % img_id).getroot()
  168. anno = self.target_transform(anno)
  169. return anno, img_id
  170. if __name__ == "__main__":
  171. import time
  172. import argparse
  173. from build import build_transform
  174. parser = argparse.ArgumentParser(description='VOC-Dataset')
  175. # opt
  176. parser.add_argument('--root', default='/Users/liuhaoran/Desktop/python_work/object-detection/dataset/VOCdevkit/',
  177. help='data root')
  178. parser.add_argument('-size', '--img_size', default=640, type=int,
  179. help='input image size.')
  180. parser.add_argument('--aug_type', type=str, default='ssd',
  181. help='augmentation type: ssd, yolo.')
  182. parser.add_argument('--mosaic', default=0., type=float,
  183. help='mosaic augmentation.')
  184. parser.add_argument('--mixup', default=0., type=float,
  185. help='mixup augmentation.')
  186. parser.add_argument('--mixup_type', type=str, default='yolov5_mixup',
  187. help='mixup augmentation.')
  188. parser.add_argument('--is_train', action="store_true", default=False,
  189. help='mixup augmentation.')
  190. args = parser.parse_args()
  191. trans_config = {
  192. 'aug_type': args.aug_type, # optional: ssd, yolov5
  193. 'pixel_mean': [123.675, 116.28, 103.53],
  194. 'pixel_std': [58.395, 57.12, 57.375],
  195. 'use_ablu': True,
  196. # Basic Augment
  197. 'affine_params': {
  198. 'degrees': 0.0,
  199. 'translate': 0.2,
  200. 'scale': [0.1, 2.0],
  201. 'shear': 0.0,
  202. 'perspective': 0.0,
  203. 'hsv_h': 0.015,
  204. 'hsv_s': 0.7,
  205. 'hsv_v': 0.4,
  206. },
  207. # Mosaic & Mixup
  208. 'mosaic_keep_ratio': False,
  209. 'mosaic_prob': args.mosaic,
  210. 'mixup_prob': args.mixup,
  211. 'mosaic_type': 'yolov5',
  212. 'mixup_type': 'yolov5',
  213. 'mixup_scale': [0.5, 1.5]
  214. }
  215. transform, trans_cfg = build_transform(args, trans_config, 32, args.is_train)
  216. pixel_mean = transform.pixel_mean
  217. pixel_std = transform.pixel_std
  218. color_format = transform.color_format
  219. dataset = VOCDataset(
  220. img_size=args.img_size,
  221. data_dir=args.root,
  222. image_sets=[('2007', 'trainval'), ('2012', 'trainval')] if args.is_train else [('2007', 'test')],
  223. trans_config=trans_config,
  224. transform=transform,
  225. is_train=args.is_train,
  226. )
  227. np.random.seed(0)
  228. class_colors = [(np.random.randint(255),
  229. np.random.randint(255),
  230. np.random.randint(255)) for _ in range(20)]
  231. print('Data length: ', len(dataset))
  232. for i in range(1000):
  233. t0 = time.time()
  234. image, target, deltas = dataset.pull_item(i)
  235. print("Load data: {} s".format(time.time() - t0))
  236. # to numpy
  237. image = image.permute(1, 2, 0).numpy()
  238. # denormalize
  239. image = image * pixel_std + pixel_mean
  240. if color_format == 'rgb':
  241. # RGB to BGR
  242. image = image[..., (2, 1, 0)]
  243. # to uint8
  244. image = image.astype(np.uint8)
  245. image = image.copy()
  246. img_h, img_w = image.shape[:2]
  247. boxes = target["boxes"]
  248. labels = target["labels"]
  249. for box, label in zip(boxes, labels):
  250. x1, y1, x2, y2 = box
  251. if x2 - x1 > 1 and y2 - y1 > 1:
  252. cls_id = int(label)
  253. color = class_colors[cls_id]
  254. # class name
  255. label = VOC_CLASSES[cls_id]
  256. image = cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), color, 2)
  257. # put the test on the bbox
  258. cv2.putText(image, label, (int(x1), int(y1 - 5)), 0, 0.5, color, 1, lineType=cv2.LINE_AA)
  259. cv2.imshow('gt', image)
  260. # cv2.imwrite(str(i)+'.jpg', img)
  261. cv2.waitKey(0)