clas_preprocess.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (c) 2021 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 "model_deploy/ppclas/include/clas_preprocess.h"
  15. namespace PaddleDeploy {
  16. bool ClasPreprocess::Init(const YAML::Node& yaml_config) {
  17. if (!BuildTransform(yaml_config)) {
  18. return false;
  19. }
  20. if (yaml_config["input_tensor_name"].IsDefined()) {
  21. input_name_ = yaml_config["input_tensor_name"].as<std::string>();
  22. } else {
  23. input_name_ = "inputs";
  24. }
  25. return true;
  26. }
  27. bool ClasPreprocess::PrepareInputs(const std::vector<ShapeInfo>& shape_infos,
  28. std::vector<cv::Mat>* imgs,
  29. std::vector<DataBlob>* inputs,
  30. int thread_num) {
  31. inputs->clear();
  32. if (!PreprocessImages(shape_infos, imgs, thread_num = thread_num)) {
  33. std::cerr << "Error happend while execute function "
  34. << "ClasPreprocess::Run" << std::endl;
  35. return false;
  36. }
  37. DataBlob im(input_name_);
  38. int batch = imgs->size();
  39. int w = shape_infos[0].shapes.back()[0];
  40. int h = shape_infos[0].shapes.back()[1];
  41. im.Resize({batch, 3, h, w}, FLOAT32);
  42. int sample_shape = 3 * h * w;
  43. #pragma omp parallel for num_threads(thread_num)
  44. for (auto i = 0; i < batch; ++i) {
  45. memcpy(im.data.data() + i * sample_shape * sizeof(float), (*imgs)[i].data,
  46. sample_shape * sizeof(float));
  47. }
  48. inputs->clear();
  49. inputs->push_back(std::move(im));
  50. return true;
  51. }
  52. bool ClasPreprocess::Run(std::vector<cv::Mat>* imgs,
  53. std::vector<DataBlob>* inputs,
  54. std::vector<ShapeInfo>* shape_infos, int thread_num) {
  55. if (!ShapeInfer(*imgs, shape_infos, thread_num)) {
  56. std::cerr << "ShapeInfer failed while call"
  57. << " ClasPreprocess::Run" << std::endl;
  58. return false;
  59. }
  60. if (!PrepareInputs(*shape_infos, imgs, inputs, thread_num)) {
  61. std::cerr << "PrepareInputs failed while call "
  62. << "ClasPreprocess::PrepareInputs" << std::endl;
  63. return false;
  64. }
  65. return true;
  66. }
  67. } // namespace PaddleDeploy