Detection基础模块之(二)mAP

关于PR曲线、Precision、Recall、TP、FP、FN等概念的细节可参考机器学习评价指标合辑

关于IoU的概念和实现可参考IoU

  • mAP: mean Average Precision, 即各类别AP的平均值

  • AP: PR曲线下面积,其实是在0~1之间所有recall值的precision的平均值。

  • PR曲线: Precision-Recall曲线

  • Precision: TP / (TP + FP)

  • Recall: TP / (TP + FN)

  • TP: IoU>Threshold的检测框数量(同一Ground Truth只计算一次)

  • FP: IoU<=Threshold的检测框,或者是检测到同一个GT的多余检测框的数量

  • FN: 没有检测到的GT的数量

  • TN:不使用。

2.关于AP与PR曲线的面积

由前面定义,我们可以知道,要计算mAP必须先绘出各类别PR曲线,计算出AP。

1)积分求解

AP既然是PR曲线下的面积,那么可以通过积分来求解,即

          《Detection基础模块之(二)mAP》

2)插值求解

但通常情况下都是使用估算或者插值的方式计算:

(1)approximated average precision:

         估算计算方式

         《Detection基础模块之(二)mAP》

(2)Interpolated average precision

         插值计算方式

         《Detection基础模块之(二)mAP》

         《Detection基础模块之(二)mAP》

  • k 为每一个样本点的索引,参与计算的是所有样本点

  • 《Detection基础模块之(二)mAP》取第 k 个样本点之后的样本中的最大值。

(3)插值方式进一步演变

         《Detection基础模块之(二)mAP》

         《Detection基础模块之(二)mAP》

         这是通常意义上的 Interpolated 形式的 AP,VOC10后采用此方式。

3.VOC采取的两种插值方式

如何采样PR曲线,VOC采用过两种不同方法。

参见:The PASCAL Visual Object Classes Challenge 2012 (VOC2012) Development Kit

在VOC2010以前,只需要选取当Recall >= 0, 0.1, 0.2, …, 1共11个点时的Precision最大值,然后AP就是这11个Precision的平均值。在VOC2010及以后,需要针对每一个不同的Recall值(包括0和1),选取其大于等于这些Recall值时的Precision最大值,然后计算PR曲线下面积作为AP值。

1)11-point interpolation(VOC07,10之前)

11-point interpolation通过平均一组11个等间距的Recall值[0,0.1,0.2,…,1]对应的Precision来绘制P-R曲线.

计算precision时采用一种插值方法(interpolate),即对于某个recall值r,precision值取所有recall>=r中的最大值(这样保证了p-r曲线是单调递减的,避免曲线出现抖动)

《Detection基础模块之(二)mAP》

《Detection基础模块之(二)mAP》

 2)Interpolating all points(VOC10之后)

 

不再是对召回率在[0,1]之间的均匀分布的11个点,而是对每个不同的recall值都计算一个ρinterp(r),然后求平均,r取recall>=r+1的最大precision值。

《Detection基础模块之(二)mAP》

 

4.mAP计算示例(两种VOC方式比较)

一个例子有助于我们更好地理解插值平均精度的概念。 考虑下面的检测:

有7个图像,其中15个ground truth objects由绿色边界框表示,24个检测到的对象由红色边界框表示。 每个检测到的对象由字母(A,B,…,Y)标识,且具有confidence。

《Detection基础模块之(二)mAP》

 

下表显示了具有相应置信度的边界框。 最后一列将检测标识为TP或FP。 在此示例中,如果IOU>=30%,则考虑TP,否则为FP。 通过查看上面的图像,我们可以粗略地判断检测是TP还是FP。

《Detection基础模块之(二)mAP》

 

在一些图像中,存在多于一个与同一个ground truth重叠的检测结果(图像2,3,4,5,6和7)。 对于这些情况,选择具有最高IOU的检测框,丢弃其他框。 此规则由PASCAL VOC 2012度量标准应用:“例如,单个对象的5个检测(TP)被计为1个正确检测和4个错误检测”。

通过计算累积的TP或FP检测的precision和recall来绘制P-R曲线。 为此,首先我们需要通过置信度对检测进行排序,然后我们计算每个检测的precision和recall,如下表所示:

