deploy.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 psutil
  17. import cv2
  18. import numpy as np
  19. import yaml
  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=psutil.cpu_count(),
  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. def create_predictor(self,
  78. use_gpu=True,
  79. gpu_id=0,
  80. use_mkl=False,
  81. mkl_thread_num=psutil.cpu_count(),
  82. use_trt=False,
  83. use_glog=False,
  84. memory_optimize=True):
  85. config = fluid.core.AnalysisConfig(
  86. os.path.join(self.model_dir, '__model__'),
  87. os.path.join(self.model_dir, '__params__'))
  88. if use_gpu:
  89. # 设置GPU初始显存(单位M)和Device ID
  90. config.enable_use_gpu(100, gpu_id)
  91. else:
  92. config.disable_gpu()
  93. if use_mkl:
  94. if self.model_name not in ["HRNet", "DeepLabv3p"]:
  95. config.enable_mkldnn()
  96. config.set_cpu_math_library_num_threads(mkl_thread_num)
  97. if use_glog:
  98. config.enable_glog_info()
  99. else:
  100. config.disable_glog_info()
  101. if memory_optimize:
  102. config.enable_memory_optim()
  103. # 开启计算图分析优化,包括OP融合等
  104. config.switch_ir_optim(True)
  105. # 关闭feed和fetch OP使用,使用ZeroCopy接口必须设置此项
  106. config.switch_use_feed_fetch_ops(False)
  107. predictor = fluid.core.create_paddle_predictor(config)
  108. return predictor
  109. def preprocess(self, image, thread_num=1):
  110. """ 对图像做预处理
  111. Args:
  112. image(list|tuple): 数组中的元素可以是图像路径,也可以是解码后的排列格式为(H,W,C)
  113. 且类型为float32且为BGR格式的数组。
  114. """
  115. res = dict()
  116. if self.model_type == "classifier":
  117. im = BaseClassifier._preprocess(
  118. image,
  119. self.transforms,
  120. self.model_type,
  121. self.model_name,
  122. thread_num=thread_num)
  123. res['image'] = im
  124. elif self.model_type == "detector":
  125. if self.model_name in ["PPYOLO", "YOLOv3"]:
  126. im, im_size = PPYOLO._preprocess(
  127. image,
  128. self.transforms,
  129. self.model_type,
  130. self.model_name,
  131. thread_num=thread_num)
  132. res['image'] = im
  133. res['im_size'] = im_size
  134. if self.model_name.count('RCNN') > 0:
  135. im, im_resize_info, im_shape = FasterRCNN._preprocess(
  136. image,
  137. self.transforms,
  138. self.model_type,
  139. self.model_name,
  140. thread_num=thread_num)
  141. res['image'] = im
  142. res['im_info'] = im_resize_info
  143. res['im_shape'] = im_shape
  144. elif self.model_type == "segmenter":
  145. im, im_info = DeepLabv3p._preprocess(
  146. image,
  147. self.transforms,
  148. self.model_type,
  149. self.model_name,
  150. thread_num=thread_num)
  151. res['image'] = im
  152. res['im_info'] = im_info
  153. return res
  154. def postprocess(self,
  155. results,
  156. topk=1,
  157. batch_size=1,
  158. im_shape=None,
  159. im_info=None):
  160. """ 对预测结果做后处理
  161. Args:
  162. results (list): 预测结果
  163. topk (int): 分类预测时前k个最大值
  164. batch_size (int): 预测时图像批量大小
  165. im_shape (list): MaskRCNN的图像输入大小
  166. im_info (list):RCNN系列和分割网络的原图大小
  167. """
  168. def offset_to_lengths(lod):
  169. offset = lod[0]
  170. lengths = [
  171. offset[i + 1] - offset[i] for i in range(len(offset) - 1)
  172. ]
  173. return [lengths]
  174. if self.model_type == "classifier":
  175. true_topk = min(self.num_classes, topk)
  176. preds = BaseClassifier._postprocess([results[0][0]], true_topk,
  177. self.labels)
  178. elif self.model_type == "detector":
  179. res = {'bbox': (results[0][0], offset_to_lengths(results[0][1])), }
  180. res['im_id'] = (np.array(
  181. [[i] for i in range(batch_size)]).astype('int32'), [[]])
  182. if self.model_name in ["PPYOLO", "YOLOv3"]:
  183. preds = PPYOLO._postprocess(res, batch_size, self.num_classes,
  184. self.labels)
  185. elif self.model_name == "FasterRCNN":
  186. preds = FasterRCNN._postprocess(res, batch_size,
  187. self.num_classes, self.labels)
  188. elif self.model_name == "MaskRCNN":
  189. res['mask'] = (results[1][0], offset_to_lengths(results[1][1]))
  190. res['im_shape'] = (im_shape, [])
  191. preds = MaskRCNN._postprocess(
  192. res, batch_size, self.num_classes,
  193. self.mask_head_resolution, self.labels)
  194. elif self.model_type == "segmenter":
  195. res = [results[0][0], results[1][0]]
  196. preds = DeepLabv3p._postprocess(res, im_info)
  197. return preds
  198. def raw_predict(self, inputs):
  199. """ 接受预处理过后的数据进行预测
  200. Args:
  201. inputs(tuple): 预处理过后的数据
  202. """
  203. for k, v in inputs.items():
  204. try:
  205. tensor = self.predictor.get_input_tensor(k)
  206. except:
  207. continue
  208. tensor.copy_from_cpu(v)
  209. self.predictor.zero_copy_run()
  210. output_names = self.predictor.get_output_names()
  211. output_results = list()
  212. for name in output_names:
  213. output_tensor = self.predictor.get_output_tensor(name)
  214. output_tensor_lod = output_tensor.lod()
  215. output_results.append(
  216. [output_tensor.copy_to_cpu(), output_tensor_lod])
  217. return output_results
  218. def predict(self, image, topk=1):
  219. """ 图片预测
  220. Args:
  221. image(str|np.ndarray): 图像路径;或者是解码后的排列格式为(H, W, C)且类型为float32且为BGR格式的数组。
  222. topk(int): 分类预测时使用,表示预测前topk的结果
  223. """
  224. preprocessed_input = self.preprocess([image])
  225. model_pred = self.raw_predict(preprocessed_input)
  226. im_shape = None if 'im_shape' not in preprocessed_input else preprocessed_input[
  227. 'im_shape']
  228. im_info = None if 'im_info' not in preprocessed_input else preprocessed_input[
  229. 'im_info']
  230. results = self.postprocess(
  231. model_pred,
  232. topk=topk,
  233. batch_size=1,
  234. im_shape=im_shape,
  235. im_info=im_info)
  236. return results[0]
  237. def batch_predict(self, image_list, topk=1, thread_num=2):
  238. """ 图片预测
  239. Args:
  240. image_list(list|tuple): 对列表(或元组)中的图像同时进行预测,列表中的元素可以是图像路径
  241. 也可以是解码后的排列格式为(H,W,C)且类型为float32且为BGR格式的数组。
  242. thread_num (int): 并发执行各图像预处理时的线程数。
  243. topk(int): 分类预测时使用,表示预测前topk的结果
  244. """
  245. preprocessed_input = self.preprocess(image_list)
  246. model_pred = self.raw_predict(preprocessed_input)
  247. im_shape = None if 'im_shape' not in preprocessed_input else preprocessed_input[
  248. 'im_shape']
  249. im_info = None if 'im_info' not in preprocessed_input else preprocessed_input[
  250. 'im_info']
  251. results = self.postprocess(
  252. model_pred,
  253. topk=topk,
  254. batch_size=len(image_list),
  255. im_shape=im_shape,
  256. im_info=im_info)
  257. return results