postprocessor.cc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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/classification/contrib/yolov5cls/postprocessor.h"
  15. #include "ultra_infer/vision/utils/utils.h"
  16. namespace ultra_infer {
  17. namespace vision {
  18. namespace classification {
  19. YOLOv5ClsPostprocessor::YOLOv5ClsPostprocessor() { topk_ = 1; }
  20. bool YOLOv5ClsPostprocessor::Run(
  21. const std::vector<FDTensor> &tensors, std::vector<ClassifyResult> *results,
  22. const std::vector<std::map<std::string, std::array<float, 2>>> &ims_info) {
  23. int batch = tensors[0].shape[0];
  24. FDTensor infer_result = tensors[0];
  25. FDTensor infer_result_softmax;
  26. function::Softmax(infer_result, &infer_result_softmax, 1);
  27. results->resize(batch);
  28. for (size_t bs = 0; bs < batch; ++bs) {
  29. (*results)[bs].Clear();
  30. // output (1,1000) score classnum 1000
  31. int num_classes = infer_result_softmax.shape[1];
  32. const float *infer_result_buffer =
  33. reinterpret_cast<const float *>(infer_result_softmax.Data()) +
  34. bs * infer_result_softmax.shape[1];
  35. topk_ = std::min(num_classes, topk_);
  36. (*results)[bs].label_ids =
  37. utils::TopKIndices(infer_result_buffer, num_classes, topk_);
  38. (*results)[bs].scores.resize(topk_);
  39. for (int i = 0; i < topk_; ++i) {
  40. (*results)[bs].scores[i] =
  41. *(infer_result_buffer + (*results)[bs].label_ids[i]);
  42. }
  43. if ((*results)[bs].label_ids.size() == 0) {
  44. return true;
  45. }
  46. }
  47. return true;
  48. }
  49. } // namespace classification
  50. } // namespace vision
  51. } // namespace ultra_infer