preprocessor.cc 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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/faceid/contrib/adaface/preprocessor.h"
  15. namespace ultra_infer {
  16. namespace vision {
  17. namespace faceid {
  18. AdaFacePreprocessor::AdaFacePreprocessor() {
  19. // parameters for preprocess
  20. size_ = {112, 112};
  21. alpha_ = {1.f / 127.5f, 1.f / 127.5f, 1.f / 127.5f};
  22. beta_ = {-1.f, -1.f, -1.f}; // RGB
  23. permute_ = true;
  24. }
  25. bool AdaFacePreprocessor::Preprocess(FDMat *mat, FDTensor *output) {
  26. // face recognition model's preprocess steps in insightface
  27. // reference: insightface/recognition/arcface_torch/inference.py
  28. // 1. Resize
  29. // 2. BGR2RGB
  30. // 3. Convert(opencv style) or Normalize
  31. // 4. HWC2CHW
  32. int resize_w = size_[0];
  33. int resize_h = size_[1];
  34. if (resize_h != mat->Height() || resize_w != mat->Width()) {
  35. Resize::Run(mat, resize_w, resize_h);
  36. }
  37. if (permute_) {
  38. BGR2RGB::Run(mat);
  39. }
  40. Convert::Run(mat, alpha_, beta_);
  41. HWC2CHW::Run(mat);
  42. Cast::Run(mat, "float");
  43. mat->ShareWithTensor(output);
  44. output->ExpandDim(0); // reshape to n, c, h, w
  45. return true;
  46. }
  47. bool AdaFacePreprocessor::Run(std::vector<FDMat> *images,
  48. std::vector<FDTensor> *outputs) {
  49. if (images->empty()) {
  50. FDERROR << "The size of input images should be greater than 0."
  51. << std::endl;
  52. return false;
  53. }
  54. FDASSERT(images->size() == 1, "Only support batch = 1 now.");
  55. outputs->resize(1);
  56. // Concat all the preprocessed data to a batch tensor
  57. std::vector<FDTensor> tensors(images->size());
  58. for (size_t i = 0; i < images->size(); ++i) {
  59. if (!Preprocess(&(*images)[i], &tensors[i])) {
  60. FDERROR << "Failed to preprocess input image." << std::endl;
  61. return false;
  62. }
  63. }
  64. (*outputs)[0] = std::move(tensors[0]);
  65. return true;
  66. }
  67. } // namespace faceid
  68. } // namespace vision
  69. } // namespace ultra_infer