deploy.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import os.path as osp
  16. import cv2
  17. import numpy as np
  18. import yaml
  19. import multiprocessing as mp
  20. import paddlex
  21. import paddle.fluid as fluid
  22. from paddlex.cv.transforms import build_transforms
  23. from paddlex.cv.models import BaseClassifier
  24. from paddlex.cv.models import PPYOLO, FasterRCNN, MaskRCNN
  25. from paddlex.cv.models import DeepLabv3p
  26. class Predictor:
  27. def __init__(self,
  28. model_dir,
  29. use_gpu=True,
  30. gpu_id=0,
  31. use_mkl=False,
  32. mkl_thread_num=4,
  33. use_trt=False,
  34. use_glog=False,
  35. memory_optimize=True):
  36. """ 创建Paddle Predictor
  37. Args:
  38. model_dir: 模型路径(必须是导出的部署或量化模型)
  39. use_gpu: 是否使用gpu,默认True
  40. gpu_id: 使用gpu的id,默认0
  41. use_mkl: 是否使用mkldnn计算库,CPU情况下使用,默认False
  42. mkl_thread_num: mkldnn计算线程数,默认为4
  43. use_trt: 是否使用TensorRT,默认False
  44. use_glog: 是否启用glog日志, 默认False
  45. memory_optimize: 是否启动内存优化,默认True
  46. """
  47. if not osp.isdir(model_dir):
  48. raise Exception("[ERROR] Path {} not exist.".format(model_dir))
  49. if not osp.exists(osp.join(model_dir, "model.yml")):
  50. raise Exception("There's not model.yml in {}".format(model_dir))
  51. with open(osp.join(model_dir, "model.yml")) as f:
  52. self.info = yaml.load(f.read(), Loader=yaml.Loader)
  53. self.status = self.info['status']
  54. if self.status != "Quant" and self.status != "Infer":
  55. raise Exception("[ERROR] Only quantized model or exported "
  56. "inference model is supported.")
  57. self.model_dir = model_dir
  58. self.model_type = self.info['_Attributes']['model_type']
  59. self.model_name = self.info['Model']
  60. self.num_classes = self.info['_Attributes']['num_classes']
  61. self.labels = self.info['_Attributes']['labels']
  62. if self.info['Model'] == 'MaskRCNN':
  63. if self.info['_init_params']['with_fpn']:
  64. self.mask_head_resolution = 28
  65. else:
  66. self.mask_head_resolution = 14
  67. transforms_mode = self.info.get('TransformsMode', 'RGB')
  68. if transforms_mode == 'RGB':
  69. to_rgb = True
  70. else:
  71. to_rgb = False
  72. self.transforms = build_transforms(self.model_type,
  73. self.info['Transforms'], to_rgb)
  74. self.predictor = self.create_predictor(use_gpu, gpu_id, use_mkl,
  75. mkl_thread_num, use_trt,
  76. use_glog, memory_optimize)
  77. # 线程池,在模型在预测时用于对输入数据以图片为单位进行并行处理
  78. # 主要用于batch_predict接口
  79. thread_num = mp.cpu_count() if mp.cpu_count() < 8 else 8
  80. self.thread_pool = mp.pool.ThreadPool(thread_num)
  81. def reset_thread_pool(self, thread_num):
  82. self.thread_pool.close()
  83. self.thread_pool.join()
  84. self.thread_pool = mp.pool.ThreadPool(thread_num)
  85. def create_predictor(self,
  86. use_gpu=True,
  87. gpu_id=0,
  88. use_mkl=False,
  89. mkl_thread_num=4,
  90. use_trt=False,
  91. use_glog=False,
  92. memory_optimize=True):
  93. config = fluid.core.AnalysisConfig(
  94. os.path.join(self.model_dir, '__model__'),
  95. os.path.join(self.model_dir, '__params__'))
  96. if use_gpu:
  97. # 设置GPU初始显存(单位M)和Device ID
  98. config.enable_use_gpu(100, gpu_id)
  99. else:
  100. config.disable_gpu()
  101. if use_mkl:
  102. config.enable_mkldnn()
  103. config.set_cpu_math_library_num_threads(mkl_thread_num)
  104. if use_glog:
  105. config.enable_glog_info()
  106. else:
  107. config.disable_glog_info()
  108. if memory_optimize:
  109. config.enable_memory_optim()
  110. # 开启计算图分析优化,包括OP融合等
  111. config.switch_ir_optim(True)
  112. # 关闭feed和fetch OP使用,使用ZeroCopy接口必须设置此项
  113. config.switch_use_feed_fetch_ops(False)
  114. predictor = fluid.core.create_paddle_predictor(config)
  115. return predictor
  116. def preprocess(self, image, thread_pool=None):
  117. """ 对图像做预处理
  118. Args:
  119. image(list|tuple): 数组中的元素可以是图像路径,也可以是解码后的排列格式为(H,W,C)
  120. 且类型为float32且为BGR格式的数组。
  121. """
  122. res = dict()
  123. if self.model_type == "classifier":
  124. im = BaseClassifier._preprocess(
  125. image,
  126. self.transforms,
  127. self.model_type,
  128. self.model_name,
  129. thread_pool=thread_pool)
  130. res['image'] = im
  131. elif self.model_type == "detector":
  132. if self.model_name in ["PPYOLO", "YOLOv3"]:
  133. im, im_size = PPYOLO._preprocess(
  134. image,
  135. self.transforms,
  136. self.model_type,
  137. self.model_name,
  138. thread_pool=thread_pool)
  139. res['image'] = im
  140. res['im_size'] = im_size
  141. if self.model_name.count('RCNN') > 0:
  142. im, im_resize_info, im_shape = FasterRCNN._preprocess(
  143. image,
  144. self.transforms,
  145. self.model_type,
  146. self.model_name,
  147. thread_pool=thread_pool)
  148. res['image'] = im
  149. res['im_info'] = im_resize_info
  150. res['im_shape'] = im_shape
  151. elif self.model_type == "segmenter":
  152. im, im_info = DeepLabv3p._preprocess(
  153. image,
  154. self.transforms,
  155. self.model_type,
  156. self.model_name,
  157. thread_pool=thread_pool)
  158. res['image'] = im
  159. res['im_info'] = im_info
  160. return res
  161. def postprocess(self,
  162. results,
  163. topk=1,
  164. batch_size=1,
  165. im_shape=None,
  166. im_info=None):
  167. """ 对预测结果做后处理
  168. Args:
  169. results (list): 预测结果
  170. topk (int): 分类预测时前k个最大值
  171. batch_size (int): 预测时图像批量大小
  172. im_shape (list): MaskRCNN的图像输入大小
  173. im_info (list):RCNN系列和分割网络的原图大小
  174. """
  175. def offset_to_lengths(lod):
  176. offset = lod[0]
  177. lengths = [
  178. offset[i + 1] - offset[i] for i in range(len(offset) - 1)
  179. ]
  180. return [lengths]
  181. if self.model_type == "classifier":
  182. true_topk = min(self.num_classes, topk)
  183. preds = BaseClassifier._postprocess([results[0][0]], true_topk,
  184. self.labels)
  185. elif self.model_type == "detector":
  186. res = {'bbox': (results[0][0], offset_to_lengths(results[0][1])), }
  187. res['im_id'] = (np.array(
  188. [[i] for i in range(batch_size)]).astype('int32'), [[]])
  189. if self.model_name in ["PPYOLO", "YOLOv3"]:
  190. preds = PPYOLO._postprocess(res, batch_size, self.num_classes,
  191. self.labels)
  192. elif self.model_name == "FasterRCNN":
  193. preds = FasterRCNN._postprocess(res, batch_size,
  194. self.num_classes, self.labels)
  195. elif self.model_name == "MaskRCNN":
  196. res['mask'] = (results[1][0], offset_to_lengths(results[1][1]))
  197. res['im_shape'] = (im_shape, [])
  198. preds = MaskRCNN._postprocess(
  199. res, batch_size, self.num_classes,
  200. self.mask_head_resolution, self.labels)
  201. elif self.model_type == "segmenter":
  202. res = [results[0][0], results[1][0]]
  203. preds = DeepLabv3p._postprocess(res, im_info)
  204. return preds
  205. def raw_predict(self, inputs):
  206. """ 接受预处理过后的数据进行预测
  207. Args:
  208. inputs(tuple): 预处理过后的数据
  209. """
  210. for k, v in inputs.items():
  211. try:
  212. tensor = self.predictor.get_input_tensor(k)
  213. except:
  214. continue
  215. tensor.copy_from_cpu(v)
  216. self.predictor.zero_copy_run()
  217. output_names = self.predictor.get_output_names()
  218. output_results = list()
  219. for name in output_names:
  220. output_tensor = self.predictor.get_output_tensor(name)
  221. output_tensor_lod = output_tensor.lod()
  222. output_results.append(
  223. [output_tensor.copy_to_cpu(), output_tensor_lod])
  224. return output_results
  225. def predict(self, image, topk=1):
  226. """ 图片预测
  227. Args:
  228. image(str|np.ndarray): 图像路径;或者是解码后的排列格式为(H, W, C)且类型为float32且为BGR格式的数组。
  229. topk(int): 分类预测时使用,表示预测前topk的结果
  230. """
  231. preprocessed_input = self.preprocess([image])
  232. model_pred = self.raw_predict(preprocessed_input)
  233. im_shape = None if 'im_shape' not in preprocessed_input else preprocessed_input[
  234. 'im_shape']
  235. im_info = None if 'im_info' not in preprocessed_input else preprocessed_input[
  236. 'im_info']
  237. results = self.postprocess(
  238. model_pred,
  239. topk=topk,
  240. batch_size=1,
  241. im_shape=im_shape,
  242. im_info=im_info)
  243. return results[0]
  244. def batch_predict(self, image_list, topk=1):
  245. """ 图片预测
  246. Args:
  247. image_list(list|tuple): 对列表(或元组)中的图像同时进行预测,列表中的元素可以是图像路径
  248. 也可以是解码后的排列格式为(H,W,C)且类型为float32且为BGR格式的数组。
  249. topk(int): 分类预测时使用,表示预测前topk的结果
  250. """
  251. preprocessed_input = self.preprocess(image_list, self.thread_pool)
  252. model_pred = self.raw_predict(preprocessed_input)
  253. im_shape = None if 'im_shape' not in preprocessed_input else preprocessed_input[
  254. 'im_shape']
  255. im_info = None if 'im_info' not in preprocessed_input else preprocessed_input[
  256. 'im_info']
  257. results = self.postprocess(
  258. model_pred,
  259. topk=topk,
  260. batch_size=len(image_list),
  261. im_shape=im_shape,
  262. im_info=im_info)
  263. return results