《Detection基础模块之(二)mAP》

 

根据precision和recall值绘制P-R曲线如下图

《Detection基础模块之(二)mAP》

 

如前所述,有两种不同的方法可以测量插值AP:11点插值和插值所有点。 下面我们在它们之间进行比较:

1)计算11-point interpolation

11-point interpolation AP是在一组11个recall levels(0,0.1,…,1)处的平均精度。 插值精度值是通过采用其recall大于当前recall值的最大precision获得,如下图所示:

《Detection基础模块之(二)mAP》

 

通过使用11-point interpolation,我们得到

《Detection基础模块之(二)mAP》

《Detection基础模块之(二)mAP》

                                        AP = 26.84%

 

2)计算在所有点中执行的插值

通过插值所有点,AP可以看作P-R曲线的AUC的近似值。 目的是减少曲线中摆动的影响。 通过应用之前给出的方程,我们可以获得这里将要展示的区域。 我们还可以通过查看从最高(0.4666)到0(从右到左看图)的recall来直观地获得插值precision,并且当我们减少recall时,我们获得最高的precision值如下图所示:

《Detection基础模块之(二)mAP》

 

看一下上图,我们可以将AUC划分为4个区域(A1,A2,A3和A4):

《Detection基础模块之(二)mAP》

 

计算总面积,可以得到AP:

《Detection基础模块之(二)mAP》

 

两种不同插值方法之间的结果略有不同:分别通过每点插值和11点插值分别为24.56%和26.84%。

5.VOC方式代码实现

Facebook开源的Detectron包含VOC数据集的mAP计算,这里贴出其核心实现,以对mAP的计算有更深入的理解。

1)读取xml文件


 
 
  1. def parse_rec(filename):
  2.       """Parse a PASCAL VOC xml file."""
  3.      tree = ET.parse(filename)
  4.      objects = []
  5.       for obj in tree.findall( 'object'):
  6.          obj_struct = {}
  7.          obj_struct[ 'name'] = obj.find( 'name').text
  8.          obj_struct[ 'pose'] = obj.find( 'pose').text
  9.          obj_struct[ 'truncated'] = int(obj.find( 'truncated').text)
  10.          obj_struct[ 'difficult'] = int(obj.find( 'difficult').text)
  11.          bbox = obj.find( 'bndbox')
  12.          obj_struct[ 'bbox'] = [int(bbox.find( 'xmin').text),
  13.                                int(bbox.find( 'ymin').text),
  14.                                int(bbox.find( 'xmax').text),
  15.                                int(bbox.find( 'ymax').text)]
  16.          objects.append(obj_struct)
  17.  ​
  18.       return objects

2)计算precision和recall:

