voc_eval_py3.py 6.8 KB

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