metrics.py 16.1 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 20 21 22 23
# 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
import sys
import json
import paddle
import numpy as np
M
Mark Ma 已提交
24
import typing
W
Wenyu 已提交
25
from pathlib import Path
K
Kaipeng Deng 已提交
26 27 28

from .map_utils import prune_zero_padding, DetectionMAP
from .coco_utils import get_infer_results, cocoapi_eval
29
from .widerface_utils import face_eval_run
K
Kaipeng Deng 已提交
30
from ppdet.data.source.category import get_categories
K
Kaipeng Deng 已提交
31 32 33 34

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

35
__all__ = [
W
Wenyu 已提交
36 37
    'Metric', 'COCOMetric', 'VOCMetric', 'WiderFaceMetric', 'get_infer_results',
    'RBoxMetric', 'SNIPERCOCOMetric'
38
]
K
Kaipeng Deng 已提交
39

40 41 42 43 44 45 46 47
COCO_SIGMAS = np.array([
    .26, .25, .25, .35, .35, .79, .79, .72, .72, .62, .62, 1.07, 1.07, .87, .87,
    .89, .89
]) / 10.0
CROWD_SIGMAS = np.array(
    [.79, .79, .72, .72, .62, .62, 1.07, 1.07, .87, .87, .89, .89, .79,
     .79]) / 10.0

K
Kaipeng Deng 已提交
48 49 50 51 52

class Metric(paddle.metric.Metric):
    def name(self):
        return self.__class__.__name__

53 54 55 56 57 58
    def reset(self):
        pass

    def accumulate(self):
        pass

K
Kaipeng Deng 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71
    # paddle.metric.Metric defined :metch:`update`, :meth:`accumulate`
    # :metch:`reset`, in ppdet, we also need following 2 methods:

    # abstract method for logging metric results
    def log(self):
        pass

    # abstract method for getting metric results
    def get_results(self):
        pass


class COCOMetric(Metric):
W
wangxinxin08 已提交
72
    def __init__(self, anno_file, **kwargs):
K
Kaipeng Deng 已提交
73
        self.anno_file = anno_file
K
Kaipeng Deng 已提交
74 75 76
        self.clsid2catid = kwargs.get('clsid2catid', None)
        if self.clsid2catid is None:
            self.clsid2catid, _ = get_categories('COCO', anno_file)
77
        self.classwise = kwargs.get('classwise', False)
S
shangliang Xu 已提交
78
        self.output_eval = kwargs.get('output_eval', None)
W
wangxinxin08 已提交
79 80
        # TODO: bias should be unified
        self.bias = kwargs.get('bias', 0)
81
        self.save_prediction_only = kwargs.get('save_prediction_only', False)
82
        self.iou_type = kwargs.get('IouType', 'bbox')
W
Wenyu 已提交
83 84 85 86 87 88 89 90

        if not self.save_prediction_only:
            assert os.path.isfile(anno_file), \
                    "anno_file {} not a file".format(anno_file)

        if self.output_eval is not None:
            Path(self.output_eval).mkdir(exist_ok=True)

K
Kaipeng Deng 已提交
91 92 93 94
        self.reset()

    def reset(self):
        # only bbox and mask evaluation support currently
95
        self.results = {'bbox': [], 'mask': [], 'segm': [], 'keypoint': []}
K
Kaipeng Deng 已提交
96 97 98 99 100 101 102 103
        self.eval_results = {}

    def update(self, inputs, outputs):
        outs = {}
        # outputs Tensor -> numpy.ndarray
        for k, v in outputs.items():
            outs[k] = v.numpy() if isinstance(v, paddle.Tensor) else v

M
Mark Ma 已提交
104 105 106 107 108
        # multi-scale inputs: all inputs have same im_id
        if isinstance(inputs, typing.Sequence):
            im_id = inputs[0]['im_id']
        else:
            im_id = inputs['im_id']
109 110
        outs['im_id'] = im_id.numpy() if isinstance(im_id,
                                                    paddle.Tensor) else im_id
K
Kaipeng Deng 已提交
111

W
wangxinxin08 已提交
112 113
        infer_results = get_infer_results(
            outs, self.clsid2catid, bias=self.bias)
K
Kaipeng Deng 已提交
114 115 116 117
        self.results['bbox'] += infer_results[
            'bbox'] if 'bbox' in infer_results else []
        self.results['mask'] += infer_results[
            'mask'] if 'mask' in infer_results else []