模型的输出包含bbox和对应的置信度(confidence),首先按照置信度降序排序,每添加一个样本,阈值就降低一点(真实情况下阈值降低,iou不一定降低,iounet就是对这里进行了改进)。这样就有多个阈值,每个阈值下分别计算对应的precision和recall。


 
 
  1. # 计算每个类别对应的AP,mAP是所有类别AP的平均值
  2.   def voc_eval(detpath,
  3.               annopath,
  4.               imagesetfile,
  5.               classname,
  6.               cachedir,
  7.               ovthresh=0.5,
  8.               use_07_metric=False):
  9.       """rec, prec, ap = voc_eval(detpath,
  10.                                 annopath,
  11.                                 imagesetfile,
  12.                                 classname,
  13.                                 [ovthresh],
  14.                                 [use_07_metric])
  15.     Top level function that does the PASCAL VOC evaluation.
  16.     detpath: Path to detections
  17.         detpath.format(classname) should produce the detection results file.
  18.     annopath: Path to annotations
  19.         annopath.format(imagename) should be the xml annotations file.
  20.     imagesetfile: Text file containing the list of images, one image per line.
  21.     classname: Category name (duh)
  22.     cachedir: Directory for caching the annotations
  23.     [ovthresh]: Overlap threshold (default = 0.5)
  24.     [use_07_metric]: Whether to use VOC07's 11 point AP computation
  25.         (default False)
  26.     """
  27.       # assumes detections are in detpath.format(classname)
  28.       # assumes annotations are in annopath.format(imagename)
  29.       # assumes imagesetfile is a text file with each line an image name
  30.       # cachedir caches the annotations in a pickle file
  31.  ​
  32.       # first load gt
  33.       if not os.path.isdir(cachedir):
  34.          os.mkdir(cachedir)
  35.      imageset = os.path.splitext(os.path.basename(imagesetfile))[ 0]
  36.      cachefile = os.path.join(cachedir, imageset + '_annots.pkl')
  37.       # read list of images
  38.       with open(imagesetfile, 'r') as f:
  39.          lines = f.readlines()
  40.      imagenames = [x.strip() for x in lines]
  41.  ​
  42.       if not os.path.isfile(cachefile):
  43.           # load annots
  44.          recs = {}
  45.           for i, imagename in enumerate(imagenames):
  46.              recs[imagename] = parse_rec(annopath.format(imagename))
  47.               if i % 100 == 0:
  48.                  logger.info(
  49.                       'Reading annotation for {:d}/{:d}'.format(
  50.                          i + 1, len(imagenames)))
  51.           # save
  52.          logger.info( 'Saving cached annotations to {:s}'.format(cachefile))
  53.           with open(cachefile, 'w') as f:
  54.              cPickle.dump(recs, f)
  55.       else:
  56.           # load
  57.           with open(cachefile, 'r') as f:
  58.              recs = cPickle.load(f)
  59.              
  60.       # 提取所有测试图片中当前类别所对应的所有ground_truth
  61.       # extract gt objects for this class
  62.      class_recs = {}
  63.      npos =
  64.       # 遍历所有测试图片
  65.       for imagename in imagenames:
  66.           # 找出所有当前类别对应的object
  67.          R = [obj for obj in recs[imagename] if obj[ 'name'] == classname]
  68.           # 该图片中该类别对应的所有bbox
  69.          bbox = np.array([x[ 'bbox'] for x in R])
  70.          difficult = np.array([x[ 'difficult'] for x in R]).astype(np.bool)
  71.           # 该图片中该类别对应的所有bbox的是否已被匹配的标志位
  72.          det = [ False] * len(R)
  73.           # 累计所有图片中的该类别目标的总数,不算diffcult
  74.          npos = npos + sum(~difficult)
  75.          class_recs[imagename] = { 'bbox': bbox,
  76.                                   'difficult': difficult,
  77.                                   'det': det}
  78.  ​
  79.       # read dets
  80.      detfile = detpath.format(classname)
  81.       with open(detfile, 'r') as f:
  82.          lines = f.readlines()
  83.  ​
  84.      splitlines = [x.strip().split( ' ') for x in lines]
  85.       # 某一行对应的检测目标所属的图像名
  86.      image_ids = [x[ 0] for x in splitlines]
  87.       # 读取该目标对应的置信度
  88.      confidence = np.array([float(x[ 1]) for x in splitlines])
  89.       # 读取该目标对应的bbox
  90.      BB = np.array([[float(z) for z in x[ 2:]] for x in splitlines])
  91.    
  92.       # 将该类别的检测结果按照置信度大小降序排列
  93.      sorted_ind = np.argsort(-confidence)
  94.      BB = BB[sorted_ind, :]
  95.      image_ids = [image_ids[x] for x in sorted_ind]
  96.  
  97.       # 该类别检测结果的总数(所有检测出的bbox的数目)
  98.       # go down dets and mark TPs and FPs
  99.      nd = len(image_ids)
  100.       # 用于标记每个检测结果是tp还是fp
  101.      tp = np.zeros(nd)
  102.      fp = np.zeros(nd)
  103.       # 按置信度遍历每个检测结果
  104.       for d in range(nd):
  105.           # 取出该条检测结果所属图片中的所有ground truth
  106.          R = class_recs[image_ids[d]]
  107.          bb = BB[d, :].astype(float)
  108.          ovmax = -np.inf
  109.          BBGT = R[ 'bbox'].astype(float)
  110.  
  111.           # 计算与该图片中所有ground truth的最大重叠度
  112.           if BBGT.size > 0:
  113.               # compute overlaps
  114.               # intersection
  115.              ixmin = np.maximum(BBGT[:, 0], bb[ 0])
  116.              iymin = np.maximum(BBGT[:, 1], bb[ 1])
  117.              ixmax = np.minimum(BBGT[:, 2], bb[ 2])
  118.              iymax = np.minimum(BBGT[:, 3], bb[ 3])
  119.              iw = np.maximum(ixmax - ixmin + 1., 0.)
  120.              ih = np.maximum(iymax - iymin + 1., 0.)
  121.              inters = iw * ih
  122.  ​
  123.               # union
  124.              uni = ((bb[ 2] - bb[ 0] + 1.) * (bb[ 3] - bb[ 1] + 1.) +
  125.                     (BBGT[:, 2] - BBGT[:, 0] + 1.) *
  126.                     (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)
  127.  ​
  128.              overlaps = inters / uni
  129.              ovmax = np.max(overlaps)
  130.              jmax = np.argmax(overlaps)
  131.  
  132.           # 如果最大的重叠度大于一定的阈值
  133.           if ovmax > ovthresh:
  134.               # 如果最大重叠度对应的ground truth为difficult就忽略
  135.               if not R[ 'difficult'][jmax]:
  136.                   # 如果对应的最大重叠度的ground truth以前没被匹配过则匹配成功,即tp
  137.                   if not R[ 'det'][jmax]:
  138.                      tp[d] = 1.
  139.                      R[ 'det'][jmax] = 1
  140.                   # 若之前有置信度更高的检测结果匹配过这个ground truth,则此次检测结果为fp
  141.                   else:
  142.                      fp[d] = 1.
  143.           # 该图片中没有对应类别的目标ground truth或者与所有ground truth重叠度都小于阈值
  144.           else:
  145.              fp[d] = 1.
  146.  ​
  147.              
  148.       # 按置信度取不同数量检测结果时的累计fp和tp
  149.       # np.cumsum([1, 2, 3, 4]) -> [1, 3, 6, 10]
  150.       # compute precision recall
  151.      fp = np.cumsum(fp)
  152.      tp = np.cumsum(tp)
  153.       # 召回率为占所有真实目标数量的比例,非减的,注意npos本身就排除了difficult,因此npos=tp+fn
  154.      rec = tp / float(npos)
  155.       # 精度为取的所有检测结果中tp的比例
  156.       # avoid divide by zero in case the first detection matches a difficult
  157.       # ground truth
  158.      prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
  159.       # 计算recall-precise曲线下面积(严格来说并不是面积)
  160.      ap = voc_ap(rec, prec, use_07_metric)
  161.  ​
  162.       return rec, prec, ap

这里最终得到一系列的precision和recall值,并且这些值是按照置信度降低排列统计的,可以认为是取不同的置信度阈值(或者rank值)得到的。

3)计算AP:


 
 
  1. def voc_ap(rec, prec, use_07_metric=False):
  2.       """Compute VOC AP given precision and recall. If use_07_metric is true, uses
  3.     the VOC 07 11-point method (default:False).
  4.     """
  5.      
  6.       # VOC2010以前按recall等间隔取11个不同点处的精度值做平均(0., 0.1, 0.2, …, 0.9, 1.0)
  7.       if use_07_metric:
  8.           # 11 point metric
  9.          ap = 0.
  10.           for t in np.arange( 0., 1.1, 0.1):
  11.               if np.sum(rec >= t) == 0:
  12.                  p = 0
  13.               else:
  14.                   # 取recall大于等于阈值的最大precision,保证precision非减
  15.                  p = np.max(prec[rec >= t])
  16.              ap = ap + p / 11.
  17.              
  18.       # VOC2010以后取所有不同的recall对应的点处的精度值做平均
  19.       else:
  20.           # correct AP calculation
  21.           # first append sentinel values at the end
  22.          mrec = np.concatenate(([ 0.], rec, [ 1.]))
  23.          mpre = np.concatenate(([ 0.], prec, [ 0.]))
  24.  
  25.           # 计算包络线,从后往前取最大保证precise非减
  26.           # compute the precision envelope
  27.           for i in range(mpre.size - 1, 0, -1):
  28.              mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
  29.  ​
  30.           # 找出所有检测结果中recall不同的点
  31.           # to calculate area under PR curve, look for points
  32.           # where X axis (recall) changes value
  33.          i = np.where(mrec[ 1:] != mrec[: -1])[ 0]
  34.  ​
  35.           # and sum (\Delta recall) * prec
  36.           # 用recall的间隔对精度作加权平均
  37.          ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
  38.       return ap
