voc_eval.py 6.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
import sys
import numpy as np

24
from ..data.source.voc import pascalvoc_label
25
from .map_utils import DetectionMAP
26 27 28 29 30
from .coco_eval import bbox2out

import logging
logger = logging.getLogger(__name__)

W
wangguanzhong 已提交
31
__all__ = ['bbox_eval', 'bbox2out', 'get_category_info']
32 33


34 35
def bbox_eval(results,
              class_num,
36 37 38 39 40 41 42 43 44 45
              overlap_thresh=0.5,
              map_type='11point',
              is_bbox_normalized=False,
              evaluate_difficult=False):
    """
    Bounding box evaluation for VOC dataset

    Args:
        results (list): prediction bounding box results.
        class_num (int): evaluation class number.
46
        overlap_thresh (float): the postive threshold of
47 48 49 50 51
                        bbox overlap
        map_type (string): method for mAP calcualtion,
                        can only be '11point' or 'integral'
        is_bbox_normalized (bool): whether bbox is normalized
                        to range [0, 1].
52
        evaluate_difficult (bool): whether to evaluate
53 54 55 56 57
                        difficult gt bbox.
    """
    assert 'bbox' in results[0]
    logger.info("Start evaluate...")

W
wangguanzhong 已提交
58 59 60 61 62 63
    detection_map = DetectionMAP(
        class_num=class_num,
        overlap_thresh=overlap_thresh,
        map_type=map_type,
        is_bbox_normalized=is_bbox_normalized,
        evaluate_difficult=evaluate_difficult)
64 65 66 67 68 69 70

    for t in results:
        bboxes = t['bbox'][0]
        bbox_lengths = t['bbox'][1][0]

        if bboxes.shape == (1, 1) or bboxes is None:
            continue
71 72
        gt_boxes = t['gt_bbox'][0]
        gt_labels = t['gt_class'][0]
73 74
        difficults = t['is_difficult'][0] if not evaluate_difficult \
                            else None
75

76 77
        if len(t['gt_bbox'][1]) == 0:
            # gt_bbox, gt_class, difficult read as zero padded Tensor
78 79 80 81
            bbox_idx = 0
            for i in range(len(gt_boxes)):
                gt_box = gt_boxes[i]
                gt_label = gt_labels[i]
82 83
                difficult = None if difficults is None \
                                else difficults[i]
84
                bbox_num = bbox_lengths[i]
W
wangguanzhong 已提交
85
                bbox = bboxes[bbox_idx:bbox_idx + bbox_num]
86
                gt_box, gt_label, difficult = prune_zero_padding(
W
wangguanzhong 已提交
87
                    gt_box, gt_label, difficult)
88 89 90 91
                detection_map.update(bbox, gt_box, gt_label, difficult)
                bbox_idx += bbox_num
        else:
            # gt_box, gt_label, difficult read as LoDTensor
92
            gt_box_lengths = t['gt_bbox'][1][0]
93 94 95 96 97
            bbox_idx = 0
            gt_box_idx = 0
            for i in range(len(bbox_lengths)):
                bbox_num = bbox_lengths[i]
                gt_box_num = gt_box_lengths[i]
W
wangguanzhong 已提交
98 99 100
                bbox = bboxes[bbox_idx:bbox_idx + bbox_num]
                gt_box = gt_boxes[gt_box_idx:gt_box_idx + gt_box_num]
                gt_label = gt_labels[gt_box_idx:gt_box_idx + gt_box_num]
101 102 103 104 105
                difficult = None if difficults is None else \
                            difficults[gt_box_idx: gt_box_idx + gt_box_num]
                detection_map.update(bbox, gt_box, gt_label, difficult)
                bbox_idx += bbox_num
                gt_box_idx += gt_box_num
106 107 108

    logger.info("Accumulating evaluatation results...")
    detection_map.accumulate()
109
    map_stat = 100. * detection_map.get_map()
K
Kaipeng Deng 已提交
110 111
    logger.info("mAP({:.2f}, {}) = {:.2f}%".format(overlap_thresh, map_type,
                                                   map_stat))
112
    return map_stat
113 114


115 116 117 118 119 120 121
def prune_zero_padding(gt_box, gt_label, difficult=None):
    valid_cnt = 0
    for i in range(len(gt_box)):
        if gt_box[i, 0] == 0 and gt_box[i, 1] == 0 and \
                gt_box[i, 2] == 0 and gt_box[i, 3] == 0:
            break
        valid_cnt += 1
W
wangguanzhong 已提交
122 123
    return (gt_box[:valid_cnt], gt_label[:valid_cnt], difficult[:valid_cnt]
            if difficult is not None else None)
124 125


126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
def get_category_info(anno_file=None,
                      with_background=True,
                      use_default_label=False):
    if use_default_label or anno_file is None \
            or not os.path.exists(anno_file):
        logger.info("Not found annotation file {}, load "
                    "voc2012 categories.".format(anno_file))
        return vocall_category_info(with_background)
    else:
        logger.info("Load categories from {}".format(anno_file))
        return get_category_info_from_anno(anno_file, with_background)


def get_category_info_from_anno(anno_file, with_background=True):
    """
    Get class id to category id map and category id
    to category name map from annotation file.

    Args:
        anno_file (str): annotation file path
        with_background (bool, default True):
            whether load background as class 0.
    """
    cats = []
    with open(anno_file) as f:
        for line in f.readlines():
            cats.append(line.strip())

    if cats[0] != 'background' and with_background:
        cats.insert(0, 'background')
    if cats[0] == 'background' and not with_background:
        cats = cats[1:]

    clsid2catid = {i: i for i in range(len(cats))}
    catid2name = {i: name for i, name in enumerate(cats)}

    return clsid2catid, catid2name


def vocall_category_info(with_background=True):
    """
    Get class id to category id map and category id
    to category name map of mixup voc dataset

    Args:
        with_background (bool, default True):
            whether load background as class 0.
    """
    label_map = pascalvoc_label(with_background)
    label_map = sorted(label_map.items(), key=lambda x: x[1])
    cats = [l[0] for l in label_map]

    if with_background:
        cats.insert(0, 'background')

    clsid2catid = {i: i for i in range(len(cats))}
    catid2name = {i: name for i, name in enumerate(cats)}

    return clsid2catid, catid2name