preprocessor.cc 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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/insightface/preprocessor.h"
  15. namespace ultra_infer {
  16. namespace vision {
  17. namespace faceid {
  18. InsightFaceRecognitionPreprocessor::InsightFaceRecognitionPreprocessor() {
  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. }
  24. bool InsightFaceRecognitionPreprocessor::Preprocess(FDMat *mat,
  25. 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 (!disable_permute_) {
  38. BGR2RGB::Run(mat);
  39. }
  40. if (!disable_normalize_) {
  41. Convert::Run(mat, alpha_, beta_);
  42. HWC2CHW::Run(mat);
  43. Cast::Run(mat, "float");
  44. }
  45. mat->ShareWithTensor(output);
  46. output->ExpandDim(0); // reshape to n, c, h, w
  47. return true;
  48. }
  49. bool InsightFaceRecognitionPreprocessor::Run(std::vector<FDMat> *images,
  50. std::vector<FDTensor> *outputs) {
  51. if (images->empty()) {
  52. FDERROR << "The size of input images should be greater than 0."
  53. << std::endl;
  54. return false;
  55. }
  56. FDASSERT(images->size() == 1, "Only support batch = 1 now.");
  57. outputs->resize(1);
  58. // Concat all the preprocessed data to a batch tensor
  59. std::vector<FDTensor> tensors(images->size());
  60. for (size_t i = 0; i < images->size(); ++i) {
  61. if (!Preprocess(&(*images)[i], &tensors[i])) {
  62. FDERROR << "Failed to preprocess input image." << std::endl;
  63. return false;
  64. }
  65. }
  66. (*outputs)[0] = std::move(tensors[0]);
  67. return true;
  68. }
  69. } // namespace faceid
  70. } // namespace vision
  71. } // namespace ultra_infer