基於opencv分類(基於TensorFlow 的訓練模型inception_v1)
阿新 • • 發佈:2019-02-01
#include<opencv2\opencv.hpp> #include <opencv2\dnn.hpp> using namespace std; using namespace cv; using namespace cv::dnn; string class_labels = "C:\\Users\\Administrator\\Desktop\\c++\\data_model\\inception_v1\\imagenet_comp_graph_label_strings.txt"; string model = "C:\\Users\\Administrator\\Desktop\\c++\\data_model\\inception_v1\\tensorflow_inception_graph.pb"; std::vector<String> readClassNames(string filename) //將檔案內容以每行,讀到一個String vector中 { std::vector<String> classNames; std::ifstream fp(filename); if (!fp.is_open()) { cout << "file is no found" << endl; exit(-1); } std::string name; while (!fp.eof())//檔案沒有到尾部 { std::getline(fp, name); //將fp第一行賦值到name中 if (name.length()) { classNames.push_back(name.substr(name.find(" ") + 1)); } } fp.close(); return classNames; } int main() { VideoCapture cap; Mat img, proBlob, prob; cap.open(0); Point class_number; double classProb; int class_id; if (!cap.isOpened()) { cout << "cammer is failed!" << endl; } Net net = readNetFromTensorflow(model); if (net.empty()) { cout << "model file is not found" << endl; return -1; } while (1) { cap >> img; proBlob = blobFromImage(img, 1, Size(224, 224), Scalar(104, 117, 123));//將Mat轉換blob格式 net.setInput(proBlob, "input");//輸入 prob = net.forward("softmax2");//計算 Mat proMax = prob.reshape(1, 1); minMaxLoc(proMax, NULL, &classProb, NULL, &class_number); class_id = class_number.x; //獲得預測索引 std::vector<String> classname = readClassNames(class_labels); cout << "Best class:#" << class_id << "," << classname.at(class_id) << "'" << endl;//根據預測索引找到檔案中的類別名 cout << "Probability:" << classProb * 100 << "%" << endl; //輸出可能性 putText(img, classname.at(class_id), Point(30, 30), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(0, 0, 255), 2, 8);//打標註 imshow("inception_v1", img); if (waitKey(100) == 27) break; } return 0; }