clas_postprocess.cpp 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 <time.h>
  15. #include "model_deploy/ppclas/include/clas_postprocess.h"
  16. namespace PaddleDeploy {
  17. bool ClasPostprocess::Init(const YAML::Node& yaml_config) {
  18. labels_.clear();
  19. for (auto item : yaml_config["labels"]) {
  20. std::string label = item.as<std::string>();
  21. labels_.push_back(label);
  22. }
  23. return true;
  24. }
  25. bool ClasPostprocess::Run(const std::vector<DataBlob>& outputs,
  26. const std::vector<ShapeInfo>& shape_infos,
  27. std::vector<Result>* results, int thread_num) {
  28. if (outputs.size() == 0) {
  29. std::cerr << "empty output on ClasPostprocess" << std::endl;
  30. return false;
  31. }
  32. results->clear();
  33. int batch_size = shape_infos.size();
  34. results->resize(batch_size);
  35. const float* result_data =
  36. reinterpret_cast<const float*>(outputs[0].data.data());
  37. int total_size = std::accumulate(outputs[0].shape.begin(),
  38. outputs[0].shape.end(),
  39. 1, std::multiplies<int>());
  40. int single_size = total_size / batch_size;
  41. #pragma omp parallel for num_threads(thread_num)
  42. for (int i = 0; i < batch_size; ++i) {
  43. (*results)[i].model_type = "clas";
  44. (*results)[i].clas_result = new ClasResult();
  45. const float* start_ptr = result_data + i * single_size;
  46. const float* end_ptr = result_data + (i + 1) * single_size;
  47. const float* ptr = std::max_element(start_ptr, end_ptr);
  48. (*results)[i].clas_result->category_id = std::distance(start_ptr, ptr);
  49. if ((*results)[i].clas_result->category_id >= labels_.size()) {
  50. std::cerr << "Compute category id is greater than labels "
  51. << "in your config file" << std::endl;
  52. std::cerr << "Compute Category ID: "
  53. << (*results)[i].clas_result->category_id
  54. << ", but length of labels is " << labels_.size()
  55. << std::endl;
  56. }
  57. (*results)[i].clas_result->category =
  58. labels_[(*results)[i].clas_result->category_id];
  59. (*results)[i].clas_result->score = *ptr;
  60. }
  61. return true;
  62. }
  63. } // namespace PaddleDeploy