voc_eval.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. # --------------------------------------------------------
  2. # Fast/er R-CNN
  3. # Licensed under The MIT License [see LICENSE for details]
  4. # Written by Bharath Hariharan
  5. # --------------------------------------------------------
  6. import xml.etree.ElementTree as ET
  7. import os
  8. import cPickle
  9. import numpy as np
  10. def parse_rec(filename):
  11. """ Parse a PASCAL VOC xml file """
  12. tree = ET.parse(filename)
  13. objects = []
  14. for obj in tree.findall('object'):
  15. obj_struct = {}
  16. obj_struct['name'] = obj.find('name').text
  17. #obj_struct['pose'] = obj.find('pose').text
  18. #obj_struct['truncated'] = int(obj.find('truncated').text)
  19. obj_struct['difficult'] = int(obj.find('difficult').text)
  20. bbox = obj.find('bndbox')
  21. obj_struct['bbox'] = [int(bbox.find('xmin').text),
  22. int(bbox.find('ymin').text),
  23. int(bbox.find('xmax').text),
  24. int(bbox.find('ymax').text)]
  25. objects.append(obj_struct)
  26. return objects
  27. def voc_ap(rec, prec, use_07_metric=False):
  28. """ ap = voc_ap(rec, prec, [use_07_metric])
  29. Compute VOC AP given precision and recall.
  30. If use_07_metric is true, uses the
  31. VOC 07 11 point method (default:False).
  32. """
  33. if use_07_metric:
  34. # 11 point metric
  35. ap = 0.
  36. for t in np.arange(0., 1.1, 0.1):
  37. if np.sum(rec >= t) == 0:
  38. p = 0
  39. else:
  40. p = np.max(prec[rec >= t])
  41. ap = ap + p / 11.
  42. else:
  43. # correct AP calculation
  44. # first append sentinel values at the end
  45. mrec = np.concatenate(([0.], rec, [1.]))
  46. mpre = np.concatenate(([0.], prec, [0.]))
  47. # compute the precision envelope
  48. for i in range(mpre.size - 1, 0, -1):
  49. mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
  50. # to calculate area under PR curve, look for points
  51. # where X axis (recall) changes value
  52. i = np.where(mrec[1:] != mrec[:-1])[0]
  53. # and sum (\Delta recall) * prec
  54. ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
  55. return ap
  56. def voc_eval(detpath,
  57. annopath,
  58. imagesetfile,
  59. classname,
  60. cachedir,
  61. ovthresh=0.5,
  62. use_07_metric=False):
  63. """rec, prec, ap = voc_eval(detpath,
  64. annopath,
  65. imagesetfile,
  66. classname,
  67. [ovthresh],
  68. [use_07_metric])
  69. Top level function that does the PASCAL VOC evaluation.
  70. detpath: Path to detections
  71. detpath.format(classname) should produce the detection results file.
  72. annopath: Path to annotations
  73. annopath.format(imagename) should be the xml annotations file.
  74. imagesetfile: Text file containing the list of images, one image per line.
  75. classname: Category name (duh)
  76. cachedir: Directory for caching the annotations
  77. [ovthresh]: Overlap threshold (default = 0.5)
  78. [use_07_metric]: Whether to use VOC07's 11 point AP computation
  79. (default False)
  80. """
  81. # assumes detections are in detpath.format(classname)
  82. # assumes annotations are in annopath.format(imagename)
  83. # assumes imagesetfile is a text file with each line an image name
  84. # cachedir caches the annotations in a pickle file
  85. # first load gt
  86. if not os.path.isdir(cachedir):
  87. os.mkdir(cachedir)
  88. cachefile = os.path.join(cachedir, 'annots.pkl')
  89. # read list of images
  90. with open(imagesetfile, 'r') as f:
  91. lines = f.readlines()
  92. imagenames = [x.strip() for x in lines]
  93. if not os.path.isfile(cachefile):
  94. # load annots
  95. recs = {}
  96. for i, imagename in enumerate(imagenames):
  97. recs[imagename] = parse_rec(annopath.format(imagename))
  98. if i % 100 == 0:
  99. print 'Reading annotation for {:d}/{:d}'.format(
  100. i + 1, len(imagenames))
  101. # save
  102. print 'Saving cached annotations to {:s}'.format(cachefile)
  103. with open(cachefile, 'w') as f:
  104. cPickle.dump(recs, f)
  105. else:
  106. # load
  107. with open(cachefile, 'r') as f:
  108. recs = cPickle.load(f)
  109. # extract gt objects for this class
  110. class_recs = {}
  111. npos = 0
  112. for imagename in imagenames:
  113. R = [obj for obj in recs[imagename] if obj['name'] == classname]
  114. bbox = np.array([x['bbox'] for x in R])
  115. difficult = np.array([x['difficult'] for x in R]).astype(np.bool)
  116. det = [False] * len(R)
  117. npos = npos + sum(~difficult)
  118. class_recs[imagename] = {'bbox': bbox,
  119. 'difficult': difficult,
  120. 'det': det}
  121. # read dets
  122. detfile = detpath.format(classname)
  123. with open(detfile, 'r') as f:
  124. lines = f.readlines()
  125. splitlines = [x.strip().split(' ') for x in lines]
  126. image_ids = [x[0] for x in splitlines]
  127. confidence = np.array([float(x[1]) for x in splitlines])
  128. BB = np.array([[float(z) for z in x[2:]] for x in splitlines])
  129. # sort by confidence
  130. sorted_ind = np.argsort(-confidence)
  131. sorted_scores = np.sort(-confidence)
  132. BB = BB[sorted_ind, :]
  133. image_ids = [image_ids[x] for x in sorted_ind]
  134. # go down dets and mark TPs and FPs
  135. nd = len(image_ids)
  136. tp = np.zeros(nd)
  137. fp = np.zeros(nd)
  138. for d in range(nd):
  139. R = class_recs[image_ids[d]]
  140. bb = BB[d, :].astype(float)
  141. ovmax = -np.inf
  142. BBGT = R['bbox'].astype(float)
  143. if BBGT.size > 0:
  144. # compute overlaps
  145. # intersection
  146. ixmin = np.maximum(BBGT[:, 0], bb[0])
  147. iymin = np.maximum(BBGT[:, 1], bb[1])
  148. ixmax = np.minimum(BBGT[:, 2], bb[2])
  149. iymax = np.minimum(BBGT[:, 3], bb[3])
  150. iw = np.maximum(ixmax - ixmin + 1., 0.)
  151. ih = np.maximum(iymax - iymin + 1., 0.)
  152. inters = iw * ih
  153. # union
  154. uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +
  155. (BBGT[:, 2] - BBGT[:, 0] + 1.) *
  156. (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)
  157. overlaps = inters / uni
  158. ovmax = np.max(overlaps)
  159. jmax = np.argmax(overlaps)
  160. if ovmax > ovthresh:
  161. if not R['difficult'][jmax]:
  162. if not R['det'][jmax]:
  163. tp[d] = 1.
  164. R['det'][jmax] = 1
  165. else:
  166. fp[d] = 1.
  167. else:
  168. fp[d] = 1.
  169. # compute precision recall
  170. fp = np.cumsum(fp)
  171. tp = np.cumsum(tp)
  172. rec = tp / float(npos)
  173. # avoid divide by zero in case the first detection matches a difficult
  174. # ground truth
  175. prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
  176. ap = voc_ap(rec, prec, use_07_metric)
  177. return rec, prec, ap