天天看點

Faster Rcnn 代碼解讀之 voc_eval.py

# --------------------------------------------------------
# Fast/er R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Bharath Hariharan
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import xml.etree.ElementTree as ET
import os
import pickle
import numpy as np
'''
評估函數
'''

# 讀取xml檔案
def parse_rec(filename):
    """ Parse a PASCAL VOC xml file """
    tree = ET.parse(filename)
    objects = []
    for obj in tree.findall('object'):
        obj_struct = {}
        obj_struct['name'] = obj.find('name').text
        obj_struct['pose'] = obj.find('pose').text
        obj_struct['truncated'] = int(obj.find('truncated').text)
        obj_struct['difficult'] = int(obj.find('difficult').text)
        bbox = obj.find('bndbox')
        obj_struct['bbox'] = [int(bbox.find('xmin').text),
                              int(bbox.find('ymin').text),
                              int(bbox.find('xmax').text),
                              int(bbox.find('ymax').text)]
        objects.append(obj_struct)

    return objects


# 計算AP的函數
def voc_ap(rec, prec, use_07_metric=False):
    """ ap = voc_ap(rec, prec, [use_07_metric])
    Compute VOC AP given precision and recall.
    If use_07_metric is true, uses the
    VOC 07 11 point method (default:False).
    計算AP值,若use_07_metric=true,則用11個點采樣的方法,将rec從0-1分成11個點,這些點prec值求平均近似表示AP
    若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(detpath,
             annopath,
             imagesetfile,
             classname,
             cachedir,
             ovthresh=0.5,
             use_07_metric=False,
             use_diff=False):
    """rec, prec, ap = voc_eval(detpath,
                                annopath,
                                imagesetfile,
                                classname,
                                [ovthresh],
                                [use_07_metric])

    Top level function that does the PASCAL VOC evaluation.

    detpath: Path to detections
        detpath.format(classname) should produce the detection results file.
    annopath: Path to annotations
        annopath.format(imagename) should be the xml annotations file.
    #imagesetfile,路徑VOCdevkit/VOC20xx/ImageSets/Main/test.txt這裡假設測試圖像1000張,那麼該txt檔案1000行。
    imagesetfile: Text file containing the list of images, one image per line.
    classname: Category name (duh)
    cachedir: Directory for caching the annotations
    [ovthresh]: Overlap threshold (default = 0.5)
    [use_07_metric]: Whether to use VOC07's 11 point AP computation
        (default False)
    """
    # assumes detections are in detpath.format(classname)
    # assumes annotations are in annopath.format(imagename)
    # assumes imagesetfile is a text file with each line an image name
    # cachedir caches the annotations in a pickle file

    # first load gt
    # 讀取真實的标簽
    # if cachedir不存在就建立一個
    if not os.path.isdir(cachedir):
        os.mkdir(cachedir)
    cachefile = os.path.join(cachedir, '%s_annots.pkl' % imagesetfile)
    # read list of images
    with open(imagesetfile, 'r') as f:
        lines = f.readlines()  # 讀取所有圖檔名
    imagenames = [x.strip() for x in lines]  # x.strip()代表去除開頭和結尾的'\n'或者'\t'

    # 如果緩存路徑對應的檔案沒有,則讀取annotations
    if not os.path.isfile(cachefile):
        # load annotations
        # 這是一個字典
        recs = {}
        for i, imagename in enumerate(imagenames):
            # parse_rec用于讀取xml檔案
            recs[imagename] = parse_rec(annopath.format(imagename))
            if i % 100 == 0:
                print('Reading annotation for {:d}/{:d}'.format(
                    i + 1, len(imagenames)))
        # save
        print('Saving cached annotations to {:s}'.format(cachefile))
        with open(cachefile, 'wb') as f:
            pickle.dump(recs, f)  # dump是序列化儲存,load是序列化解析
    else:  # 如果已經有了cachefile緩存檔案,直接讀取
        # load
        with open(cachefile, 'rb') as f:
            try:
                recs = pickle.load(f)
            except:
                recs = pickle.load(f, encoding='bytes')

    # extract gt objects for this class
    #
    class_recs = {}  # 目前類别的标注
    npos = 0
    for imagename in imagenames:
        # recs[imagename]是儲存了圖檔的object裡面的所有屬性,是個字典
        # 值保留指定類别的項
        R = [obj for obj in recs[imagename] if obj['name'] == classname]
        # 獲得所有的bbox,裡面儲存了xmin,ymin,xmax,ymax
        bbox = np.array([x['bbox'] for x in R])
        if use_diff:  # 如果使用difficult(難檢測的),所有的值都是false
            difficult = np.array([False for x in R]).astype(np.bool)
        else:  # 否則裡面的内容有1有0
            difficult = np.array([x['difficult'] for x in R]).astype(np.bool)
        # len(R)就是目前類别的個數
        # 開辟一個全為False長度是len(R)的數組
        det = [False] * len(R)
        # 我測試~difficult的意思是取相反數之後再減1,這是什麼意思。。。
        npos = npos + sum(~difficult)
        class_recs[imagename] = {'bbox': bbox,
                                 'difficult': difficult,
                                 'det': det}

    # read dets
    # dets是檢測結果的路徑,讀取出來就是圖檔名字、得分、bbox四個值。
    detfile = detpath.format(classname)
    # 讀取txt裡面的所有内容
    with open(detfile, 'r') as f:
        lines = f.readlines()
    # 這裡的操作x.strip().split(' ')首先去掉了每行開頭和結尾的'\n'或'\t'然後去除每行的' '
    # 之前再運作代碼時,報錯時一直以為空格會影響檔案的讀入,還專門寫了函數去去除所有額外的空格。。多餘了
    splitlines = [x.strip().split(' ') for x in lines]
    # 以圖檔的名稱作為下标
    image_ids = [x[0] for x in splitlines]  # x[0]為名稱
    confidence = np.array([float(x[1]) for x in splitlines])  # x[1]為得分
    BB = np.array([[float(z) for z in x[2:]] for x in splitlines])  # x[2]為bbox的4個值
    # 統計檢測的目标數量
    nd = len(image_ids)
    # tp:正類預測為正類->A預測成A
    # fp:正類預測為負類->A預測成B
    tp = np.zeros(nd)
    fp = np.zeros(nd)

    if BB.shape[0] > 0:  # 行數>0
        # sort by confidence
        # 按照分數從大到小排序,傳回下标
        sorted_ind = np.argsort(-confidence)
        # 按照分數從大到小排序,傳回分數
        # 下面也沒有用到該變量,其實sorted_ind得到之後,直接根據confidence[sorted_ind[i]]就可以得到sorted_scores
        sorted_scores = np.sort(-confidence)
        # 對BB也重排一下
        BB = BB[sorted_ind, :]
        # image_ids也重排
        image_ids = [image_ids[x] for x in sorted_ind]
        # 上面這些操作就是為了下标對應起來,後面好操作
        # go down dets and mark TPs and FPs
        for d in range(nd):
            '''
            class_recs[imagename] = {'bbox': bbox,
                                 'difficult': difficult,
                                 'det': det}
            '''
            # 由image_ids[d]擷取名稱。然後得到R
            R = class_recs[image_ids[d]]
            # dets是檢測結果的路徑,BB通過dets擷取每一行的資料,然後得到對應的BB值(也就是4個屬性)
            bb = BB[d, :].astype(float)
            # 設定一個負無窮
            ovmax = -np.inf
            # BBGT是真實的坐标
            BBGT = R['bbox'].astype(float)

            if BBGT.size > 0:  # 如果存在GT計算交并比,如果不存在,首先就是檢測錯誤
                # 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)
                # 計算IOU,注意這個overlaps不一定是一個數值,可能是一個清單的,所有後面才有np.max和np.argmax
                overlaps = inters / uni
                # 保留最大的IOU
                ovmax = np.max(overlaps)
                # 保留最大IOU的下标
                jmax = np.argmax(overlaps)

            if ovmax > ovthresh:  # 這個阙值預設0.5
                if not R['difficult'][jmax]:  # 這個後面是不是少個else,如果是難測樣本呢??
                    # R = class_recs[image_ids[d]]
                    if not R['det'][jmax]:  # R['det']初始值全為False,意思應該是如果該位置第一次使用,才可以。那也會出現tp[d]=fp[d]=1的情況啊
                        # 下面都是标記
                        tp[d] = 1.
                        R['det'][jmax] = 1
                    else:
                        fp[d] = 1.
            else:
                fp[d] = 1.

    # compute precision recall
    # 我測試cumsum是字首和的意思???? 不懂
    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
           

繼續閱讀