1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
| import codecs import os import time import sys sys.path.append('PaddleDetection') import json import yaml from functools import reduce import multiprocessing
from PIL import Image import cv2 import numpy as np import paddle
from paddle.inference import Config from paddle.inference import create_predictor from multiprocessing.dummy import Pool as ThreadPool from functools import partial from deploy.python.preprocess import preprocess,Resize, NormalizeImage, Permute, PadStride from deploy.python.utils import argsparser, Timer, get_current_memory_mb
LABEL_MAP = { "0": "bump", "1": "granary", "2": "CrossWalk", "3": "cone", "4": "bridge", "5": "pig", "6": "tractor", "7": "corn", }
class PredictConfig(): def __init__(self, model_dir): deploy_file = os.path.join(model_dir, 'infer_cfg.yml') with open(deploy_file) as f: yml_conf = yaml.safe_load(f) self.arch = yml_conf['arch'] self.preprocess_infos = yml_conf['Preprocess'] self.min_subgraph_size = yml_conf['min_subgraph_size'] self.labels = yml_conf['label_list']
def get_test_images(infer_file): with open(infer_file, 'r') as f: dirs = f.readlines() images = [] for dir in dirs: images.append(eval(repr(dir.replace('\n',''))).replace('\\', '/')) assert len(images) > 0, "no image found in {}".format(infer_file) return images
def load_predictor(model_dir): config = Config( os.path.join(model_dir, 'model.pdmodel'), os.path.join(model_dir, 'model.pdiparams')) config.enable_use_gpu(3000, 0) config.switch_ir_optim(True) config.disable_glog_info() config.enable_memory_optim() config.switch_use_feed_fetch_ops(False) predictor = create_predictor(config) return predictor, config
def create_inputs(imgs, im_info): inputs = {}
im_shape = [] scale_factor = [] if len(imgs) == 1: inputs['image'] = np.array((imgs[0], )).astype('float32') inputs['im_shape'] = np.array( (im_info[0]['im_shape'], )).astype('float32') inputs['scale_factor'] = np.array( (im_info[0]['scale_factor'], )).astype('float32') return inputs
for e in im_info: im_shape.append(np.array((e['im_shape'], )).astype('float32')) scale_factor.append(np.array((e['scale_factor'], )).astype('float32'))
inputs['im_shape'] = np.concatenate(im_shape, axis=0) inputs['scale_factor'] = np.concatenate(scale_factor, axis=0)
imgs_shape = [[e.shape[1], e.shape[2]] for e in imgs] max_shape_h = max([e[0] for e in imgs_shape]) max_shape_w = max([e[1] for e in imgs_shape]) padding_imgs = [] for img in imgs: im_c, im_h, im_w = img.shape[:] padding_im = np.zeros( (im_c, max_shape_h, max_shape_w), dtype=np.float32) padding_im[:, :im_h, :im_w] = img padding_imgs.append(padding_im) inputs['image'] = np.stack(padding_imgs, axis=0) return inputs
class Detector(object):
def __init__(self, pred_config, model_dir): self.pred_config = pred_config self.predictor, self.config = load_predictor(model_dir) self.preprocess_ops = self.get_ops() def get_ops(self): preprocess_ops = [] for op_info in self.pred_config.preprocess_infos: new_op_info = op_info.copy() op_type = new_op_info.pop('type') preprocess_ops.append(eval(op_type)(**new_op_info)) return preprocess_ops
def predict(self, inputs): input_names = self.predictor.get_input_names() for i in range(len(input_names)): input_tensor = self.predictor.get_input_handle(input_names[i]) input_tensor.copy_from_cpu(inputs[input_names[i]])
self.predictor.run() output_names = self.predictor.get_output_names() boxes_tensor = self.predictor.get_output_handle(output_names[0]) np_boxes = boxes_tensor.copy_to_cpu() boxes_num = self.predictor.get_output_handle(output_names[1]) np_boxes_num = boxes_num.copy_to_cpu()
results = [] if reduce(lambda x, y: x * y, np_boxes.shape) < 6: results = {'boxes': np.zeros([]), 'boxes_num': [0]} else: results = {'boxes': np_boxes, 'boxes_num': np_boxes_num} return results
def my_preprocess(para): im_path, preprocess_ops = para im, im_info = preprocess(im_path, preprocess_ops) return im, im_info
def predict_image(detector, image_list, result_path): c_results = {"result": []} multiclass_thres = [0.49, 0.49, 0.49, 0.49, 0.49, 0.49, 0.49, 0.49] num_worker = 4 pool = ThreadPool(processes=num_worker) img_length = len(image_list) img_iter_filter = 10 img_iter_range = list(range(img_length//img_iter_filter)) for start_index in img_iter_range: if start_index == img_iter_range[-1]: im_paths = image_list[start_index*img_iter_filter:] else: im_paths = image_list[start_index*img_iter_filter:(start_index+1)*img_iter_filter] image_ids = [int(os.path.basename(im_p).split('.')[0]) for im_p in im_paths] para = [[i,detector.preprocess_ops] for i in im_paths] imandinfos = pool.map(my_preprocess, para) for idx, imandinfo in enumerate(imandinfos): image_id = image_ids[idx] inputs = create_inputs([imandinfo[0]], [imandinfo[1]])
det_results = detector.predict(inputs) im_bboxes_num = det_results['boxes_num'][0] if im_bboxes_num > 0: bbox_results = det_results['boxes'][0:im_bboxes_num, 2:] id_results = det_results['boxes'][0:im_bboxes_num, 0] score_results = det_results['boxes'][0:im_bboxes_num, 1] for idx in range(im_bboxes_num): if float(score_results[idx]) >= multiclass_thres[int(id_results[idx])]: c_results["result"].append({"image_id": image_id, "type": LABEL_MAP[str(int(id_results[idx]))], "x": float(bbox_results[idx][0]), "y": float(bbox_results[idx][1]), "width": float(bbox_results[idx][2]) - float(bbox_results[idx][0]), "height": float(bbox_results[idx][3]) - float(bbox_results[idx][1]), "segmentation": []})
with open(result_path, 'w') as ft: json.dump(c_results, ft)
def main(infer_txt, result_path, det_model_path): pred_config = PredictConfig(det_model_path) detector = Detector(pred_config, det_model_path)
img_list = get_test_images(infer_txt) predict_image(detector, img_list, result_path)
if __name__ == '__main__': print('start…') start_time = time.time() det_model_path = "model/"
paddle.enable_static() infer_txt = sys.argv[1] result_path = sys.argv[2] main(infer_txt, result_path, det_model_path) print('total time:', time.time() - start_time)
|