voc_evaluator.py 13 KB

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