modnet.cc 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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 "ultra_infer/vision/matting/contrib/modnet.h"
  15. #include "ultra_infer/utils/perf.h"
  16. #include "ultra_infer/vision/utils/utils.h"
  17. namespace ultra_infer {
  18. namespace vision {
  19. namespace matting {
  20. MODNet::MODNet(const std::string &model_file, const std::string &params_file,
  21. const RuntimeOption &custom_option,
  22. const ModelFormat &model_format) {
  23. if (model_format == ModelFormat::ONNX) {
  24. valid_cpu_backends = {Backend::ORT};
  25. valid_gpu_backends = {Backend::ORT, Backend::TRT};
  26. } else {
  27. valid_cpu_backends = {Backend::PDINFER, Backend::ORT};
  28. valid_gpu_backends = {Backend::PDINFER, Backend::ORT, Backend::TRT};
  29. }
  30. runtime_option = custom_option;
  31. runtime_option.model_format = model_format;
  32. runtime_option.model_file = model_file;
  33. runtime_option.params_file = params_file;
  34. initialized = Initialize();
  35. }
  36. bool MODNet::Initialize() {
  37. // parameters for preprocess
  38. size = {256, 256};
  39. alpha = {1.f / 127.5f, 1.f / 127.5f, 1.f / 127.5f};
  40. beta = {-1.f, -1.f, -1.f}; // RGB
  41. swap_rb = true;
  42. if (!InitRuntime()) {
  43. FDERROR << "Failed to initialize ultra_infer backend." << std::endl;
  44. return false;
  45. }
  46. return true;
  47. }
  48. bool MODNet::Preprocess(Mat *mat, FDTensor *output,
  49. std::map<std::string, std::array<int, 2>> *im_info) {
  50. // 1. Resize
  51. // 2. BGR2RGB
  52. // 3. Convert(opencv style) or Normalize
  53. // 4. HWC2CHW
  54. int resize_w = size[0];
  55. int resize_h = size[1];
  56. if (resize_h != mat->Height() || resize_w != mat->Width()) {
  57. Resize::Run(mat, resize_w, resize_h);
  58. }
  59. if (swap_rb) {
  60. BGR2RGB::Run(mat);
  61. }
  62. Convert::Run(mat, alpha, beta);
  63. // Record output shape of preprocessed image
  64. (*im_info)["output_shape"] = {mat->Height(), mat->Width()};
  65. HWC2CHW::Run(mat);
  66. Cast::Run(mat, "float");
  67. mat->ShareWithTensor(output);
  68. output->shape.insert(output->shape.begin(), 1); // reshape to n, c, h, w
  69. return true;
  70. }
  71. bool MODNet::Postprocess(
  72. std::vector<FDTensor> &infer_result, MattingResult *result,
  73. const std::map<std::string, std::array<int, 2>> &im_info) {
  74. FDASSERT((infer_result.size() == 1),
  75. "The default number of output tensor must be 1 according to "
  76. "modnet.");
  77. FDTensor &alpha_tensor = infer_result.at(0); // (1, 1, h, w)
  78. FDASSERT((alpha_tensor.shape[0] == 1), "Only support batch =1 now.");
  79. if (alpha_tensor.dtype != FDDataType::FP32) {
  80. FDERROR << "Only support post process with float32 data." << std::endl;
  81. return false;
  82. }
  83. auto iter_ipt = im_info.find("input_shape");
  84. auto iter_out = im_info.find("output_shape");
  85. FDASSERT(iter_out != im_info.end() && iter_ipt != im_info.end(),
  86. "Cannot find input_shape or output_shape from im_info.");
  87. int out_h = iter_out->second[0];
  88. int out_w = iter_out->second[1];
  89. int ipt_h = iter_ipt->second[0];
  90. int ipt_w = iter_ipt->second[1];
  91. float *alpha_ptr = static_cast<float *>(alpha_tensor.Data());
  92. // cv::Mat alpha_zero_copy_ref(out_h, out_w, CV_32FC1, alpha_ptr);
  93. // Mat alpha_resized(alpha_zero_copy_ref); // ref-only, zero copy.
  94. Mat alpha_resized = Mat::Create(out_h, out_w, 1, FDDataType::FP32,
  95. alpha_ptr); // ref-only, zero copy.
  96. if ((out_h != ipt_h) || (out_w != ipt_w)) {
  97. Resize::Run(&alpha_resized, ipt_w, ipt_h, -1, -1);
  98. }
  99. result->Clear();
  100. // note: must be setup shape before Resize
  101. result->contain_foreground = false;
  102. result->shape = {static_cast<int64_t>(ipt_h), static_cast<int64_t>(ipt_w)};
  103. int numel = ipt_h * ipt_w;
  104. int nbytes = numel * sizeof(float);
  105. result->Resize(numel);
  106. std::memcpy(result->alpha.data(), alpha_resized.Data(), nbytes);
  107. return true;
  108. }
  109. bool MODNet::Predict(cv::Mat *im, MattingResult *result) {
  110. Mat mat(*im);
  111. std::vector<FDTensor> input_tensors(1);
  112. std::map<std::string, std::array<int, 2>> im_info;
  113. // Record the shape of image and the shape of preprocessed image
  114. im_info["input_shape"] = {mat.Height(), mat.Width()};
  115. im_info["output_shape"] = {mat.Height(), mat.Width()};
  116. if (!Preprocess(&mat, &input_tensors[0], &im_info)) {
  117. FDERROR << "Failed to preprocess input image." << std::endl;
  118. return false;
  119. }
  120. input_tensors[0].name = InputInfoOfRuntime(0).name;
  121. std::vector<FDTensor> output_tensors;
  122. if (!Infer(input_tensors, &output_tensors)) {
  123. FDERROR << "Failed to inference." << std::endl;
  124. return false;
  125. }
  126. if (!Postprocess(output_tensors, result, im_info)) {
  127. FDERROR << "Failed to post process." << std::endl;
  128. return false;
  129. }
  130. return true;
  131. }
  132. } // namespace matting
  133. } // namespace vision
  134. } // namespace ultra_infer