voc_evaluator.py 13 KB

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