image-classification.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include <fstream>
  2. #include <sstream>
  3. #include <iostream>
  4. #include <string>
  5. #include <vector>
  6. #include <opencv2/dnn.hpp>
  7. #include <opencv2/imgproc.hpp>
  8. #include <opencv2/highgui.hpp>
  9. #include <opencv2/dnn.hpp>
  10. using namespace std;
  11. using namespace cv;
  12. using namespace cv::dnn;
  13. int main() {
  14. string caffe_root = "/home/ubuntu/caffe/";
  15. Mat image = imread("/home/ubuntu/caffe/examples/images/cat.jpg");
  16. string labels_file = "/home/ubuntu/caffe/data/ilsvrc12/synset_words.txt";
  17. string prototxt = "/home/ubuntu/caffe/models/bvlc_reference_caffenet/deploy.prototxt";
  18. string model = "/home/ubuntu/caffe/models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel";
  19. vector<string> classes;
  20. // load the labels file
  21. std::ifstream ifs(labels_file.c_str());
  22. if (!ifs.is_open())
  23. {
  24. CV_Error(Error::StsError, "File " + labels_file + " not found");
  25. string line;
  26. while (std::getline(ifs, line))
  27. {
  28. classes.push_back(line);
  29. }
  30. }
  31. Mat blob = dnn::blobFromImage(image, 1, Size(224, 224), Scalar(104,117,123));
  32. cout << "[INFO] loading model..." << endl;
  33. dnn::Net net = readNetFromCaffe(prototxt, model);
  34. net.setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
  35. net.setPreferableTarget(DNN_TARGET_CPU);
  36. // set the blob as input to the network and perform a forward-pass to
  37. // obtain our output classification
  38. net.setInput(blob);
  39. Mat preds = net.forward();
  40. double freq = getTickFrequency() / 1000;
  41. std::vector<double> layersTimes;
  42. double t = net.getPerfProfile(layersTimes) / freq;
  43. cout << "[INFO] classification took " << t << " ms" << endl;
  44. return 0;
  45. }