predict_system.py 5.8 KB
Newer Older
F
Felix 已提交
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
littletomatodonkey's avatar
littletomatodonkey 已提交
2
#
D
dongshuilong 已提交
3
# Licensed under the Apache License, Version 2.0 (the "License"); 
littletomatodonkey's avatar
littletomatodonkey 已提交
4 5 6 7 8 9 10 11 12 13 14 15
# 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 copy
16

littletomatodonkey's avatar
littletomatodonkey 已提交
17
import numpy as np
18
import cv2
D
dongshuilong 已提交
19 20
import faiss
import pickle
littletomatodonkey's avatar
littletomatodonkey 已提交
21

22 23 24 25 26
from paddleclas.deploy.utils import logger, config
from paddleclas.deploy.utils.get_image_list import get_image_list
from paddleclas.deploy.utils.draw_bbox import draw_bbox_results
from paddleclas.deploy.python.predict_rec import RecPredictor
from paddleclas.deploy.python.predict_det import DetPredictor
L
littletomatodonkey 已提交
27

littletomatodonkey's avatar
littletomatodonkey 已提交
28 29 30

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

        self.config = config
littletomatodonkey's avatar
littletomatodonkey 已提交
33
        self.rec_predictor = RecPredictor(config)
34 35 36 37 38 39 40 41

        if not config["Global"]["det_inference_model_dir"]:
            logger.info(
                f"find 'Global.det_inference_model_dir' empty({config['Global']['det_inference_model_dir']}), so det_predictor is disabled"
            )
            self.det_predictor = None
        else:
            self.det_predictor = DetPredictor(config)
littletomatodonkey's avatar
littletomatodonkey 已提交
42

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

D
dongshuilong 已提交
46 47 48 49 50
        index_dir = self.config["IndexProcess"]["index_dir"]
        assert os.path.exists(os.path.join(
            index_dir, "vector.index")), "vector.index not found ..."
        assert os.path.exists(os.path.join(
            index_dir, "id_map.pkl")), "id_map.pkl not found ... "
S
stephon 已提交
51 52

        if config['IndexProcess'].get("dist_type") == "hamming":
53 54 55 56 57
            self.Searcher = faiss.read_index_binary(
                os.path.join(index_dir, "vector.index"))
        else:
            self.Searcher = faiss.read_index(
                os.path.join(index_dir, "vector.index"))
S
stephon 已提交
58

D
dongshuilong 已提交
59 60
        with open(os.path.join(index_dir, "id_map.pkl"), "rb") as fd:
            self.id_map = pickle.load(fd)
F
Felix 已提交
61

littletomatodonkey's avatar
littletomatodonkey 已提交
62 63 64 65
    def append_self(self, results, shape):
        results.append({
            "class_id": 0,
            "score": 1.0,
66 67
            "bbox":
            np.array([0, 0, shape[1], shape[0]]),  # xmin, ymin, xmax, ymax
littletomatodonkey's avatar
littletomatodonkey 已提交
68 69 70 71
            "label_name": "foreground",
        })
        return results

D
dyning 已提交
72
    def nms_to_rec_results(self, results, thresh=0.1):
73 74 75 76 77 78 79 80 81 82 83 84
        filtered_results = []
        x1 = np.array([r["bbox"][0] for r in results]).astype("float32")
        y1 = np.array([r["bbox"][1] for r in results]).astype("float32")
        x2 = np.array([r["bbox"][2] for r in results]).astype("float32")
        y2 = np.array([r["bbox"][3] for r in results]).astype("float32")
        scores = np.array([r["rec_scores"] for r in results])

        areas = (x2 - x1 + 1) * (y2 - y1 + 1)
        order = scores.argsort()[::-1]
        while order.size > 0:
            i = order[0]
            xx1 = np.maximum(x1[i], x1[order[1:]])
D
dyning 已提交
85
            yy1 = np.maximum(y1[i], y1[order[1:]])
86
            xx2 = np.minimum(x2[i], x2[order[1:]])
D
dyning 已提交
87
            yy2 = np.minimum(y2[i], y2[order[1:]])
88 89 90 91 92 93 94 95 96 97 98

            w = np.maximum(0.0, xx2 - xx1 + 1)
            h = np.maximum(0.0, yy2 - yy1 + 1)
            inter = w * h
            ovr = inter / (areas[i] + areas[order[1:]] - inter)
            inds = np.where(ovr <= thresh)[0]
            order = order[inds + 1]
            filtered_results.append(results[i])

        return filtered_results

littletomatodonkey's avatar
littletomatodonkey 已提交
99 100
    def predict(self, img):
        output = []
101
        # st1: get all detection results
102 103 104 105
        if self.det_predictor:
            results = self.det_predictor.predict(img)
        else:
            results = []
106 107

        # st2: add the whole image for recognition to improve recall
littletomatodonkey's avatar
littletomatodonkey 已提交
108 109
        results = self.append_self(results, img.shape)

110
        # st3: recognition process, use score_thres to ensure accuracy
littletomatodonkey's avatar
littletomatodonkey 已提交
111
        for result in results:
F
Felix 已提交
112
            preds = {}
L
littletomatodonkey 已提交
113
            xmin, ymin, xmax, ymax = result["bbox"].astype("int")
F
Felix 已提交
114
            crop_img = img[ymin:ymax, xmin:xmax, :].copy()
littletomatodonkey's avatar
littletomatodonkey 已提交
115
            rec_results = self.rec_predictor.predict(crop_img)
F
Felix 已提交
116
            preds["bbox"] = [xmin, ymin, xmax, ymax]
D
dongshuilong 已提交
117
            scores, docs = self.Searcher.search(rec_results, self.return_k)
S
stephon 已提交
118

littletomatodonkey's avatar
littletomatodonkey 已提交
119
            # just top-1 result will be returned for the final
S
stephon 已提交
120 121 122 123 124 125 126 127 128 129 130
            if self.config["IndexProcess"]["dist_type"] == "hamming":
                if scores[0][0] <= self.config["IndexProcess"][
                        "hamming_radius"]:
                    preds["rec_docs"] = self.id_map[docs[0][0]].split()[1]
                    preds["rec_scores"] = scores[0][0]
                    output.append(preds)
            else:
                if scores[0][0] >= self.config["IndexProcess"]["score_thres"]:
                    preds["rec_docs"] = self.id_map[docs[0][0]].split()[1]
                    preds["rec_scores"] = scores[0][0]
                    output.append(preds)
131 132 133 134

        # st5: nms to the final results to avoid fetching duplicate results
        output = self.nms_to_rec_results(
            output, self.config["Global"]["rec_nms_thresold"])
F
Felix 已提交
135

littletomatodonkey's avatar
littletomatodonkey 已提交
136
        return output
L
littletomatodonkey 已提交
137

littletomatodonkey's avatar
littletomatodonkey 已提交
138 139 140 141 142 143 144 145 146

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 已提交
147
        draw_bbox_results(img, output, image_file)
F
Felix 已提交
148
        print(output)
littletomatodonkey's avatar
littletomatodonkey 已提交
149 150 151 152 153 154 155
    return


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