voc_evaluator.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. """Adapted from:
  2. @longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch
  3. @rbgirshick py-faster-rcnn https://github.com/rbgirshick/py-faster-rcnn
  4. Licensed under The MIT License [see LICENSE for details]
  5. """
  6. from dataset.voc import VOCDataset, VOC_CLASSES
  7. import os
  8. import time
  9. import numpy as np
  10. import pickle
  11. import xml.etree.ElementTree as ET
  12. from utils.box_ops import rescale_bboxes
  13. class VOCAPIEvaluator():
  14. """ VOC AP Evaluation class """
  15. def __init__(self,
  16. cfg,
  17. data_dir,
  18. device,
  19. transform,
  20. set_type='test',
  21. year='2007',
  22. display=False):
  23. # basic config
  24. self.data_dir = data_dir
  25. self.device = device
  26. self.labelmap = VOC_CLASSES
  27. self.set_type = set_type
  28. self.year = year
  29. self.display = display
  30. self.map = 0.
  31. # transform
  32. self.transform = transform
  33. # path
  34. time_stamp = time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime(time.time()))
  35. self.devkit_path = os.path.join(data_dir, 'VOC' + year)
  36. self.annopath = os.path.join(data_dir, 'VOC2007', 'Annotations', '%s.xml')
  37. self.imgpath = os.path.join(data_dir, 'VOC2007', 'JPEGImages', '%s.jpg')
  38. self.imgsetpath = os.path.join(data_dir, 'VOC2007', 'ImageSets', 'Main', set_type+'.txt')
  39. self.output_dir = self.get_output_dir('det_results/eval/voc_eval/{}'.format(time_stamp), self.set_type)
  40. # dataset
  41. self.dataset = VOCDataset(
  42. cfg=cfg,
  43. data_dir=data_dir,
  44. image_set=[('2007', set_type)],
  45. is_train=False)
  46. def evaluate(self, net):
  47. net.eval()
  48. num_images = len(self.dataset)
  49. # all detections are collected into:
  50. # all_boxes[cls][image] = N x 5 array of detections in
  51. # (x1, y1, x2, y2, score)
  52. self.all_boxes = [[[] for _ in range(num_images)]
  53. for _ in range(len(self.labelmap))]
  54. # timers
  55. det_file = os.path.join(self.output_dir, 'detections.pkl')
  56. for i in range(num_images):
  57. img, _ = self.dataset.pull_image(i)
  58. orig_h, orig_w = img.shape[:2]
  59. # preprocess
  60. x, _, ratio = self.transform(img)
  61. x = x.unsqueeze(0).to(self.device)
  62. # forward
  63. t0 = time.time()
  64. outputs = net(x)
  65. scores = outputs['scores']
  66. labels = outputs['labels']
  67. bboxes = outputs['bboxes']
  68. detect_time = time.time() - t0
  69. # rescale bboxes
  70. bboxes = rescale_bboxes(bboxes, [orig_w, orig_h], ratio)
  71. for j in range(len(self.labelmap)):
  72. inds = np.where(labels == j)[0]
  73. if len(inds) == 0:
  74. self.all_boxes[j][i] = np.empty([0, 5], dtype=np.float32)
  75. continue
  76. c_bboxes = bboxes[inds]
  77. c_scores = scores[inds]
  78. c_dets = np.hstack((c_bboxes,
  79. c_scores[:, np.newaxis])).astype(np.float32,
  80. copy=False)
  81. self.all_boxes[j][i] = c_dets
  82. if i % 500 == 0:
  83. print('im_detect: {:d}/{:d} {:.3f}s'.format(i + 1, num_images, detect_time))
  84. with open(det_file, 'wb') as f:
  85. pickle.dump(self.all_boxes, f, pickle.HIGHEST_PROTOCOL)
  86. print('Evaluating detections')
  87. self.evaluate_detections(self.all_boxes)
  88. print('Mean AP: ', self.map)
  89. def parse_rec(self, filename):
  90. """ Parse a PASCAL VOC xml file """
  91. tree = ET.parse(filename)
  92. objects = []
  93. for obj in tree.findall('object'):
  94. obj_struct = {}
  95. obj_struct['name'] = obj.find('name').text
  96. obj_struct['pose'] = obj.find('pose').text
  97. obj_struct['truncated'] = int(obj.find('truncated').text)
  98. obj_struct['difficult'] = int(obj.find('difficult').text)
  99. bbox = obj.find('bndbox')
  100. obj_struct['bbox'] = [int(bbox.find('xmin').text),
  101. int(bbox.find('ymin').text),
  102. int(bbox.find('xmax').text),
  103. int(bbox.find('ymax').text)]
  104. objects.append(obj_struct)
  105. return objects
  106. def get_output_dir(self, name, phase):
  107. """Return the directory where experimental artifacts are placed.
  108. If the directory does not exist, it is created.
  109. A canonical path is built using the name from an imdb and a network
  110. (if not None).
  111. """
  112. filedir = os.path.join(name, phase)
  113. if not os.path.exists(filedir):
  114. os.makedirs(filedir, exist_ok=True)
  115. return filedir
  116. def get_voc_results_file_template(self, cls):
  117. # VOCdevkit/VOC2007/results/det_test_aeroplane.txt
  118. filename = 'det_' + self.set_type + '_%s.txt' % (cls)
  119. filedir = os.path.join(self.devkit_path, 'results')
  120. if not os.path.exists(filedir):
  121. os.makedirs(filedir)
  122. path = os.path.join(filedir, filename)
  123. return path
  124. def write_voc_results_file(self, all_boxes):
  125. for cls_ind, cls in enumerate(self.labelmap):
  126. if self.display:
  127. print('Writing {:s} VOC results file'.format(cls))
  128. filename = self.get_voc_results_file_template(cls)
  129. with open(filename, 'wt') as f:
  130. for im_ind, index in enumerate(self.dataset.ids):
  131. dets = all_boxes[cls_ind][im_ind]
  132. if len(dets) == 0:
  133. continue
  134. # the VOCdevkit expects 1-based indices
  135. for k in range(dets.shape[0]):
  136. f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'.
  137. format(index[1], dets[k, -1],
  138. dets[k, 0] + 1, dets[k, 1] + 1,
  139. dets[k, 2] + 1, dets[k, 3] + 1))
  140. def do_python_eval(self, use_07=True):
  141. cachedir = os.path.join(self.devkit_path, 'annotations_cache')
  142. aps = []
  143. # The PASCAL VOC metric changed in 2010
  144. use_07_metric = use_07
  145. print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No'))
  146. if not os.path.isdir(self.output_dir):
  147. os.mkdir(self.output_dir)
  148. for i, cls in enumerate(self.labelmap):
  149. filename = self.get_voc_results_file_template(cls)
  150. rec, prec, ap = self.voc_eval(detpath=filename,
  151. classname=cls,
  152. cachedir=cachedir,
  153. ovthresh=0.5,
  154. use_07_metric=use_07_metric
  155. )
  156. aps += [ap]
  157. print('AP for {} = {:.4f}'.format(cls, ap))
  158. with open(os.path.join(self.output_dir, cls + '_pr.pkl'), 'wb') as f:
  159. pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)
  160. if self.display:
  161. self.map = np.mean(aps)
  162. print('Mean AP = {:.4f}'.format(np.mean(aps)))
  163. print('~~~~~~~~')
  164. print('Results:')
  165. for ap in aps:
  166. print('{:.3f}'.format(ap))
  167. print('{:.3f}'.format(np.mean(aps)))
  168. print('~~~~~~~~')
  169. print('')
  170. print('--------------------------------------------------------------')
  171. print('Results computed with the **unofficial** Python eval code.')
  172. print('Results should be very close to the official MATLAB eval code.')
  173. print('--------------------------------------------------------------')
  174. else:
  175. self.map = np.mean(aps)
  176. print('Mean AP = {:.4f}'.format(np.mean(aps)))
  177. def voc_ap(self, rec, prec, use_07_metric=True):
  178. """ ap = voc_ap(rec, prec, [use_07_metric])
  179. Compute VOC AP given precision and recall.
  180. If use_07_metric is true, uses the
  181. VOC 07 11 point method (default:True).
  182. """
  183. if use_07_metric:
  184. # 11 point metric
  185. ap = 0.
  186. for t in np.arange(0., 1.1, 0.1):
  187. if np.sum(rec >= t) == 0:
  188. p = 0
  189. else:
  190. p = np.max(prec[rec >= t])
  191. ap = ap + p / 11.
  192. else:
  193. # correct AP calculation
  194. # first append sentinel values at the end
  195. mrec = np.concatenate(([0.], rec, [1.]))
  196. mpre = np.concatenate(([0.], prec, [0.]))
  197. # compute the precision envelope
  198. for i in range(mpre.size - 1, 0, -1):
  199. mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
  200. # to calculate area under PR curve, look for points
  201. # where X axis (recall) changes value
  202. i = np.where(mrec[1:] != mrec[:-1])[0]
  203. # and sum (\Delta recall) * prec
  204. ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
  205. return ap
  206. def voc_eval(self, detpath, classname, cachedir, ovthresh=0.5, use_07_metric=True):
  207. if not os.path.isdir(cachedir):
  208. os.mkdir(cachedir)
  209. cachefile = os.path.join(cachedir, 'annots.pkl')
  210. # read list of images
  211. with open(self.imgsetpath, 'r') as f:
  212. lines = f.readlines()
  213. imagenames = [x.strip() for x in lines]
  214. if not os.path.isfile(cachefile):
  215. # load annots
  216. recs = {}
  217. for i, imagename in enumerate(imagenames):
  218. recs[imagename] = self.parse_rec(self.annopath % (imagename))
  219. if i % 100 == 0 and self.display:
  220. print('Reading annotation for {:d}/{:d}'.format(
  221. i + 1, len(imagenames)))
  222. # save
  223. if self.display:
  224. print('Saving cached annotations to {:s}'.format(cachefile))
  225. with open(cachefile, 'wb') as f:
  226. pickle.dump(recs, f)
  227. else:
  228. # load
  229. with open(cachefile, 'rb') as f:
  230. recs = pickle.load(f)
  231. # extract gt objects for this class
  232. class_recs = {}
  233. npos = 0
  234. for imagename in imagenames:
  235. R = [obj for obj in recs[imagename] if obj['name'] == classname]
  236. bbox = np.array([x['bbox'] for x in R])
  237. difficult = np.array([x['difficult'] for x in R]).astype(np.bool_)
  238. det = [False] * len(R)
  239. npos = npos + sum(~difficult)
  240. class_recs[imagename] = {'bbox': bbox,
  241. 'difficult': difficult,
  242. 'det': det}
  243. # read dets
  244. detfile = detpath.format(classname)
  245. with open(detfile, 'r') as f:
  246. lines = f.readlines()
  247. if any(lines) == 1:
  248. splitlines = [x.strip().split(' ') for x in lines]
  249. image_ids = [x[0] for x in splitlines]
  250. confidence = np.array([float(x[1]) for x in splitlines])
  251. BB = np.array([[float(z) for z in x[2:]] for x in splitlines])
  252. # sort by confidence
  253. sorted_ind = np.argsort(-confidence)
  254. sorted_scores = np.sort(-confidence)
  255. BB = BB[sorted_ind, :]
  256. image_ids = [image_ids[x] for x in sorted_ind]
  257. # go down dets and mark TPs and FPs
  258. nd = len(image_ids)
  259. tp = np.zeros(nd)
  260. fp = np.zeros(nd)
  261. for d in range(nd):
  262. R = class_recs[image_ids[d]]
  263. bb = BB[d, :].astype(float)
  264. ovmax = -np.inf
  265. BBGT = R['bbox'].astype(float)
  266. if BBGT.size > 0:
  267. # compute overlaps
  268. # intersection
  269. ixmin = np.maximum(BBGT[:, 0], bb[0])
  270. iymin = np.maximum(BBGT[:, 1], bb[1])
  271. ixmax = np.minimum(BBGT[:, 2], bb[2])
  272. iymax = np.minimum(BBGT[:, 3], bb[3])
  273. iw = np.maximum(ixmax - ixmin, 0.)
  274. ih = np.maximum(iymax - iymin, 0.)
  275. inters = iw * ih
  276. uni = ((bb[2] - bb[0]) * (bb[3] - bb[1]) +
  277. (BBGT[:, 2] - BBGT[:, 0]) *
  278. (BBGT[:, 3] - BBGT[:, 1]) - inters)
  279. overlaps = inters / uni
  280. ovmax = np.max(overlaps)
  281. jmax = np.argmax(overlaps)
  282. if ovmax > ovthresh:
  283. if not R['difficult'][jmax]:
  284. if not R['det'][jmax]:
  285. tp[d] = 1.
  286. R['det'][jmax] = 1
  287. else:
  288. fp[d] = 1.
  289. else:
  290. fp[d] = 1.
  291. # compute precision recall
  292. fp = np.cumsum(fp)
  293. tp = np.cumsum(tp)
  294. rec = tp / float(npos)
  295. # avoid divide by zero in case the first detection matches a difficult
  296. # ground truth
  297. prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
  298. ap = self.voc_ap(rec, prec, use_07_metric)
  299. else:
  300. rec = -1.
  301. prec = -1.
  302. ap = -1.
  303. return rec, prec, ap
  304. def evaluate_detections(self, box_list):
  305. self.write_voc_results_file(box_list)
  306. self.do_python_eval()
  307. if __name__ == '__main__':
  308. pass