voc_evaluator.py 13 KB

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