predict_system.py 3.4 KB
Newer Older
F
Felix 已提交
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
littletomatodonkey's avatar
littletomatodonkey 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#
# 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.
import os
import sys

__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.abspath(os.path.join(__dir__, '../')))

import copy
import cv2
import numpy as np

from python.predict_rec import RecPredictor
from python.predict_det import DetPredictor
F
Felix 已提交
26
from vector_search import Graph_Index
littletomatodonkey's avatar
littletomatodonkey 已提交
27 28 29 30

from utils import logger
from utils import config
from utils.get_image_list import get_image_list
L
littletomatodonkey 已提交
31 32
from utils.draw_bbox import draw_bbox_results

littletomatodonkey's avatar
littletomatodonkey 已提交
33 34 35

class SystemPredictor(object):
    def __init__(self, config):
F
Felix 已提交
36 37

        self.config = config
littletomatodonkey's avatar
littletomatodonkey 已提交
38 39 40
        self.rec_predictor = RecPredictor(config)
        self.det_predictor = DetPredictor(config)

F
Felix 已提交
41
        assert 'IndexProcess' in config.keys(), "Index config not found ... "
F
Felix 已提交
42 43 44
        self.return_k = self.config['IndexProcess']['return_k']
        self.search_budget = self.config['IndexProcess']['search_budget']

L
littletomatodonkey 已提交
45 46
        self.Searcher = Graph_Index(
            dist_type=config['IndexProcess']['dist_type'])
F
Felix 已提交
47
        self.Searcher.load(config['IndexProcess']['index_path'])
F
Felix 已提交
48

littletomatodonkey's avatar
littletomatodonkey 已提交
49 50 51 52 53 54 55 56 57
    def append_self(self, results, shape):
        results.append({
            "class_id": 0,
            "score": 1.0,
            "bbox": np.array([0, 0, shape[1], shape[0]]),
            "label_name": "foreground",
        })
        return results

littletomatodonkey's avatar
littletomatodonkey 已提交
58 59 60
    def predict(self, img):
        output = []
        results = self.det_predictor.predict(img)
littletomatodonkey's avatar
littletomatodonkey 已提交
61 62 63
        # add the whole image for recognition
        results = self.append_self(results, img.shape)

littletomatodonkey's avatar
littletomatodonkey 已提交
64
        for result in results:
F
Felix 已提交
65
            preds = {}
L
littletomatodonkey 已提交
66
            xmin, ymin, xmax, ymax = result["bbox"].astype("int")
F
Felix 已提交
67
            crop_img = img[ymin:ymax, xmin:xmax, :].copy()
littletomatodonkey's avatar
littletomatodonkey 已提交
68
            rec_results = self.rec_predictor.predict(crop_img)
F
Felix 已提交
69
            preds["bbox"] = [xmin, ymin, xmax, ymax]
L
littletomatodonkey 已提交
70 71 72 73
            scores, docs = self.Searcher.search(
                query=rec_results,
                return_k=self.return_k,
                search_budget=self.search_budget)
littletomatodonkey's avatar
littletomatodonkey 已提交
74 75 76 77 78 79 80
            # just top-1 result will be returned for the final
            if scores[0] >= self.config["IndexProcess"]["score_thres"]:
                preds["rec_docs"] = docs[0]
                preds["rec_scores"] = scores[0]
            else:
                preds["rec_docs"] = None
                preds["rec_scores"] = 0.0
F
Felix 已提交
81

F
Felix 已提交
82
            output.append(preds)
littletomatodonkey's avatar
littletomatodonkey 已提交
83
        return output
L
littletomatodonkey 已提交
84

littletomatodonkey's avatar
littletomatodonkey 已提交
85 86 87 88 89 90 91 92 93

def main(config):
    system_predictor = SystemPredictor(config)
    image_list = get_image_list(config["Global"]["infer_imgs"])

    assert config["Global"]["batch_size"] == 1
    for idx, image_file in enumerate(image_list):
        img = cv2.imread(image_file)[:, :, ::-1]
        output = system_predictor.predict(img)
littletomatodonkey's avatar
littletomatodonkey 已提交
94
        draw_bbox_results(img, output, image_file)
F
Felix 已提交
95
        print(output)
littletomatodonkey's avatar
littletomatodonkey 已提交
96 97 98 99 100 101 102
    return


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