G
Guanghua Yu 已提交
118 119
        self.results['segm'] += infer_results[
            'segm'] if 'segm' in infer_results else []
120 121
        self.results['keypoint'] += infer_results[
            'keypoint'] if 'keypoint' in infer_results else []
K
Kaipeng Deng 已提交
122 123 124

    def accumulate(self):
        if len(self.results['bbox']) > 0:
S
shangliang Xu 已提交
125 126 127 128
            output = "bbox.json"
            if self.output_eval:
                output = os.path.join(self.output_eval, output)
            with open(output, 'w') as f:
K
Kaipeng Deng 已提交
129 130 131
                json.dump(self.results['bbox'], f)
                logger.info('The bbox result is saved to bbox.json.')

132 133 134 135 136 137 138 139 140 141 142
            if self.save_prediction_only:
                logger.info('The bbox result is saved to {} and do not '
                            'evaluate the mAP.'.format(output))
            else:
                bbox_stats = cocoapi_eval(
                    output,
                    'bbox',
                    anno_file=self.anno_file,
                    classwise=self.classwise)
                self.eval_results['bbox'] = bbox_stats
                sys.stdout.flush()
K
Kaipeng Deng 已提交
143 144

        if len(self.results['mask']) > 0:
S
shangliang Xu 已提交
145 146 147 148
            output = "mask.json"
            if self.output_eval:
                output = os.path.join(self.output_eval, output)
            with open(output, 'w') as f:
K
Kaipeng Deng 已提交
149 150 151
                json.dump(self.results['mask'], f)
                logger.info('The mask result is saved to mask.json.')

152 153 154 155 156 157 158 159 160 161 162
            if self.save_prediction_only:
                logger.info('The mask result is saved to {} and do not '
                            'evaluate the mAP.'.format(output))
            else:
                seg_stats = cocoapi_eval(
                    output,
                    'segm',
                    anno_file=self.anno_file,
                    classwise=self.classwise)
                self.eval_results['mask'] = seg_stats
                sys.stdout.flush()
K
Kaipeng Deng 已提交
163

G
Guanghua Yu 已提交
164
        if len(self.results['segm']) > 0:
S
shangliang Xu 已提交
165 166 167 168
            output = "segm.json"
            if self.output_eval:
                output = os.path.join(self.output_eval, output)
            with open(output, 'w') as f:
G
Guanghua Yu 已提交
169 170 171
                json.dump(self.results['segm'], f)
                logger.info('The segm result is saved to segm.json.')

172 173 174 175 176 177 178 179 180 181 182
            if self.save_prediction_only:
                logger.info('The segm result is saved to {} and do not '
                            'evaluate the mAP.'.format(output))
            else:
                seg_stats = cocoapi_eval(
                    output,
                    'segm',
                    anno_file=self.anno_file,
                    classwise=self.classwise)
                self.eval_results['mask'] = seg_stats
                sys.stdout.flush()
G
Guanghua Yu 已提交
183

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
        if len(self.results['keypoint']) > 0:
            output = "keypoint.json"
            if self.output_eval:
                output = os.path.join(self.output_eval, output)
            with open(output, 'w') as f:
                json.dump(self.results['keypoint'], f)
                logger.info('The keypoint result is saved to keypoint.json.')

            if self.save_prediction_only:
                logger.info('The keypoint result is saved to {} and do not '
                            'evaluate the mAP.'.format(output))
            else:
                style = 'keypoints'
                use_area = True
                sigmas = COCO_SIGMAS
                if self.iou_type == 'keypoints_crowd':
                    style = 'keypoints_crowd'
                    use_area = False
                    sigmas = CROWD_SIGMAS
                keypoint_stats = cocoapi_eval(
                    output,
                    style,
                    anno_file=self.anno_file,
                    classwise=self.classwise,
                    sigmas=sigmas,
                    use_area=use_area)
                self.eval_results['keypoint'] = keypoint_stats
                sys.stdout.flush()

K
Kaipeng Deng 已提交
213 214 215 216 217 218 219 220 221
    def log(self):
        pass

    def get_results(self):
        return self.eval_results


class VOCMetric(Metric):
    def __init__(self,
222
                 label_list,
K
Kaipeng Deng 已提交
223 224 225 226
                 class_num=20,
                 overlap_thresh=0.5,
                 map_type='11point',
                 is_bbox_normalized=False,
227 228 229 230 231
                 evaluate_difficult=False,
                 classwise=False):
        assert os.path.isfile(label_list), \
                "label_list {} not a file".format(label_list)
        self.clsid2catid, self.catid2name = get_categories('VOC', label_list)
