predict_cls.py 6.1 KB
Newer Older
littletomatodonkey's avatar
littletomatodonkey 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

R
fix  
root 已提交
15 16
import os

littletomatodonkey's avatar
littletomatodonkey 已提交
17 18 19
import cv2
import numpy as np

20 21 22 23 24
from paddleclas.deploy.utils import logger, config
from paddleclas.deploy.utils.predictor import Predictor
from paddleclas.deploy.utils.get_image_list import get_image_list
from paddleclas.deploy.python.preprocess import create_operators
from paddleclas.deploy.python.postprocess import build_postprocess
littletomatodonkey's avatar
littletomatodonkey 已提交
25 26


littletomatodonkey's avatar
littletomatodonkey 已提交
27
class ClsPredictor(Predictor):
littletomatodonkey's avatar
littletomatodonkey 已提交
28
    def __init__(self, config):
littletomatodonkey's avatar
littletomatodonkey 已提交
29
        super().__init__(config["Global"])
T
Tingquan Gao 已提交
30 31 32 33 34 35 36 37 38

        self.preprocess_ops = []
        self.postprocess = None
        if "PreProcess" in config:
            if "transform_ops" in config["PreProcess"]:
                self.preprocess_ops = create_operators(config["PreProcess"][
                    "transform_ops"])
        if "PostProcess" in config:
            self.postprocess = build_postprocess(config["PostProcess"])
littletomatodonkey's avatar
littletomatodonkey 已提交
39

D
dongshuilong 已提交
40
        # for whole_chain project to test each repo of paddle
D
dongshuilong 已提交
41
        self.benchmark = config["Global"].get("benchmark", False)
D
dongshuilong 已提交
42 43 44 45
        if self.benchmark:
            import auto_log
            import os
            pid = os.getpid()
D
dongshuilong 已提交
46 47
            size = config["PreProcess"]["transform_ops"][1]["CropImage"][
                "size"]
littletomatodonkey's avatar
littletomatodonkey 已提交
48 49 50 51 52 53
            if config["Global"].get("use_int8", False):
                precision = "int8"
            elif config["Global"].get("use_fp16", False):
                precision = "fp16"
            else:
                precision = "fp32"
D
dongshuilong 已提交
54
            self.auto_logger = auto_log.AutoLogger(
D
dongshuilong 已提交
55
                model_name=config["Global"].get("model_name", "cls"),
littletomatodonkey's avatar
littletomatodonkey 已提交
56
                model_precision=precision,
D
dongshuilong 已提交
57
                batch_size=config["Global"].get("batch_size", 1),
D
dongshuilong 已提交
58
                data_shape=[3, size, size],
D
dongshuilong 已提交
59 60 61
                save_path=config["Global"].get("save_log_path",
                                               "./auto_log.log"),
                inference_config=self.config,
D
dongshuilong 已提交
62 63 64
                pids=pid,
                process_name=None,
                gpu_ids=None,
D
dongshuilong 已提交
65 66 67 68
                time_keys=[
                    'preprocess_time', 'inference_time', 'postprocess_time'
                ],
                warmup=2)
D
dongshuilong 已提交
69

littletomatodonkey's avatar
littletomatodonkey 已提交
70
    def predict(self, images):
71 72 73 74 75 76 77 78 79 80
        use_onnx = self.args.get("use_onnx", False)
        if not use_onnx:
            input_names = self.predictor.get_input_names()
            input_tensor = self.predictor.get_input_handle(input_names[0])

            output_names = self.predictor.get_output_names()
            output_tensor = self.predictor.get_output_handle(output_names[0])
        else:
            input_names = self.predictor.get_inputs()[0].name
            output_names = self.predictor.get_outputs()[0].name
littletomatodonkey's avatar
littletomatodonkey 已提交
81

D
dongshuilong 已提交
82
        if self.benchmark:
D
dongshuilong 已提交
83
            self.auto_logger.times.start()
littletomatodonkey's avatar
littletomatodonkey 已提交
84 85 86 87 88 89
        if not isinstance(images, (list, )):
            images = [images]
        for idx in range(len(images)):
            for ops in self.preprocess_ops:
                images[idx] = ops(images[idx])
        image = np.array(images)
D
dongshuilong 已提交
90
        if self.benchmark:
D
dongshuilong 已提交
91
            self.auto_logger.times.stamp()
littletomatodonkey's avatar
littletomatodonkey 已提交
92

93 94 95 96 97 98 99 100 101
        if not use_onnx:
            input_tensor.copy_from_cpu(image)
            self.predictor.run()
            batch_output = output_tensor.copy_to_cpu()
        else:
            batch_output = self.predictor.run(
                output_names=[output_names],
                input_feed={input_names: image})[0]

D
dongshuilong 已提交
102
        if self.benchmark:
D
dongshuilong 已提交
103
            self.auto_logger.times.stamp()
104 105
        if self.postprocess is not None:
            batch_output = self.postprocess(batch_output)
D
dongshuilong 已提交
106
        if self.benchmark:
D
dongshuilong 已提交
107
            self.auto_logger.times.end(stamp=True)
littletomatodonkey's avatar
littletomatodonkey 已提交
108 109
        return batch_output

littletomatodonkey's avatar
littletomatodonkey 已提交
110 111 112 113 114

def main(config):
    cls_predictor = ClsPredictor(config)
    image_list = get_image_list(config["Global"]["infer_imgs"])

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    batch_imgs = []
    batch_names = []
    cnt = 0
    for idx, img_path in enumerate(image_list):
        img = cv2.imread(img_path)
        if img is None:
            logger.warning(
                "Image file failed to read and has been skipped. The path: {}".
                format(img_path))
        else:
            img = img[:, :, ::-1]
            batch_imgs.append(img)
            img_name = os.path.basename(img_path)
            batch_names.append(img_name)
            cnt += 1
littletomatodonkey's avatar
littletomatodonkey 已提交
130

D
dongshuilong 已提交
131 132 133
        if cnt % config["Global"]["batch_size"] == 0 or (idx + 1
                                                         ) == len(image_list):
            if len(batch_imgs) == 0:
134 135 136
                continue
            batch_results = cls_predictor.predict(batch_imgs)
            for number, result_dict in enumerate(batch_results):
137
                if "PersonAttribute" in config[
138 139
                        "PostProcess"] or "VehicleAttribute" in config[
                            "PostProcess"]:
Z
zhiboniu 已提交
140
                    filename = batch_names[number]
littletomatodonkey's avatar
littletomatodonkey 已提交
141
                    print("{}:\t {}".format(filename, result_dict))
Z
zhiboniu 已提交
142 143 144 145 146 147 148 149 150
                else:
                    filename = batch_names[number]
                    clas_ids = result_dict["class_ids"]
                    scores_str = "[{}]".format(", ".join("{:.2f}".format(
                        r) for r in result_dict["scores"]))
                    label_names = result_dict["label_names"]
                    print(
                        "{}:\tclass id(s): {}, score(s): {}, label_name(s): {}".
                        format(filename, clas_ids, scores_str, label_names))
151 152
            batch_imgs = []
            batch_names = []
D
dongshuilong 已提交
153 154
    if cls_predictor.benchmark:
        cls_predictor.auto_logger.report()
littletomatodonkey's avatar
littletomatodonkey 已提交
155 156 157 158 159 160 161
    return


if __name__ == "__main__":
    args = config.parse_args()
    config = config.get_config(args.config, overrides=args.override, show=True)
    main(config)