1 #include <opencv2/opencv.hpp> 2 #include <opencv2/dnn.hpp> 3 #include <iostream> 4 //使用Googlenet Caffe模型实现图像分类 5 using namespace cv; 6 using namespace cv::dnn; 7 using namespace std; 8 9 String model_bin_file = "D:/opencv3.3/opencv/sources/samples/data/dnn/bvlc_googlenet.caffemodel";//模型二进制文件 10 String model_txt_file = "D:/opencv3.3/opencv/sources/samples/data/dnn/bvlc_googlenet.prototxt";//模型文本(描述)文件 11 String labels_txt_file = "D:/opencv3.3/opencv/sources/samples/data/dnn/synset_words.txt";//标签文本文件 12 vector<String> readLabels();//读写文件方法 13 int main(int argc, char** argv) { 14 Mat src = imread("space_shuttle.jpg"); 15 if (src.empty()) { 16 printf("could not load image...\n"); 17 return -1; 18 } 19 namedWindow("input image", CV_WINDOW_AUTOSIZE); 20 imshow("input image", src); 21 vector<String> labels = readLabels(); 22 //读取Caffe模型 23 Net net = readNetFromCaffe(model_txt_file, model_bin_file); 24 if (net.empty()) {//如果没读到模型 25 printf("read caffe model data failure...\n"); 26 return -1; 27 } 28 //由bvlc_googlenet.prototxt知网络输入层大小为224*224 29 Mat inputBlob = blobFromImage(src, 1.0, Size(224, 224), Scalar(104, 117, 123)); 30 Mat prob; 31 for (int i = 0; i < 10; i++) { 32 net.setInput(inputBlob, "data");//设置第一层数据层进行输入 33 prob = net.forward("prob");//设置最后一层进行结果输出 34 } 35 Mat probMat = prob.reshape(1, 1);//转换成一行多列的分类结果 36 Point classNumber;//最大可能性的分类号 37 double classProb;//最大可能性的概率值 38 minMaxLoc(probMat, NULL, &classProb, NULL, &classNumber); 39 int classidx = classNumber.x; 40 printf("\n current image classification : %s, possible : %.2f", labels.at(classidx).c_str(), classProb); 41 //图片上放置文本 红色显示 42 putText(src, labels.at(classidx), Point(20, 20), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(0, 0, 255), 2, 8); 43 imshow("Image Classification", src); 44 45 waitKey(0); 46 return 0; 47 } 48 vector<String> readLabels() {//读取标签文本文件 49 vector<String> classNames; 50 ifstream fp(labels_txt_file);//文件输入输出流 51 if (!fp.is_open()) {//如果文件未打开 52 printf("could not open the file"); 53 exit(-1); 54 } 55 string name; 56 while (!fp.eof()) {//如果文件并未读取到结尾 57 getline(fp, name);//读取文件每一行 58 if (name.length()) { 59 classNames.push_back(name.substr(name.find(' ') + 1));//字符拆解与分割 60 } 61 } 62 fp.close();//关闭文件输入输出流 63 return classNames;//返回分类名 64 }
航天飞机,概率100%
山地单车,概率93%
标签:fp,src,DNN,name,labels,GoogleNet,Caffe,file,txt From: https://www.cnblogs.com/ybqjymy/p/17639506.html