Yolo计算AP,mAP,生成P-R曲线

环境:Python3.7 Opencv Numpy Matplotlib

参考:

  • https://blog.csdn.net/cgt19910923/article/details/80524173
  • https://blog.csdn.net/amusi1994/article/details/81564504
  • https://www.pianshen.com/article/59941009383/

前言:

  • 在darknet版本中,用 darknet detector valid data cfg weight命令可以在result/目录下得到网络检测的输出。包括检测的图像名字、类别、概率、边界框位置(左上角和右下角)。

  • VOC数据集的xml格式标注文件在得到检测输出文件后用darknet/Script目录下的reval_voc_py3.py可以生成P-R曲线。

  • 用Yolo_mark标注后的标注文件后缀为txt。

  • 本文主要为修改reval_voc_py3.py文件后,利用yolo_mark的标注文件和valid命令生成的文件生成P-R曲线

步骤如下:

  1. 修改voc_eval_py3.py中的parse_rec()函数。原函数是加载xml标签的,修改为加载txt标注文件的标签
  2. 修改VOC数据集参数传入。原reval_voc_py3需要传入VOC数据集的路径。
  3. reval_voc_py3 中,需要修改以下内容为自己的文件路径
	label_path		# label文件夹,标注txt和图像应在同一目录下
	valid_file  	# valid命令生成的txt文件,在result/目录下。	
	name_path   	# name文件
	output_dir		# 生成的pkl保存路径
  1. 具体参考下列代码:

reval_voc_py.py:

#!/usr/bin/env python

import os, sys, argparse
import numpy as np
import _pickle as cPickle
from voc_eval_py3 import voc_eval
import matplotlib.pyplot as plt

def do_python_eval(label_path, valid_file, classes, output_dir = 'results'):
    cachedir = os.path.join('./', 'annotations_cache')
    aps = []
    use_07_metric = False
    print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No'))
    
    if not os.path.isdir(output_dir):
        os.mkdir(output_dir)
    for i, cls in enumerate(classes):
        if cls == '__background__':
            continue
        rec, prec, ap = voc_eval(
            label_path,
            valid_file,  cls, cachedir, ovthresh=0.5,
            use_07_metric=use_07_metric)
        aps += [ap]
        print('AP for {} = {:.4f}'.format(cls, ap))
        with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f:
            cPickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)
    print('Mean AP = {:.4f}'.format(np.mean(aps)))
    print('~~~~~~~~')
    print('Results:')
    for ap in aps:
        print('{:.3f}'.format(ap))
    print('{:.3f}'.format(np.mean(aps)))
    print('~~~~~~~~')
    print('')
    print('--------------------------------------------------------------')
    print('Results computed with the **unofficial** Python eval code.')
    print('Results should be very close to the official MATLAB eval code.')
    print('-- Thanks, The Management')
    print('--------------------------------------------------------------')

    fr = open(cls + '_pr.pkl','rb')
    inf = cPickle.load(fr)
    fr.close()

    x=inf['rec']
    y=inf['prec']
    plt.figure()
    plt.xlabel('recall')
    plt.ylabel('precision')
    plt.title('PR cruve')
    plt.plot(x,y)
    plt.show()
    
    print('AP:',inf['ap'])

if __name__ == '__main__':
    label_path = r'E:\Datum\Data\dataset\vaild'  		#label文件夹
    valid_file = r'8_10000_25.txt'						#valid命令生成的txt文件,在result/目录下。	
    name_path = r'E:\Datum\Data\darknet\data\obj.name' 	#name文件
    output_dir = os.path.abspath('./')			 		#pkl保存路径
    with open(name_path, 'r') as f:	     
        lines = f.readlines()
    classes = [t.strip('\n') for t in lines]
    print('Evaluating detections')
    do_python_eval(label_path, valid_file, classes, output_dir)

voc_ecal_py.py:

import xml.etree.ElementTree as ET
import os
import _pickle as cPickle
import numpy as np
import cv2

def parse_rec(label_path, label_name):
    objects = []
    label_file = os.path.join(label_path, label_name + '.txt')
    img_file = os.path.join(label_path, label_name + '.jpg')
    height, width, _ = cv2.imread(img_file).shape
    with open(label_file) as f:
        for line in f.readlines():
            obj_struct = {}
            obj_struct['name'] = 'car'
            obj_struct['difficult'] = int(0)
            center_x, center_y, width_b, height_b =[float(x) for x in line.split()[1:]]
            obj_struct['bbox'] = [int(center_x * width - width * width_b / 2.0),
                                  int(center_y * height - height * height_b / 2.0),
                                  int(center_x * width + width * width_b / 2.0),
                                  int(center_y * height + height * height_b / 2.0)]
            objects.append(obj_struct)
    return objects

