eval.py 4.1 KB
Newer Older
D
dengkaipeng 已提交
1
#  Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
D
dengkaipeng 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#
#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 time
D
dengkaipeng 已提交
20
import json
D
dengkaipeng 已提交
21 22 23 24
import numpy as np
import paddle
import paddle.fluid as fluid
import reader
D
dengkaipeng 已提交
25
from models.yolov3 import YOLOv3
D
dengkaipeng 已提交
26 27 28
from utility import print_arguments, parse_args
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval, Params
T
tink2123 已提交
29
from config import cfg
D
dengkaipeng 已提交
30 31 32 33 34 35 36 37 38 39 40 41


def eval():
    if '2014' in cfg.dataset:
        test_list = 'annotations/instances_val2014.json'
    elif '2017' in cfg.dataset:
        test_list = 'annotations/instances_val2017.json'

    if cfg.debug:
        if not os.path.exists('output'):
            os.mkdir('output')

D
dengkaipeng 已提交
42
    model = YOLOv3(is_train=False)
D
dengkaipeng 已提交
43 44 45 46 47
    model.build_model()
    outputs = model.get_pred()
    place = fluid.CUDAPlace(0) if cfg.use_gpu else fluid.CPUPlace()
    exe = fluid.Executor(place)
    # yapf: disable
D
dengkaipeng 已提交
48
    if cfg.weights:
D
dengkaipeng 已提交
49
        def if_exist(var):
D
dengkaipeng 已提交
50 51
            return os.path.exists(os.path.join(cfg.weights, var.name))
        fluid.io.load_vars(exe, cfg.weights, predicate=if_exist)
D
dengkaipeng 已提交
52
    # yapf: enable
D
dengkaipeng 已提交
53
    input_size = cfg.input_size
D
dengkaipeng 已提交
54 55 56 57 58 59
    test_reader = reader.test(input_size, 1)
    label_names, label_ids = reader.get_label_infos()
    if cfg.debug:
        print("Load in labels {} with ids {}".format(label_names, label_ids))
    feeder = fluid.DataFeeder(place=place, feed_list=model.feeds())

D
dengkaipeng 已提交
60
    def get_pred_result(boxes, scores, labels, im_id):
D
dengkaipeng 已提交
61
        result = []
D
dengkaipeng 已提交
62
        for box, score, label in zip(boxes, scores, labels):
D
dengkaipeng 已提交
63 64
            x1, y1, x2, y2 = box
            w = x2 - x1 + 1
D
dengkaipeng 已提交
65
            h = y2 - y1 + 1
D
dengkaipeng 已提交
66 67 68 69 70
            bbox = [x1, y1, w, h]
            
            res = {
                    'image_id': im_id,
                    'category_id': label_ids[int(label)],
D
dengkaipeng 已提交
71
                    'bbox': list(map(float, bbox)),
D
dengkaipeng 已提交
72
                    'score': float(score)
D
dengkaipeng 已提交
73 74 75 76 77
            }
            result.append(res)
        return result

    dts_res = []
D
dengkaipeng 已提交
78
    fetch_list = [outputs]
D
dengkaipeng 已提交
79 80 81 82 83 84
    total_time = 0
    for batch_id, batch_data in enumerate(test_reader()):
        start_time = time.time()
        batch_outputs = exe.run(
            fetch_list=[v.name for v in fetch_list],
            feed=feeder.feed(batch_data),
D
dengkaipeng 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
            return_numpy=False,
            use_program_cache=True)
        lod = batch_outputs[0].lod()[0]
        nmsed_boxes = np.array(batch_outputs[0])
        if nmsed_boxes.shape[1] != 6:
            continue
        for i in range(len(lod) - 1):
            im_id = batch_data[i][1]
            start = lod[i]
            end = lod[i + 1]
            if start == end:
                continue
            nmsed_box = nmsed_boxes[start:end, :]
            labels = nmsed_box[:, 0]
            scores = nmsed_box[:, 1]
            boxes = nmsed_box[:, 2:6]
D
dengkaipeng 已提交
101 102
            dts_res += get_pred_result(boxes, scores, labels, im_id)

D
dengkaipeng 已提交
103 104 105
        end_time = time.time()
        print("batch id: {}, time: {}".format(batch_id, end_time - start_time))
        total_time += end_time - start_time
D
dengkaipeng 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

    with open("yolov3_result.json", 'w') as outfile:
        json.dump(dts_res, outfile)
    print("start evaluate detection result with coco api")
    coco = COCO(os.path.join(cfg.data_dir, test_list))
    cocoDt = coco.loadRes("yolov3_result.json")
    cocoEval = COCOeval(coco, cocoDt, 'bbox')
    cocoEval.evaluate()
    cocoEval.accumulate()
    cocoEval.summarize()
    print("evaluate done.")

    print("Time per batch: {}".format(total_time / batch_id))


if __name__ == '__main__':
    args = parse_args()
    print_arguments(args)
    eval()