mask_rcnn_r50_fpn_1x_coco.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. // Copyright (c) 2022 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. #include "core/general-server/op/mask_rcnn_r50_fpn_1x_coco.h"
  15. #include "core/predictor/framework/infer.h"
  16. #include "core/predictor/framework/memory.h"
  17. #include "core/predictor/framework/resource.h"
  18. #include "core/util/include/timer.h"
  19. #include <algorithm>
  20. #include <iostream>
  21. #include <memory>
  22. #include <sstream>
  23. namespace baidu {
  24. namespace paddle_serving {
  25. namespace serving {
  26. using baidu::paddle_serving::Timer;
  27. using baidu::paddle_serving::predictor::InferManager;
  28. using baidu::paddle_serving::predictor::MempoolWrapper;
  29. using baidu::paddle_serving::predictor::PaddleGeneralModelConfig;
  30. using baidu::paddle_serving::predictor::general_model::Request;
  31. using baidu::paddle_serving::predictor::general_model::Response;
  32. using baidu::paddle_serving::predictor::general_model::Tensor;
  33. int mask_rcnn_r50_fpn_1x_coco::inference() {
  34. VLOG(2) << "Going to run inference";
  35. const std::vector<std::string> pre_node_names = pre_names();
  36. if (pre_node_names.size() != 1) {
  37. LOG(ERROR) << "This op(" << op_name()
  38. << ") can only have one predecessor op, but received "
  39. << pre_node_names.size();
  40. return -1;
  41. }
  42. const std::string pre_name = pre_node_names[0];
  43. const GeneralBlob *input_blob = get_depend_argument<GeneralBlob>(pre_name);
  44. if (!input_blob) {
  45. LOG(ERROR) << "input_blob is nullptr,error";
  46. return -1;
  47. }
  48. uint64_t log_id = input_blob->GetLogId();
  49. VLOG(2) << "(logid=" << log_id << ") Get precedent op name: " << pre_name;
  50. GeneralBlob *output_blob = mutable_data<GeneralBlob>();
  51. if (!output_blob) {
  52. LOG(ERROR) << "output_blob is nullptr,error";
  53. return -1;
  54. }
  55. output_blob->SetLogId(log_id);
  56. if (!input_blob) {
  57. LOG(ERROR) << "(logid=" << log_id
  58. << ") Failed mutable depended argument, op:" << pre_name;
  59. return -1;
  60. }
  61. const TensorVector *in = &input_blob->tensor_vector;
  62. TensorVector *out = &output_blob->tensor_vector;
  63. int batch_size = input_blob->_batch_size;
  64. output_blob->_batch_size = batch_size;
  65. VLOG(2) << "(logid=" << log_id << ") infer batch size: " << batch_size;
  66. Timer timeline;
  67. int64_t start = timeline.TimeStampUS();
  68. timeline.Start();
  69. // only support string type
  70. char *total_input_ptr = static_cast<char *>(in->at(0).data.data());
  71. std::string base64str = total_input_ptr;
  72. cv::Mat img = Base2Mat(base64str);
  73. cv::cvtColor(img, img, cv::COLOR_BGR2RGB);
  74. // preprocess
  75. Resize(&img, scale_factor_h, scale_factor_w, im_shape_h, im_shape_w);
  76. Normalize(&img, mean_, scale_, is_scale_);
  77. PadStride(&img, 32);
  78. int input_shape_h = img.rows;
  79. int input_shape_w = img.cols;
  80. std::vector<float> input(1 * 3 * input_shape_h * input_shape_w, 0.0f);
  81. Permute(img, input.data());
  82. // create real_in
  83. TensorVector *real_in = new TensorVector();
  84. if (!real_in) {
  85. LOG(ERROR) << "real_in is nullptr,error";
  86. return -1;
  87. }
  88. int in_num = 0;
  89. size_t databuf_size = 0;
  90. void *databuf_data = NULL;
  91. char *databuf_char = NULL;
  92. // im_shape
  93. std::vector<float> im_shape{static_cast<float>(im_shape_h),
  94. static_cast<float>(im_shape_w)};
  95. databuf_size = 2 * sizeof(float);
  96. databuf_data = MempoolWrapper::instance().malloc(databuf_size);
  97. if (!databuf_data) {
  98. LOG(ERROR) << "Malloc failed, size: " << databuf_size;
  99. return -1;
  100. }
  101. memcpy(databuf_data, im_shape.data(), databuf_size);
  102. databuf_char = reinterpret_cast<char *>(databuf_data);
  103. paddle::PaddleBuf paddleBuf_0(databuf_char, databuf_size);
  104. paddle::PaddleTensor tensor_in_0;
  105. tensor_in_0.name = "im_shape";
  106. tensor_in_0.dtype = paddle::PaddleDType::FLOAT32;
  107. tensor_in_0.shape = {1, 2};
  108. tensor_in_0.lod = in->at(0).lod;
  109. tensor_in_0.data = paddleBuf_0;
  110. real_in->push_back(tensor_in_0);
  111. // image
  112. in_num = 1 * 3 * input_shape_h * input_shape_w;
  113. databuf_size = in_num * sizeof(float);
  114. databuf_data = MempoolWrapper::instance().malloc(databuf_size);
  115. if (!databuf_data) {
  116. LOG(ERROR) << "Malloc failed, size: " << databuf_size;
  117. return -1;
  118. }
  119. memcpy(databuf_data, input.data(), databuf_size);
  120. databuf_char = reinterpret_cast<char *>(databuf_data);
  121. paddle::PaddleBuf paddleBuf_1(databuf_char, databuf_size);
  122. paddle::PaddleTensor tensor_in_1;
  123. tensor_in_1.name = "image";
  124. tensor_in_1.dtype = paddle::PaddleDType::FLOAT32;
  125. tensor_in_1.shape = {1, 3, input_shape_h, input_shape_w};
  126. tensor_in_1.lod = in->at(0).lod;
  127. tensor_in_1.data = paddleBuf_1;
  128. real_in->push_back(tensor_in_1);
  129. // scale_factor
  130. std::vector<float> scale_factor{scale_factor_h, scale_factor_w};
  131. databuf_size = 2 * sizeof(float);
  132. databuf_data = MempoolWrapper::instance().malloc(databuf_size);
  133. if (!databuf_data) {
  134. LOG(ERROR) << "Malloc failed, size: " << databuf_size;
  135. return -1;
  136. }
  137. memcpy(databuf_data, scale_factor.data(), databuf_size);
  138. databuf_char = reinterpret_cast<char *>(databuf_data);
  139. paddle::PaddleBuf paddleBuf_2(databuf_char, databuf_size);
  140. paddle::PaddleTensor tensor_in_2;
  141. tensor_in_2.name = "scale_factor";
  142. tensor_in_2.dtype = paddle::PaddleDType::FLOAT32;
  143. tensor_in_2.shape = {1, 2};
  144. tensor_in_2.lod = in->at(0).lod;
  145. tensor_in_2.data = paddleBuf_2;
  146. real_in->push_back(tensor_in_2);
  147. if (InferManager::instance().infer(engine_name().c_str(), real_in, out,
  148. batch_size)) {
  149. LOG(ERROR) << "(logid=" << log_id
  150. << ") Failed do infer in fluid model: " << engine_name().c_str();
  151. return -1;
  152. }
  153. int64_t end = timeline.TimeStampUS();
  154. CopyBlobInfo(input_blob, output_blob);
  155. AddBlobInfo(output_blob, start);
  156. AddBlobInfo(output_blob, end);
  157. return 0;
  158. }
  159. void mask_rcnn_r50_fpn_1x_coco::Resize(cv::Mat *img, float &scale_factor_h,
  160. float &scale_factor_w, int &im_shape_h,
  161. int &im_shape_w) {
  162. // keep_ratio
  163. int im_size_max = std::max(img->rows, img->cols);
  164. int im_size_min = std::min(img->rows, img->cols);
  165. int target_size_max = std::max(im_shape_h, im_shape_w);
  166. int target_size_min = std::min(im_shape_h, im_shape_w);
  167. float scale_min =
  168. static_cast<float>(target_size_min) / static_cast<float>(im_size_min);
  169. float scale_max =
  170. static_cast<float>(target_size_max) / static_cast<float>(im_size_max);
  171. float scale_ratio = std::min(scale_min, scale_max);
  172. // scale_factor
  173. scale_factor_h = scale_ratio;
  174. scale_factor_w = scale_ratio;
  175. // Resize
  176. cv::resize(*img, *img, cv::Size(), scale_ratio, scale_ratio, 2);
  177. im_shape_h = img->rows;
  178. im_shape_w = img->cols;
  179. }
  180. void mask_rcnn_r50_fpn_1x_coco::Normalize(cv::Mat *img,
  181. const std::vector<float> &mean,
  182. const std::vector<float> &scale,
  183. const bool is_scale) {
  184. // Normalize
  185. double e = 1.0;
  186. if (is_scale) {
  187. e /= 255.0;
  188. }
  189. (*img).convertTo(*img, CV_32FC3, e);
  190. for (int h = 0; h < img->rows; h++) {
  191. for (int w = 0; w < img->cols; w++) {
  192. img->at<cv::Vec3f>(h, w)[0] =
  193. (img->at<cv::Vec3f>(h, w)[0] - mean[0]) / scale[0];
  194. img->at<cv::Vec3f>(h, w)[1] =
  195. (img->at<cv::Vec3f>(h, w)[1] - mean[1]) / scale[1];
  196. img->at<cv::Vec3f>(h, w)[2] =
  197. (img->at<cv::Vec3f>(h, w)[2] - mean[2]) / scale[2];
  198. }
  199. }
  200. }
  201. void mask_rcnn_r50_fpn_1x_coco::PadStride(cv::Mat *img, int stride_) {
  202. // PadStride
  203. if (stride_ <= 0)
  204. return;
  205. int rh = img->rows;
  206. int rw = img->cols;
  207. int nh = (rh / stride_) * stride_ + (rh % stride_ != 0) * stride_;
  208. int nw = (rw / stride_) * stride_ + (rw % stride_ != 0) * stride_;
  209. cv::copyMakeBorder(*img, *img, 0, nh - rh, 0, nw - rw, cv::BORDER_CONSTANT,
  210. cv::Scalar(0));
  211. }
  212. void mask_rcnn_r50_fpn_1x_coco::Permute(const cv::Mat &img, float *data) {
  213. // Permute
  214. int rh = img.rows;
  215. int rw = img.cols;
  216. int rc = img.channels();
  217. for (int i = 0; i < rc; ++i) {
  218. cv::extractChannel(img, cv::Mat(rh, rw, CV_32FC1, data + i * rh * rw), i);
  219. }
  220. }
  221. cv::Mat mask_rcnn_r50_fpn_1x_coco::Base2Mat(std::string &base64_data) {
  222. cv::Mat img;
  223. std::string s_mat;
  224. s_mat = base64Decode(base64_data.data(), base64_data.size());
  225. std::vector<char> base64_img(s_mat.begin(), s_mat.end());
  226. img = cv::imdecode(base64_img, cv::IMREAD_COLOR); // CV_LOAD_IMAGE_COLOR
  227. return img;
  228. }
  229. std::string mask_rcnn_r50_fpn_1x_coco::base64Decode(const char *Data,
  230. int DataByte) {
  231. const char DecodeTable[] = {
  232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  234. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  235. 62, // '+'
  236. 0, 0, 0,
  237. 63, // '/'
  238. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // '0'-'9'
  239. 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  240. 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'A'-'Z'
  241. 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
  242. 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // 'a'-'z'
  243. };
  244. std::string strDecode;
  245. int nValue;
  246. int i = 0;
  247. while (i < DataByte) {
  248. if (*Data != '\r' && *Data != '\n') {
  249. nValue = DecodeTable[*Data++] << 18;
  250. nValue += DecodeTable[*Data++] << 12;
  251. strDecode += (nValue & 0x00FF0000) >> 16;
  252. if (*Data != '=') {
  253. nValue += DecodeTable[*Data++] << 6;
  254. strDecode += (nValue & 0x0000FF00) >> 8;
  255. if (*Data != '=') {
  256. nValue += DecodeTable[*Data++];
  257. strDecode += nValue & 0x000000FF;
  258. }
  259. }
  260. i += 4;
  261. } else // 回车换行,跳过
  262. {
  263. Data++;
  264. i++;
  265. }
  266. }
  267. return strDecode;
  268. }
  269. DEFINE_OP(mask_rcnn_r50_fpn_1x_coco);
  270. } // namespace serving
  271. } // namespace paddle_serving
  272. } // namespace baidu