classifier.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright (c) 2020 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 <gflags/gflags.h>
  15. #include <fstream>
  16. #include <iostream>
  17. #include <string>
  18. #include <vector>
  19. #include "include/paddlex/paddlex.h"
  20. DEFINE_string(model_dir, "", "Path of inference model");
  21. DEFINE_string(cfg_file, "", "Path of PaddelX model yml file");
  22. DEFINE_string(device, "CPU", "Device name");
  23. DEFINE_string(image, "", "Path of test image file");
  24. DEFINE_string(image_list, "", "Path of test image list file");
  25. int main(int argc, char** argv) {
  26. // Parsing command-line
  27. google::ParseCommandLineFlags(&argc, &argv, true);
  28. if (FLAGS_model_dir == "") {
  29. std::cerr << "--model_dir need to be defined" << std::endl;
  30. return -1;
  31. }
  32. if (FLAGS_cfg_file == "") {
  33. std::cerr << "--cfg_file need to be defined" << std::endl;
  34. return -1;
  35. }
  36. if (FLAGS_image == "" & FLAGS_image_list == "") {
  37. std::cerr << "--image or --image_list need to be defined" << std::endl;
  38. return -1;
  39. }
  40. // load model
  41. PaddleX::Model model;
  42. model.Init(FLAGS_model_dir, FLAGS_cfg_file, FLAGS_device);
  43. // predict
  44. if (FLAGS_image_list != "") {
  45. std::ifstream inf(FLAGS_image_list);
  46. if (!inf) {
  47. std::cerr << "Fail to open file " << FLAGS_image_list << std::endl;
  48. return -1;
  49. }
  50. std::string image_path;
  51. while (getline(inf, image_path)) {
  52. PaddleX::ClsResult result;
  53. cv::Mat im = cv::imread(image_path, 1);
  54. if (!model.predict(im, &result)) {
  55. return -1;
  56. }
  57. std::cout << "Predict label: " << result.category
  58. << ", label_id:" << result.category_id
  59. << ", score: " << result.score << std::endl;
  60. }
  61. } else {
  62. PaddleX::ClsResult result;
  63. cv::Mat im = cv::imread(FLAGS_image, 1);
  64. if (!model.predict(im, &result)) {
  65. return -1;
  66. }
  67. std::cout << "Predict label: " << result.category
  68. << ", label_id:" << result.category_id
  69. << ", score: " << result.score << std::endl;
  70. }
  71. return 0;
  72. }