//实现googlenet网络 #include<opencv2\opencv.hpp> #include <opencv2\dnn.hpp> using namespace std; using namespace cv; using namespace cv::dnn; string model_text = "C:\\Users\\Administrator\\Desktop\\c++\\data_model\\googlenet\\bvlc_googlenet.prototxt"; string model_bin = "C:\\Users\\Administrator\\Desktop\\c++\\data_model\\googlenet\\bvlc_googlenet.caffemodel"; string class_labels = "C:\\Users\\Administrator\\Desktop\\c++\\data_model\\googlenet\\synset_words.txt"; 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; cap.open(0); if(!cap.isOpened()) { cout << "cammer is failed!" << endl; } Net net = readNetFromCaffe(model_text, model_bin); if (net.empty()) { cout << "model_text is empty" << endl; cout << "model_bin is empty" << endl; } Mat img, pro; int class_id; double classProb; while (1) { cap >> img; Mat inputBlob = blobFromImage(img, 1, Size(224, 224), Scalar(104, 117, 123)); net.setInput(inputBlob, "data"); pro = net.forward("prob"); //计算输出 Mat proMax = pro.reshape(1, 1);//维度reshape成1*1000 Point class_number; 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; //输出可能性 imshow("googleNet", img); if (waitKey(100) ==27) break; } return 0; }
08-11
251
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)