voc_evaluator.py 13 KB

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