voc_evaluator.py 14 KB

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