计算各个类别的AP值后,取平均值就可以得到最终的mAP值了。但是对于COCO数据集相对比较复杂,不过其提供了计算的API,感兴趣可以看一下cocodataset/cocoapi。
 

6.PASCAL数据集mAP计算方式

PASCAL VOC最终的检测结构是如下这种格式的:

比如comp3_det_test_car.txt: 


 
 
  1. 000004 0.702732 89 112 516 466
  2. 000006 0.870849 373 168 488 229
  3. 000006 0.852346 407 157 500 213
  4. 000006 0.914587 2 161 55 221
  5. 000008 0.532489 175 184 232 201

每一行依次为 :

 <image identifier> <confidence> <left> <top> <right> <bottom>
 

每一行都是一个bounding box,后面四个数定义了检测出的bounding box的左上角点和右下角点的座标。

在计算mAP时,如果按照二分类问题理解,那么每一行都应该对应一个标签,这个标签可以通过ground truth计算出来。

但是如果严格按照 ground truth 的座标来判断这个bounding box是否正确,那么这个标准就太严格了,因为这是属于像素级别的检测,所以PASCAL中规定当一个bounding box与ground truth的 IOU>0.5 时就认为这个框是正样本,标记为1;否则标记为0。这样一来每个bounding box都有个得分,也有一个标签,这时你可以认为前面的文件是这样的,后面多了一个标签项


 
 
  1. 000004 0.702732 89 112 516 466 1
  2. 000006 0.870849 373 168 488 229 0
  3. 000006 0.852346 407 157 500 213 1
  4. 000006 0.914587 2 161 55 221 0
  5. 000008 0.532489 175 184 232 201 1

