predict_system.py 4.3 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 31 32

from utils import logger
from utils import config
from utils.get_image_list import get_image_list


F
Felix 已提交
33 34 35
def split_datafile(data_file, image_root):
    gallery_images = []
    gallery_docs = []
B
Bin Lu 已提交
36
    with open(data_file) as f:
F
Felix 已提交
37 38 39 40 41 42 43 44 45 46 47 48
        lines = f.readlines()
        for i, line in enumerate(lines):
            line = line.strip().split("\t")
            if line[0] == 'image_id':
                 continue
            image_file = os.path.join(image_root, line[3])
            image_doc = line[1]
            gallery_images.append(image_file)
            gallery_docs.append(image_doc)
    return gallery_images, gallery_docs


littletomatodonkey's avatar
littletomatodonkey 已提交
49 50
class SystemPredictor(object):
    def __init__(self, config):
F
Felix 已提交
51 52

        self.config = config
littletomatodonkey's avatar
littletomatodonkey 已提交
53 54 55
        self.rec_predictor = RecPredictor(config)
        self.det_predictor = DetPredictor(config)

F
Felix 已提交
56 57 58 59 60 61 62
        assert 'IndexProcess' in config.keys(), "Index config not found ... "
        self.indexer(config['IndexProcess'])
        self.return_k = self.config['IndexProcess']['infer']['return_k']
        self.search_budget = self.config['IndexProcess']['infer']['search_budget']
    
    def indexer(self, config):
        if 'build' in config.keys() and config['build']['enable']:  # build the index from scratch    
B
Bin Lu 已提交
63
            with open(config['build']['data_file']) as f:
F
Felix 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
                lines = f.readlines()
            gallery_images, gallery_docs = split_datafile(config['build']['data_file'], config['build']['image_root'])
            # extract gallery features
            gallery_features = np.zeros([len(gallery_images), config['build']['embedding_size']], dtype=np.float32)
            for i, image_file in enumerate(gallery_images):
                img = cv2.imread(image_file)[:, :, ::-1]
                rec_feat = self.rec_predictor.predict(img)
                gallery_features[i,:] = rec_feat
            # train index 
            self.Searcher = Graph_Index(dist_type=config['build']['dist_type']) 
            self.Searcher.build(gallery_vectors=gallery_features, gallery_docs=gallery_docs, 
                pq_size=config['build']['pq_size'], index_path=config['build']['index_path'])
            
        else:   # load local index
            self.Searcher = Graph_Index(dist_type=config['build']['dist_type']) 
            self.Searcher.load(config['infer']['index_path'])

littletomatodonkey's avatar
littletomatodonkey 已提交
81 82 83 84
    def predict(self, img):
        output = []
        results = self.det_predictor.predict(img)
        for result in results:
L
littletomatodonkey 已提交
85
            xmin, ymin, xmax, ymax = result["bbox"].astype("int")
littletomatodonkey's avatar
littletomatodonkey 已提交
86 87
            crop_img = img[xmin:xmax, ymin:ymax, :].copy()
            rec_results = self.rec_predictor.predict(crop_img)
B
Bin Lu 已提交
88
            result["feature"] = rec_results
F
Felix 已提交
89 90 91 92 93

            scores, docs = self.Searcher.search(query=rec_results, return_k=self.return_k, search_budget=self.search_budget)
            result["ret_docs"] = docs
            result["ret_scores"] = scores

littletomatodonkey's avatar
littletomatodonkey 已提交
94 95
            output.append(result)
        return output
F
Felix 已提交
96
            
littletomatodonkey's avatar
littletomatodonkey 已提交
97 98 99 100 101 102 103 104 105 106


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)
F
Felix 已提交
107
        #print(output)
littletomatodonkey's avatar
littletomatodonkey 已提交
108 109 110 111 112 113 114
    return


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