general_detection_op.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. #include "core/general-server/op/general_detection_op.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. /*
  24. #include "opencv2/imgcodecs/legacy/constants_c.h"
  25. #include "opencv2/imgproc/types_c.h"
  26. */
  27. namespace baidu {
  28. namespace paddle_serving {
  29. namespace serving {
  30. using baidu::paddle_serving::Timer;
  31. using baidu::paddle_serving::predictor::MempoolWrapper;
  32. using baidu::paddle_serving::predictor::general_model::Tensor;
  33. using baidu::paddle_serving::predictor::general_model::Response;
  34. using baidu::paddle_serving::predictor::general_model::Request;
  35. using baidu::paddle_serving::predictor::InferManager;
  36. using baidu::paddle_serving::predictor::PaddleGeneralModelConfig;
  37. int GeneralDetectionOp::inference() {
  38. VLOG(2) << "Going to run inference";
  39. const std::vector<std::string> pre_node_names = pre_names();
  40. if (pre_node_names.size() != 1) {
  41. LOG(ERROR) << "This op(" << op_name()
  42. << ") can only have one predecessor op, but received "
  43. << pre_node_names.size();
  44. return -1;
  45. }
  46. const std::string pre_name = pre_node_names[0];
  47. const GeneralBlob *input_blob = get_depend_argument<GeneralBlob>(pre_name);
  48. if (!input_blob) {
  49. LOG(ERROR) << "input_blob is nullptr,error";
  50. return -1;
  51. }
  52. uint64_t log_id = input_blob->GetLogId();
  53. VLOG(2) << "(logid=" << log_id << ") Get precedent op name: " << pre_name;
  54. GeneralBlob *output_blob = mutable_data<GeneralBlob>();
  55. if (!output_blob) {
  56. LOG(ERROR) << "output_blob is nullptr,error";
  57. return -1;
  58. }
  59. output_blob->SetLogId(log_id);
  60. if (!input_blob) {
  61. LOG(ERROR) << "(logid=" << log_id
  62. << ") Failed mutable depended argument, op:" << pre_name;
  63. return -1;
  64. }
  65. const TensorVector *in = &input_blob->tensor_vector;
  66. TensorVector *out = &output_blob->tensor_vector;
  67. int batch_size = input_blob->_batch_size;
  68. VLOG(2) << "(logid=" << log_id << ") input batch size: " << batch_size;
  69. output_blob->_batch_size = batch_size;
  70. std::vector<int> input_shape;
  71. int in_num = 0;
  72. void *databuf_data = NULL;
  73. char *databuf_char = NULL;
  74. size_t databuf_size = 0;
  75. // now only support single string
  76. char *total_input_ptr = static_cast<char *>(in->at(0).data.data());
  77. std::string base64str = total_input_ptr;
  78. float ratio_h{};
  79. float ratio_w{};
  80. cv::Mat img = Base2Mat(base64str);
  81. cv::Mat srcimg;
  82. cv::Mat resize_img;
  83. cv::Mat resize_img_rec;
  84. cv::Mat crop_img;
  85. img.copyTo(srcimg);
  86. this->resize_op_.Run(img, resize_img, this->max_side_len_, ratio_h, ratio_w,
  87. this->use_tensorrt_);
  88. this->normalize_op_.Run(&resize_img, this->mean_det, this->scale_det,
  89. this->is_scale_);
  90. std::vector<float> input(1 * 3 * resize_img.rows * resize_img.cols, 0.0f);
  91. this->permute_op_.Run(&resize_img, input.data());
  92. TensorVector *real_in = new TensorVector();
  93. if (!real_in) {
  94. LOG(ERROR) << "real_in is nullptr,error";
  95. return -1;
  96. }
  97. for (int i = 0; i < in->size(); ++i) {
  98. input_shape = {1, 3, resize_img.rows, resize_img.cols};
  99. in_num = std::accumulate(input_shape.begin(), input_shape.end(), 1,
  100. std::multiplies<int>());
  101. databuf_size = in_num * sizeof(float);
  102. databuf_data = MempoolWrapper::instance().malloc(databuf_size);
  103. if (!databuf_data) {
  104. LOG(ERROR) << "Malloc failed, size: " << databuf_size;
  105. return -1;
  106. }
  107. memcpy(databuf_data, input.data(), databuf_size);
  108. databuf_char = reinterpret_cast<char *>(databuf_data);
  109. paddle::PaddleBuf paddleBuf(databuf_char, databuf_size);
  110. paddle::PaddleTensor tensor_in;
  111. tensor_in.name = in->at(i).name;
  112. tensor_in.dtype = paddle::PaddleDType::FLOAT32;
  113. tensor_in.shape = {1, 3, resize_img.rows, resize_img.cols};
  114. tensor_in.lod = in->at(i).lod;
  115. tensor_in.data = paddleBuf;
  116. real_in->push_back(tensor_in);
  117. }
  118. Timer timeline;
  119. int64_t start = timeline.TimeStampUS();
  120. timeline.Start();
  121. if (InferManager::instance().infer(engine_name().c_str(), real_in, out,
  122. batch_size)) {
  123. LOG(ERROR) << "(logid=" << log_id
  124. << ") Failed do infer in fluid model: " << engine_name().c_str();
  125. return -1;
  126. }
  127. delete real_in;
  128. std::vector<int> output_shape;
  129. int out_num = 0;
  130. void *databuf_data_out = NULL;
  131. char *databuf_char_out = NULL;
  132. size_t databuf_size_out = 0;
  133. // this is special add for PaddleOCR postprecess
  134. int infer_outnum = out->size();
  135. for (int k = 0; k < infer_outnum; ++k) {
  136. int n2 = out->at(k).shape[2];
  137. int n3 = out->at(k).shape[3];
  138. int n = n2 * n3;
  139. float *out_data = static_cast<float *>(out->at(k).data.data());
  140. std::vector<float> pred(n, 0.0);
  141. std::vector<unsigned char> cbuf(n, ' ');
  142. for (int i = 0; i < n; i++) {
  143. pred[i] = float(out_data[i]);
  144. cbuf[i] = (unsigned char)((out_data[i]) * 255);
  145. }
  146. cv::Mat cbuf_map(n2, n3, CV_8UC1, (unsigned char *)cbuf.data());
  147. cv::Mat pred_map(n2, n3, CV_32F, (float *)pred.data());
  148. const double threshold = this->det_db_thresh_ * 255;
  149. const double maxvalue = 255;
  150. cv::Mat bit_map;
  151. cv::threshold(cbuf_map, bit_map, threshold, maxvalue, cv::THRESH_BINARY);
  152. cv::Mat dilation_map;
  153. cv::Mat dila_ele =
  154. cv::getStructuringElement(cv::MORPH_RECT, cv::Size(2, 2));
  155. cv::dilate(bit_map, dilation_map, dila_ele);
  156. boxes = post_processor_.BoxesFromBitmap(pred_map, dilation_map,
  157. this->det_db_box_thresh_,
  158. this->det_db_unclip_ratio_);
  159. boxes = post_processor_.FilterTagDetRes(boxes, ratio_h, ratio_w, srcimg);
  160. float max_wh_ratio = 0.0f;
  161. std::vector<cv::Mat> crop_imgs;
  162. std::vector<cv::Mat> resize_imgs;
  163. int max_resize_w = 0;
  164. int max_resize_h = 0;
  165. int box_num = boxes.size();
  166. std::vector<std::vector<float>> output_rec;
  167. for (int i = 0; i < box_num; ++i) {
  168. cv::Mat line_img = GetRotateCropImage(img, boxes[i]);
  169. float wh_ratio = float(line_img.cols) / float(line_img.rows);
  170. max_wh_ratio = max_wh_ratio > wh_ratio ? max_wh_ratio : wh_ratio;
  171. crop_imgs.push_back(line_img);
  172. }
  173. for (int i = 0; i < box_num; ++i) {
  174. cv::Mat resize_img;
  175. crop_img = crop_imgs[i];
  176. this->resize_op_rec.Run(crop_img, resize_img, max_wh_ratio,
  177. this->use_tensorrt_);
  178. this->normalize_op_.Run(&resize_img, this->mean_rec, this->scale_rec,
  179. this->is_scale_);
  180. max_resize_w = std::max(max_resize_w, resize_img.cols);
  181. max_resize_h = std::max(max_resize_h, resize_img.rows);
  182. resize_imgs.push_back(resize_img);
  183. }
  184. int buf_size = 3 * max_resize_h * max_resize_w;
  185. output_rec = std::vector<std::vector<float>>(
  186. box_num, std::vector<float>(buf_size, 0.0f));
  187. for (int i = 0; i < box_num; ++i) {
  188. resize_img_rec = resize_imgs[i];
  189. this->permute_op_.Run(&resize_img_rec, output_rec[i].data());
  190. }
  191. // Inference.
  192. output_shape = {box_num, 3, max_resize_h, max_resize_w};
  193. out_num = std::accumulate(output_shape.begin(), output_shape.end(), 1,
  194. std::multiplies<int>());
  195. databuf_size_out = out_num * sizeof(float);
  196. databuf_data_out = MempoolWrapper::instance().malloc(databuf_size_out);
  197. if (!databuf_data_out) {
  198. LOG(ERROR) << "Malloc failed, size: " << databuf_size_out;
  199. return -1;
  200. }
  201. int offset = buf_size * sizeof(float);
  202. for (int i = 0; i < box_num; ++i) {
  203. memcpy(databuf_data_out + i * offset, output_rec[i].data(), offset);
  204. }
  205. databuf_char_out = reinterpret_cast<char *>(databuf_data_out);
  206. paddle::PaddleBuf paddleBuf(databuf_char_out, databuf_size_out);
  207. paddle::PaddleTensor tensor_out;
  208. tensor_out.name = "x";
  209. tensor_out.dtype = paddle::PaddleDType::FLOAT32;
  210. tensor_out.shape = output_shape;
  211. tensor_out.data = paddleBuf;
  212. out->push_back(tensor_out);
  213. }
  214. out->erase(out->begin(), out->begin() + infer_outnum);
  215. int64_t end = timeline.TimeStampUS();
  216. CopyBlobInfo(input_blob, output_blob);
  217. AddBlobInfo(output_blob, start);
  218. AddBlobInfo(output_blob, end);
  219. return 0;
  220. }
  221. cv::Mat GeneralDetectionOp::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 GeneralDetectionOp::base64Decode(const char *Data, int DataByte) {
  230. const char DecodeTable[] = {
  231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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,
  234. 62, // '+'
  235. 0, 0, 0,
  236. 63, // '/'
  237. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // '0'-'9'
  238. 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
  239. 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'A'-'Z'
  240. 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
  241. 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // 'a'-'z'
  242. };
  243. std::string strDecode;
  244. int nValue;
  245. int i = 0;
  246. while (i < DataByte) {
  247. if (*Data != '\r' && *Data != '\n') {
  248. nValue = DecodeTable[*Data++] << 18;
  249. nValue += DecodeTable[*Data++] << 12;
  250. strDecode += (nValue & 0x00FF0000) >> 16;
  251. if (*Data != '=') {
  252. nValue += DecodeTable[*Data++] << 6;
  253. strDecode += (nValue & 0x0000FF00) >> 8;
  254. if (*Data != '=') {
  255. nValue += DecodeTable[*Data++];
  256. strDecode += nValue & 0x000000FF;
  257. }
  258. }
  259. i += 4;
  260. } else // 回车换行,跳过
  261. {
  262. Data++;
  263. i++;
  264. }
  265. }
  266. return strDecode;
  267. }
  268. cv::Mat
  269. GeneralDetectionOp::GetRotateCropImage(const cv::Mat &srcimage,
  270. std::vector<std::vector<int>> box) {
  271. cv::Mat image;
  272. srcimage.copyTo(image);
  273. std::vector<std::vector<int>> points = box;
  274. int x_collect[4] = {box[0][0], box[1][0], box[2][0], box[3][0]};
  275. int y_collect[4] = {box[0][1], box[1][1], box[2][1], box[3][1]};
  276. int left = int(*std::min_element(x_collect, x_collect + 4));
  277. int right = int(*std::max_element(x_collect, x_collect + 4));
  278. int top = int(*std::min_element(y_collect, y_collect + 4));
  279. int bottom = int(*std::max_element(y_collect, y_collect + 4));
  280. cv::Mat img_crop;
  281. image(cv::Rect(left, top, right - left, bottom - top)).copyTo(img_crop);
  282. for (int i = 0; i < points.size(); i++) {
  283. points[i][0] -= left;
  284. points[i][1] -= top;
  285. }
  286. int img_crop_width = int(sqrt(pow(points[0][0] - points[1][0], 2) +
  287. pow(points[0][1] - points[1][1], 2)));
  288. int img_crop_height = int(sqrt(pow(points[0][0] - points[3][0], 2) +
  289. pow(points[0][1] - points[3][1], 2)));
  290. cv::Point2f pts_std[4];
  291. pts_std[0] = cv::Point2f(0., 0.);
  292. pts_std[1] = cv::Point2f(img_crop_width, 0.);
  293. pts_std[2] = cv::Point2f(img_crop_width, img_crop_height);
  294. pts_std[3] = cv::Point2f(0.f, img_crop_height);
  295. cv::Point2f pointsf[4];
  296. pointsf[0] = cv::Point2f(points[0][0], points[0][1]);
  297. pointsf[1] = cv::Point2f(points[1][0], points[1][1]);
  298. pointsf[2] = cv::Point2f(points[2][0], points[2][1]);
  299. pointsf[3] = cv::Point2f(points[3][0], points[3][1]);
  300. cv::Mat M = cv::getPerspectiveTransform(pointsf, pts_std);
  301. cv::Mat dst_img;
  302. cv::warpPerspective(img_crop, dst_img, M,
  303. cv::Size(img_crop_width, img_crop_height),
  304. cv::BORDER_REPLICATE);
  305. if (float(dst_img.rows) >= float(dst_img.cols) * 1.5) {
  306. cv::Mat srcCopy = cv::Mat(dst_img.rows, dst_img.cols, dst_img.depth());
  307. cv::transpose(dst_img, srcCopy);
  308. cv::flip(srcCopy, srcCopy, 0);
  309. return srcCopy;
  310. } else {
  311. return dst_img;
  312. }
  313. }
  314. DEFINE_OP(GeneralDetectionOp);
  315. } // namespace serving
  316. } // namespace paddle_serving
  317. } // namespace baidu