infer.py 2.1 KB
Newer Older
D
dengkaipeng 已提交
1 2 3 4 5 6 7 8
import os
import time
import numpy as np
import paddle
import paddle.fluid as fluid
import box_utils
import reader
from utility import print_arguments, parse_args
D
dengkaipeng 已提交
9
from models.yolov3 import YOLOv3
D
dengkaipeng 已提交
10 11
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval, Params
T
tink2123 已提交
12
from config import cfg
D
dengkaipeng 已提交
13 14 15 16 17 18 19


def infer():

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

D
dengkaipeng 已提交
20
    model = YOLOv3(cfg.model_cfg_path, is_train=False)
D
dengkaipeng 已提交
21 22
    model.build_model()
    outputs = model.get_pred()
D
dengkaipeng 已提交
23
    input_size = cfg.input_size
D
dengkaipeng 已提交
24 25 26
    place = fluid.CUDAPlace(0) if cfg.use_gpu else fluid.CPUPlace()
    exe = fluid.Executor(place)
    # yapf: disable
D
dengkaipeng 已提交
27
    if cfg.weights:
D
dengkaipeng 已提交
28
        def if_exist(var):
D
dengkaipeng 已提交
29 30
            return os.path.exists(os.path.join(cfg.weights, var.name))
        fluid.io.load_vars(exe, cfg.weights, predicate=if_exist)
D
dengkaipeng 已提交
31 32
    # yapf: enable
    feeder = fluid.DataFeeder(place=place, feed_list=model.feeds())
D
dengkaipeng 已提交
33
    fetch_list = [outputs]
D
dengkaipeng 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    image_names = []
    if cfg.image_name is not None:
        image_names.append(cfg.image_name)
    else:
        for image_name in os.listdir(cfg.image_path):
            if image_name.split('.')[-1] in ['jpg', 'png']:
                image_names.append(image_name)
    for image_name in image_names:
        infer_reader = reader.infer(input_size, os.path.join(cfg.image_path, image_name))
        label_names, _ = reader.get_label_infos()
        data = next(infer_reader())
        im_shape = data[0][2]
        outputs = exe.run(
            fetch_list=[v.name for v in fetch_list],
            feed=feeder.feed(data),
D
dengkaipeng 已提交
49 50 51 52
            return_numpy=False)
        bboxes = np.array(outputs[0])
        if bboxes.shape[1] != 6:
            print("No object found in {}".format(image_name))
53
            continue
D
dengkaipeng 已提交
54 55 56
        labels = bboxes[:, 0].astype('int32')
        scores = bboxes[:, 1].astype('float32')
        boxes = bboxes[:, 2:].astype('float32')
D
dengkaipeng 已提交
57 58 59 60 61 62 63 64 65

        path = os.path.join(cfg.image_path, image_name)
        box_utils.draw_boxes_on_image(path, boxes, scores, labels, label_names, cfg.draw_thresh)


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