K
Kaipeng Deng 已提交
232 233 234 235 236 237 238 239 240

        self.overlap_thresh = overlap_thresh
        self.map_type = map_type
        self.evaluate_difficult = evaluate_difficult
        self.detection_map = DetectionMAP(
            class_num=class_num,
            overlap_thresh=overlap_thresh,
            map_type=map_type,
            is_bbox_normalized=is_bbox_normalized,
241 242 243
            evaluate_difficult=evaluate_difficult,
            catid2name=self.catid2name,
            classwise=classwise)
K
Kaipeng Deng 已提交
244 245 246 247 248 249 250

        self.reset()

    def reset(self):
        self.detection_map.reset()

    def update(self, inputs, outputs):
W
wangguanzhong 已提交
251 252 253 254
        bbox_np = outputs['bbox'].numpy()
        bboxes = bbox_np[:, 2:]
        scores = bbox_np[:, 1]
        labels = bbox_np[:, 0]
K
Kaipeng Deng 已提交
255 256 257 258
        bbox_lengths = outputs['bbox_num'].numpy()

        if bboxes.shape == (1, 1) or bboxes is None:
            return
W
wangguanzhong 已提交
259 260 261
        gt_boxes = inputs['gt_bbox']
        gt_labels = inputs['gt_class']
        difficults = inputs['difficult'] if not self.evaluate_difficult \
K
Kaipeng Deng 已提交
262 263 264 265 266 267 268
                            else None

        scale_factor = inputs['scale_factor'].numpy(
        ) if 'scale_factor' in inputs else np.ones(
            (gt_boxes.shape[0], 2)).astype('float32')

        bbox_idx = 0
W
wangguanzhong 已提交
269 270
        for i in range(len(gt_boxes)):
            gt_box = gt_boxes[i].numpy()
K
Kaipeng Deng 已提交
271 272
            h, w = scale_factor[i]
            gt_box = gt_box / np.array([w, h, w, h])
W
wangguanzhong 已提交
273
            gt_label = gt_labels[i].numpy()
K
Kaipeng Deng 已提交
274
            difficult = None if difficults is None \
W
wangguanzhong 已提交
275
                            else difficults[i].numpy()
K
Kaipeng Deng 已提交
276 277
            bbox_num = bbox_lengths[i]
            bbox = bboxes[bbox_idx:bbox_idx + bbox_num]
278 279
            score = scores[bbox_idx:bbox_idx + bbox_num]
            label = labels[bbox_idx:bbox_idx + bbox_num]
K
Kaipeng Deng 已提交
280 281
            gt_box, gt_label, difficult = prune_zero_padding(gt_box, gt_label,
                                                             difficult)
282 283
            self.detection_map.update(bbox, score, label, gt_box, gt_label,
                                      difficult)
K
Kaipeng Deng 已提交
284 285 286 287 288 289 290 291 292 293 294 295
            bbox_idx += bbox_num

    def accumulate(self):
        logger.info("Accumulating evaluatation results...")
        self.detection_map.accumulate()

    def log(self):
        map_stat = 100. * self.detection_map.get_map()
        logger.info("mAP({:.2f}, {}) = {:.2f}%".format(self.overlap_thresh,
                                                       self.map_type, map_stat))

    def get_results(self):
296
        return {'bbox': [self.detection_map.get_map()]}
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314


class WiderFaceMetric(Metric):
    def __init__(self, image_dir, anno_file, multi_scale=True):
        self.image_dir = image_dir
        self.anno_file = anno_file
        self.multi_scale = multi_scale
        self.clsid2catid, self.catid2name = get_categories('widerface')

    def update(self, model):

        face_eval_run(
            model,
            self.image_dir,
            self.anno_file,
            pred_dir='output/pred',
            eval_mode='widerface',
            multi_scale=self.multi_scale)
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405