def voc_ap(rec, prec, use_07_metric=False):
    if use_07_metric:
        # 11 point metric
        ap = 0.
        for t in np.arange(0., 1.1, 0.1):
            if np.sum(rec >= t) == 0:
                p = 0
            else:
                p = np.max(prec[rec >= t])
            ap = ap + p / 11.
    else:
        # correct AP calculation
        # first append sentinel values at the end
        mrec = np.concatenate(([0.], rec, [1.]))
        mpre = np.concatenate(([0.], prec, [0.]))

        # compute the precision envelope
        for i in range(mpre.size - 1, 0, -1):
            mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])

        # to calculate area under PR curve, look for points
        # where X axis (recall) changes value
        i = np.where(mrec[1:] != mrec[:-1])[0]

        # and sum (\Delta recall) * prec
        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
    return ap

def voc_eval(label_path,
             detpath,
             classname,
             cachedir,
             ovthresh=0.5,
             use_07_metric=False):
    # first load gt
    if not os.path.isdir(cachedir):
        os.mkdir(cachedir)
    cachefile = os.path.join(cachedir, 'annots.pkl')

    label_file = []
    for f in os.listdir(label_path):
        file, tmp = f.split('.')
        if  tmp == 'txt':
            label_file.append(file)
    
    if not os.path.isfile(cachefile):
        # load annots
        recs = {}
        for label_name in label_file:
            recs[label_name] = parse_rec(label_path, label_name)
        with open(cachefile, 'wb') as f:
            cPickle.dump(recs, f)
    else:
        # load
        print('!!! cachefile = ',cachefile)
        with open(cachefile, 'rb') as f:
            recs = cPickle.load(f)

    # extract gt objects for this class
    class_recs = {}
    npos = 0
    for label_name in label_file:
    # for imagename in imagenames:
        R = [obj for obj in recs[label_name] if obj['name'] == classname]
        bbox = np.array([x['bbox'] for x in R])
        difficult = np.array([x['difficult'] for x in R]).astype(np.bool)
        det = [False] * len(R)
        npos = npos + sum(~difficult)
        class_recs[label_name] = {'bbox': bbox,
                                 'difficult': difficult,
                                 'det': det}

    # read dets
    detfile = detpath
    # detfile = detpath.format(classname)
    with open(detfile, 'r') as f:
        lines = f.readlines()

    splitlines = [x.strip().split(' ') for x in lines]
    image_ids = [x[0] for x in splitlines]
    confidence = np.array([float(x[1]) for x in splitlines])
    BB = np.array([[float(z) for z in x[2:]] for x in splitlines])

    # sort by confidence
    sorted_ind = np.argsort(-confidence)
    sorted_scores = np.sort(-confidence)
    BB = BB[sorted_ind, :]
    image_ids = [image_ids[x] for x in sorted_ind]
    # go down dets and mark TPs and FPs
    nd = len(image_ids)
    # print(image_ids)
    # print(nd)
    tp = np.zeros(nd)
    fp = np.zeros(nd)
    for d in range(nd):
        R = class_recs[image_ids[d]]
        bb = BB[d, :].astype(float)
        ovmax = -np.inf
        BBGT = R['bbox'].astype(float)

        if BBGT.size > 0:
            # compute overlaps
            # intersection
            ixmin = np.maximum(BBGT[:, 0], bb[0])
            iymin = np.maximum(BBGT[:, 1], bb[1])
            ixmax = np.minimum(BBGT[:, 2], bb[2])
            iymax = np.minimum(BBGT[:, 3], bb[3])
            iw = np.maximum(ixmax - ixmin + 1., 0.)
            ih = np.maximum(iymax - iymin + 1., 0.)
            inters = iw * ih

            # union
            uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +
                   (BBGT[:, 2] - BBGT[:, 0] + 1.) *
                   (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)

            overlaps = inters / uni
            ovmax = np.max(overlaps)
            jmax = np.argmax(overlaps)

        if ovmax > ovthresh:
            if not R['difficult'][jmax]:
                if not R['det'][jmax]:
                    tp[d] = 1.
                    R['det'][jmax] = 1
                else:
                    fp[d] = 1.
        else:
            fp[d] = 1.

    # compute precision recall
    fp = np.cumsum(fp)
    tp = np.cumsum(tp)
    rec = tp / float(npos)
    # avoid divide by zero in case the first detection matches a difficult
    # ground truth
    prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
    ap = voc_ap(rec, prec, use_07_metric)

    return rec, prec, ap

你可能感兴趣的:(Yolo计算AP,mAP,生成P-R曲线)