convert.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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/common/processors/convert.h"
  15. namespace ultra_infer {
  16. namespace vision {
  17. Convert::Convert(const std::vector<float> &alpha,
  18. const std::vector<float> &beta) {
  19. FDASSERT(alpha.size() == beta.size(),
  20. "Convert: requires the size of alpha equal to the size of beta.");
  21. FDASSERT(alpha.size() != 0,
  22. "Convert: requires the size of alpha and beta > 0.");
  23. alpha_.assign(alpha.begin(), alpha.end());
  24. beta_.assign(beta.begin(), beta.end());
  25. }
  26. bool Convert::ImplByOpenCV(Mat *mat) {
  27. cv::Mat *im = mat->GetOpenCVMat();
  28. std::vector<cv::Mat> split_im;
  29. cv::split(*im, split_im);
  30. for (int c = 0; c < im->channels(); c++) {
  31. split_im[c].convertTo(split_im[c], CV_32FC1, alpha_[c], beta_[c]);
  32. }
  33. cv::merge(split_im, *im);
  34. return true;
  35. }
  36. #ifdef ENABLE_FLYCV
  37. bool Convert::ImplByFlyCV(Mat *mat) {
  38. fcv::Mat *im = mat->GetFlyCVMat();
  39. FDASSERT(im->channels() == 3, "Only support 3-channels image in FlyCV.");
  40. std::vector<float> mean(3, 0);
  41. std::vector<float> std(3, 0);
  42. for (size_t i = 0; i < 3; ++i) {
  43. std[i] = 1.0 / alpha_[i];
  44. mean[i] = -1 * beta_[i] * std[i];
  45. }
  46. fcv::Mat new_im;
  47. fcv::normalize_to_submean_to_reorder(*im, mean, std, std::vector<uint32_t>(),
  48. new_im, true);
  49. mat->SetMat(new_im);
  50. return true;
  51. }
  52. #endif
  53. bool Convert::Run(Mat *mat, const std::vector<float> &alpha,
  54. const std::vector<float> &beta, ProcLib lib) {
  55. auto c = Convert(alpha, beta);
  56. return c(mat, lib);
  57. }
  58. } // namespace vision
  59. } // namespace ultra_infer