class RBoxMetric(Metric):
    def __init__(self, anno_file, **kwargs):
        assert os.path.isfile(anno_file), \
                "anno_file {} not a file".format(anno_file)
        assert os.path.exists(anno_file), "anno_file {} not exists".format(
            anno_file)
        self.anno_file = anno_file
        self.gt_anno = json.load(open(self.anno_file))
        cats = self.gt_anno['categories']
        self.clsid2catid = {i: cat['id'] for i, cat in enumerate(cats)}
        self.catid2clsid = {cat['id']: i for i, cat in enumerate(cats)}
        self.catid2name = {cat['id']: cat['name'] for cat in cats}
        self.classwise = kwargs.get('classwise', False)
        self.output_eval = kwargs.get('output_eval', None)
        # TODO: bias should be unified
        self.bias = kwargs.get('bias', 0)
        self.save_prediction_only = kwargs.get('save_prediction_only', False)
        self.iou_type = kwargs.get('IouType', 'bbox')
        self.overlap_thresh = kwargs.get('overlap_thresh', 0.5)
        self.map_type = kwargs.get('map_type', '11point')
        self.evaluate_difficult = kwargs.get('evaluate_difficult', False)
        class_num = len(self.catid2name)
        self.detection_map = DetectionMAP(
            class_num=class_num,
            overlap_thresh=self.overlap_thresh,
            map_type=self.map_type,
            is_bbox_normalized=False,
            evaluate_difficult=self.evaluate_difficult,
            catid2name=self.catid2name,
            classwise=self.classwise)

        self.reset()

    def reset(self):
        self.result_bbox = []
        self.detection_map.reset()

    def update(self, inputs, outputs):
        outs = {}
        # outputs Tensor -> numpy.ndarray
        for k, v in outputs.items():
            outs[k] = v.numpy() if isinstance(v, paddle.Tensor) else v

        im_id = inputs['im_id']
        outs['im_id'] = im_id.numpy() if isinstance(im_id,
                                                    paddle.Tensor) else im_id

        infer_results = get_infer_results(
            outs, self.clsid2catid, bias=self.bias)
        self.result_bbox += infer_results[
            'bbox'] if 'bbox' in infer_results else []
        bbox = [b['bbox'] for b in self.result_bbox]
        score = [b['score'] for b in self.result_bbox]
        label = [b['category_id'] for b in self.result_bbox]
        label = [self.catid2clsid[e] for e in label]
        gt_box = [
            e['bbox'] for e in self.gt_anno['annotations']
            if e['image_id'] == outs['im_id']
        ]
        gt_label = [
            e['category_id'] for e in self.gt_anno['annotations']
            if e['image_id'] == outs['im_id']
        ]
        gt_label = [self.catid2clsid[e] for e in gt_label]
        self.detection_map.update(bbox, score, label, gt_box, gt_label)

    def accumulate(self):
        if len(self.result_bbox) > 0:
            output = "bbox.json"
            if self.output_eval:
                output = os.path.join(self.output_eval, output)
            with open(output, 'w') as f:
                json.dump(self.result_bbox, f)
                logger.info('The bbox result is saved to bbox.json.')

            if self.save_prediction_only:
                logger.info('The bbox result is saved to {} and do not '
                            'evaluate the mAP.'.format(output))
            else:
                logger.info("Accumulating evaluatation results...")
                self.detection_map.accumulate()

    def log(self):
        map_stat = 100. * self.detection_map.get_map()
        logger.info("mAP({:.2f}, {}) = {:.2f}%".format(self.overlap_thresh,
                                                       self.map_type, map_stat))

    def get_results(self):
        return {'bbox': [self.detection_map.get_map()]}
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432


class SNIPERCOCOMetric(COCOMetric):
    def __init__(self, anno_file, **kwargs):
        super(SNIPERCOCOMetric, self).__init__(anno_file, **kwargs)
        self.dataset = kwargs["dataset"]
        self.chip_results = []

    def reset(self):
        # only bbox and mask evaluation support currently
        self.results = {'bbox': [], 'mask': [], 'segm': [], 'keypoint': []}
        self.eval_results = {}
        self.chip_results = []

    def update(self, inputs, outputs):
        outs = {}
        # outputs Tensor -> numpy.ndarray
        for k, v in outputs.items():
            outs[k] = v.numpy() if isinstance(v, paddle.Tensor) else v

        im_id = inputs['im_id']
        outs['im_id'] = im_id.numpy() if isinstance(im_id,
                                                    paddle.Tensor) else im_id

        self.chip_results.append(outs)

    def accumulate(self):
W
Wenyu 已提交
433 434
        results = self.dataset.anno_cropper.aggregate_chips_detections(
            self.chip_results)
435
        for outs in results:
W
Wenyu 已提交
436 437 438 439
            infer_results = get_infer_results(
                outs, self.clsid2catid, bias=self.bias)
            self.results['bbox'] += infer_results[
                'bbox'] if 'bbox' in infer_results else []
440 441

        super(SNIPERCOCOMetric, self).accumulate()