进而你可以认为是这样的,后面的标签实际上是通过座标计算出来的


 
 
  1. 000004 0.702732 1
  2. 000006 0.870849 0
  3. 000006 0.852346 1
  4. 000006 0.914587 0
  5. 000008 0.532489 1

这样一来就可以根据前面博客中的二分类方法计算AP了。但这是某一个类别的,将所有类别的都计算出来,再做平均即可得到mAP.

7.COCO数据集AP计算方式

COCO数据集里的评估标准比PASCAL 严格许多

COCO检测出的结果是json文件格式,比如下面的:


 
 
  1. [
  2.     {
  3.               "image_id": 139,
  4.               "category_id": 1,
  5.               "bbox": [
  6.                  431.23001,
  7.                  164.85001,
  8.                  42.580002,
  9.                  124.79
  10.             ],
  11.               "score": 0.16355941
  12.       },
  13.      ……
  14.      ……
  15.  ]

我们还是按照前面的形式来便于理解: 


 
 
  1. 000004 0.702732 89 112 516 466
  2. 000006 0.870849 373 168 488 229
  3. 000006 0.852346 407 157 500 213
  4. 000006 0.914587 2 161 55 221
  5. 000008 0.532489 175 184 232 201

前面提到可以使用IOU来计算出一个标签,PASCAL用的是 IOU>0.5即认为是正样本,但是COCO要求IOU阈值在[0.5, 0.95]区间内每隔0.05取一次,这样就可以计算出10个类似于PASCAL的mAP,然后这10个还要再做平均,即为最后的AP,COCO中并不将AP与mAP做区分,许多论文中的写法是 [email protected][0.5:0.95]。而COCO中的 [email protected] 与PASCAL 中的mAP是一样的。

8.参考资料

知乎回答

Object-Detection-Metrics

目标检测mAP计算方式

目标检测评价标准-AP mAP

目标检测模型的评估指标mAP详解(附代码)

How to calculate mAP for detection task for the PASCAL VOC Challenge

点赞