rvm.cc 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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/rvm.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. RobustVideoMatting::RobustVideoMatting(const std::string &model_file,
  21. const std::string &params_file,
  22. const RuntimeOption &custom_option,
  23. const ModelFormat &model_format) {
  24. if (model_format == ModelFormat::ONNX) {
  25. valid_cpu_backends = {Backend::ORT, Backend::OPENVINO};
  26. valid_gpu_backends = {Backend::ORT, Backend::TRT};
  27. } else {
  28. valid_cpu_backends = {Backend::PDINFER, Backend::ORT};
  29. valid_gpu_backends = {Backend::PDINFER, Backend::ORT, Backend::TRT};
  30. }
  31. runtime_option = custom_option;
  32. runtime_option.model_format = model_format;
  33. runtime_option.model_file = model_file;
  34. runtime_option.params_file = params_file;
  35. initialized = Initialize();
  36. }
  37. bool RobustVideoMatting::Initialize() {
  38. // parameters for preprocess
  39. size = {1080, 1920};
  40. video_mode = true;
  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 RobustVideoMatting::Preprocess(
  49. Mat *mat, FDTensor *output,
  50. std::map<std::string, std::array<int, 2>> *im_info) {
  51. // Resize
  52. int resize_w = size[0];
  53. int resize_h = size[1];
  54. if (resize_h != mat->Height() || resize_w != mat->Width()) {
  55. Resize::Run(mat, resize_w, resize_h);
  56. }
  57. // Convert_and_permute(swap_rb=true)
  58. std::vector<float> alpha = {1.0f / 255.0f, 1.0f / 255.0f, 1.0f / 255.0f};
  59. std::vector<float> beta = {0.0f, 0.0f, 0.0f};
  60. ConvertAndPermute::Run(mat, alpha, beta, swap_rb);
  61. // Record output shape of preprocessed image
  62. (*im_info)["output_shape"] = {mat->Height(), mat->Width()};
  63. mat->ShareWithTensor(output);
  64. output->ExpandDim(0); // reshape to n, c, h, w
  65. return true;
  66. }
  67. bool RobustVideoMatting::Postprocess(
  68. std::vector<FDTensor> &infer_result, MattingResult *result,
  69. const std::map<std::string, std::array<int, 2>> &im_info) {
  70. FDASSERT((infer_result.size() == 6),
  71. "The default number of output tensor must be 6 according to "
  72. "RobustVideoMatting.");
  73. FDTensor &fgr = infer_result.at(0); // fgr (1, 3, h, w) 0.~1.
  74. FDTensor &alpha = infer_result.at(1); // alpha (1, 1, h, w) 0.~1.
  75. FDASSERT((fgr.shape[0] == 1), "Only support batch = 1 now.");
  76. FDASSERT((alpha.shape[0] == 1), "Only support batch = 1 now.");
  77. if (fgr.dtype != FDDataType::FP32) {
  78. FDERROR << "Only support post process with float32 data." << std::endl;
  79. return false;
  80. }
  81. if (alpha.dtype != FDDataType::FP32) {
  82. FDERROR << "Only support post process with float32 data." << std::endl;
  83. return false;
  84. }
  85. // update context
  86. if (video_mode) {
  87. for (size_t i = 0; i < 4; ++i) {
  88. FDTensor &rki = infer_result.at(i + 2);
  89. dynamic_inputs_dims_[i] = rki.shape;
  90. dynamic_inputs_datas_[i].resize(rki.Numel());
  91. memcpy(dynamic_inputs_datas_[i].data(), rki.Data(),
  92. rki.Numel() * FDDataTypeSize(rki.dtype));
  93. }
  94. }
  95. auto iter_in = im_info.find("input_shape");
  96. auto iter_out = im_info.find("output_shape");
  97. FDASSERT(iter_out != im_info.end() && iter_in != im_info.end(),
  98. "Cannot find input_shape or output_shape from im_info.");
  99. int out_h = iter_out->second[0];
  100. int out_w = iter_out->second[1];
  101. int in_h = iter_in->second[0];
  102. int in_w = iter_in->second[1];
  103. // for alpha
  104. float *alpha_ptr = static_cast<float *>(alpha.Data());
  105. Mat alpha_resized = Mat::Create(out_h, out_w, 1, FDDataType::FP32,
  106. alpha_ptr); // ref-only, zero copy.
  107. if ((out_h != in_h) || (out_w != in_w)) {
  108. Resize::Run(&alpha_resized, in_w, in_h, -1, -1);
  109. }
  110. // for foreground
  111. float *fgr_ptr = static_cast<float *>(fgr.Data());
  112. Mat fgr_resized = Mat::Create(out_h, out_w, 1, FDDataType::FP32,
  113. fgr_ptr); // ref-only, zero copy.
  114. if ((out_h != in_h) || (out_w != in_w)) {
  115. Resize::Run(&fgr_resized, in_w, in_h, -1, -1);
  116. }
  117. result->contain_foreground = true;
  118. // if contain_foreground == true, shape must set to (h, w, c)
  119. result->shape = {static_cast<int64_t>(in_h), static_cast<int64_t>(in_w), 3};
  120. int numel = in_h * in_w;
  121. int nbytes = numel * sizeof(float);
  122. result->Resize(numel);
  123. memcpy(result->alpha.data(), alpha_resized.Data(), nbytes);
  124. memcpy(result->foreground.data(), fgr_resized.Data(), nbytes);
  125. return true;
  126. }
  127. bool RobustVideoMatting::Predict(cv::Mat *im, MattingResult *result) {
  128. Mat mat(*im);
  129. int inputs_nums = NumInputsOfRuntime();
  130. std::vector<FDTensor> input_tensors(inputs_nums);
  131. std::map<std::string, std::array<int, 2>> im_info;
  132. // Record the shape of image and the shape of preprocessed image
  133. im_info["input_shape"] = {mat.Height(), mat.Width()};
  134. im_info["output_shape"] = {mat.Height(), mat.Width()};
  135. // convert vector to FDTensor
  136. for (size_t i = 1; i < inputs_nums; ++i) {
  137. input_tensors[i].SetExternalData(dynamic_inputs_dims_[i - 1],
  138. FDDataType::FP32,
  139. dynamic_inputs_datas_[i - 1].data());
  140. input_tensors[i].device = Device::CPU;
  141. }
  142. if (!Preprocess(&mat, &input_tensors[0], &im_info)) {
  143. FDERROR << "Failed to preprocess input image." << std::endl;
  144. return false;
  145. }
  146. for (size_t i = 0; i < inputs_nums; ++i) {
  147. input_tensors[i].name = InputInfoOfRuntime(i).name;
  148. }
  149. std::vector<FDTensor> output_tensors;
  150. if (!Infer(input_tensors, &output_tensors)) {
  151. FDERROR << "Failed to inference." << std::endl;
  152. return false;
  153. }
  154. if (!Postprocess(output_tensors, result, im_info)) {
  155. FDERROR << "Failed to post process." << std::endl;
  156. return false;
  157. }
  158. return true;
  159. }
  160. } // namespace matting
  161. } // namespace vision
  162. } // namespace ultra_infer