You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

squeezenet.cpp 2.3 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright 2017 Tencent
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. #include "net.h"
  4. #include <algorithm>
  5. #if defined(USE_NCNN_SIMPLEOCV)
  6. #include "simpleocv.h"
  7. #else
  8. #include <opencv2/core/core.hpp>
  9. #include <opencv2/highgui/highgui.hpp>
  10. #endif
  11. #include <stdio.h>
  12. #include <vector>
  13. static int detect_squeezenet(const cv::Mat& bgr, std::vector<float>& cls_scores)
  14. {
  15. ncnn::Net squeezenet;
  16. squeezenet.opt.use_vulkan_compute = true;
  17. // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models
  18. if (squeezenet.load_param("squeezenet_v1.1.param"))
  19. exit(-1);
  20. if (squeezenet.load_model("squeezenet_v1.1.bin"))
  21. exit(-1);
  22. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR, bgr.cols, bgr.rows, 227, 227);
  23. const float mean_vals[3] = {104.f, 117.f, 123.f};
  24. in.substract_mean_normalize(mean_vals, 0);
  25. ncnn::Extractor ex = squeezenet.create_extractor();
  26. ex.input("data", in);
  27. ncnn::Mat out;
  28. ex.extract("prob", out);
  29. cls_scores.resize(out.w);
  30. for (int j = 0; j < out.w; j++)
  31. {
  32. cls_scores[j] = out[j];
  33. }
  34. return 0;
  35. }
  36. static int print_topk(const std::vector<float>& cls_scores, int topk)
  37. {
  38. // partial sort topk with index
  39. int size = cls_scores.size();
  40. std::vector<std::pair<float, int> > vec;
  41. vec.resize(size);
  42. for (int i = 0; i < size; i++)
  43. {
  44. vec[i] = std::make_pair(cls_scores[i], i);
  45. }
  46. std::partial_sort(vec.begin(), vec.begin() + topk, vec.end(),
  47. std::greater<std::pair<float, int> >());
  48. // print topk and score
  49. for (int i = 0; i < topk; i++)
  50. {
  51. float score = vec[i].first;
  52. int index = vec[i].second;
  53. fprintf(stderr, "%d = %f\n", index, score);
  54. }
  55. return 0;
  56. }
  57. int main(int argc, char** argv)
  58. {
  59. if (argc != 2)
  60. {
  61. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  62. return -1;
  63. }
  64. const char* imagepath = argv[1];
  65. cv::Mat m = cv::imread(imagepath, 1);
  66. if (m.empty())
  67. {
  68. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  69. return -1;
  70. }
  71. std::vector<float> cls_scores;
  72. detect_squeezenet(m, cls_scores);
  73. print_topk(cls_scores, 3);
  74. return 0;
  75. }