coco_utils.py 6.0 KB
Newer Older
K
Kaipeng Deng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright (c) 2020 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

import os
20 21 22
import sys
import numpy as np
import itertools
K
Kaipeng Deng 已提交
23

G
Guanghua Yu 已提交
24
from ppdet.py_op.post_process import get_det_res, get_seg_res, get_solov2_segm_res
25
from ppdet.metrics.map_utils import draw_pr_curve
K
Kaipeng Deng 已提交
26 27 28 29 30

from ppdet.utils.logger import setup_logger
logger = setup_logger(__name__)


W
wangxinxin08 已提交
31
def get_infer_results(outs, catid, bias=0):
K
Kaipeng Deng 已提交
32 33 34 35 36
    """
    Get result at the stage of inference.
    The output format is dictionary containing bbox or mask result.

    For example, bbox result is a list and each element contains
G
Guanghua Yu 已提交
37
    image_id, category_id, bbox and score.
K
Kaipeng Deng 已提交
38 39 40 41 42 43 44 45 46 47
    """
    if outs is None or len(outs) == 0:
        raise ValueError(
            'The number of valid detection result if zero. Please use reasonable model and check input data.'
        )

    im_id = outs['im_id']

    infer_res = {}
    if 'bbox' in outs:
W
wangxinxin08 已提交
48
        infer_res['bbox'] = get_det_res(
G
Guanghua Yu 已提交
49
            outs['bbox'], outs['bbox_num'], im_id, catid, bias=bias)
K
Kaipeng Deng 已提交
50 51 52

    if 'mask' in outs:
        # mask post process
G
Guanghua Yu 已提交
53 54
        infer_res['mask'] = get_seg_res(outs['mask'], outs['bbox'],
                                        outs['bbox_num'], im_id, catid)
K
Kaipeng Deng 已提交
55

G
Guanghua Yu 已提交
56 57 58
    if 'segm' in outs:
        infer_res['segm'] = get_solov2_segm_res(outs, im_id, catid)

K
Kaipeng Deng 已提交
59 60 61 62 63 64 65
    return infer_res


def cocoapi_eval(jsonfile,
                 style,
                 coco_gt=None,
                 anno_file=None,
66 67
                 max_dets=(100, 300, 1000),
                 classwise=False):
K
Kaipeng Deng 已提交
68 69
    """
    Args:
F
Feng Ni 已提交
70 71 72
        jsonfile (str): Evaluation json file, eg: bbox.json, mask.json.
        style (str): COCOeval style, can be `bbox` , `segm` and `proposal`.
        coco_gt (str): Whether to load COCOAPI through anno_file,
K
Kaipeng Deng 已提交
73
                 eg: coco_gt = COCO(anno_file)
F
Feng Ni 已提交
74 75 76
        anno_file (str): COCO annotations file.
        max_dets (tuple): COCO evaluation maxDets.
        classwise (bool): Whether per-category AP and draw P-R Curve or not.
K
Kaipeng Deng 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    """
    assert coco_gt != None or anno_file != None
    from pycocotools.coco import COCO
    from pycocotools.cocoeval import COCOeval

    if coco_gt == None:
        coco_gt = COCO(anno_file)
    logger.info("Start evaluate...")
    coco_dt = coco_gt.loadRes(jsonfile)
    if style == 'proposal':
        coco_eval = COCOeval(coco_gt, coco_dt, 'bbox')
        coco_eval.params.useCats = 0
        coco_eval.params.maxDets = list(max_dets)
    else:
        coco_eval = COCOeval(coco_gt, coco_dt, style)
    coco_eval.evaluate()
    coco_eval.accumulate()
    coco_eval.summarize()
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    if classwise:
        # Compute per-category AP and PR curve
        try:
            from terminaltables import AsciiTable
        except Exception as e:
            logger.error(
                'terminaltables not found, plaese install terminaltables. '
                'for example: `pip install terminaltables`.')
            raise e
        precisions = coco_eval.eval['precision']
        cat_ids = coco_gt.getCatIds()
        # precision: (iou, recall, cls, area range, max dets)
        assert len(cat_ids) == precisions.shape[2]
        results_per_category = []
        for idx, catId in enumerate(cat_ids):
            # area range index 0: all area ranges
            # max dets index -1: typically 100 per image
            nm = coco_gt.loadCats(catId)[0]
            precision = precisions[:, :, idx, 0, -1]
            precision = precision[precision > -1]
            if precision.size:
                ap = np.mean(precision)
            else:
                ap = float('nan')
            results_per_category.append(
                (str(nm["name"]), '{:0.3f}'.format(float(ap))))
            pr_array = precisions[0, :, idx, 0, 2]
            recall_array = np.arange(0.0, 1.01, 0.01)
            draw_pr_curve(
                pr_array,
                recall_array,
                out_dir=style + '_pr_curve',
                file_name='{}_precision_recall_curve.jpg'.format(nm["name"]))

        num_columns = min(6, len(results_per_category) * 2)
        results_flatten = list(itertools.chain(*results_per_category))
        headers = ['category', 'AP'] * (num_columns // 2)
        results_2d = itertools.zip_longest(
133
            *[results_flatten[i::num_columns] for i in range(num_columns)])
134 135 136 137 138 139 140 141
        table_data = [headers]
        table_data += [result for result in results_2d]
        table = AsciiTable(table_data)
        logger.info('Per-category of {} AP: \n{}'.format(style, table.table))
        logger.info("per-category PR curve has output to {} folder.".format(
            style + '_pr_curve'))
    # flush coco evaluation result
    sys.stdout.flush()
K
Kaipeng Deng 已提交
142
    return coco_eval.stats
S
shangliang Xu 已提交
143 144


F
Feng Ni 已提交
145
def json_eval_results(metric, json_directory, dataset):
S
shangliang Xu 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    """
    cocoapi eval with already exists proposal.json, bbox.json or mask.json
    """
    assert metric == 'COCO'
    anno_file = dataset.get_anno()
    json_file_list = ['proposal.json', 'bbox.json', 'mask.json']
    if json_directory:
        assert os.path.exists(
            json_directory), "The json directory:{} does not exist".format(
                json_directory)
        for k, v in enumerate(json_file_list):
            json_file_list[k] = os.path.join(str(json_directory), v)

    coco_eval_style = ['proposal', 'bbox', 'segm']
    for i, v_json in enumerate(json_file_list):
        if os.path.exists(v_json):
            cocoapi_eval(v_json, coco_eval_style[i], anno_file=anno_file)
        else:
            logger.info("{} not exists!".format(v_json))