voc_evaluator.py 13 KB

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