classifier.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. model.predict(im, &result);
  55. std::cout << "Predict label: " << result.category
  56. << ", label_id:" << result.category_id
  57. << ", score: " << result.score << std::endl;
  58. }
  59. } else {
  60. PaddleX::ClsResult result;
  61. cv::Mat im = cv::imread(FLAGS_image, 1);
  62. model.predict(im, &result);
  63. std::cout << "Predict label: " << result.category
  64. << ", label_id:" << result.category_id
  65. << ", score: " << result.score << std::endl;
  66. }
  67. return 0;
  68. }