#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2\opencv.hpp>
#include<opencv2/dnn.hpp>
#include<fstream>
using namespace std;
using namespace cv;
using namespace cv::dnn;
String model_bin_file = "bvlc_googlenet.caffemodel";
String model_text_file = "bvlc_googlenet.prototxt";
String labels_txt_file = "synset_words.txt";
vector<String>readLabels();
int main()
{
Mat input = imread("飞机.jpg");
namedWindow("OUTPUT", WINDOW_AUTOSIZE);
imshow("OUTPUT", input);
vector<String>labels = readLabels();
Net net = readNetFromCaffe(model_text_file, model_bin_file);
if (net.empty())
{
cout << "read caffe model data No" << endl;
}
Mat inputBlob = blobFromImage(input, 1.0, Size(224, 224), Scalar(104, 117, 123));
Mat prob;
for (int i = 0; i < 10; i++)
{
net.setInput(inputBlob, "data");
prob = net.forward("prob");
}
Mat probMat=prob.reshape(1, 1);
Point classNumber;
double classProb;
minMaxLoc(probMat, NULL, &classProb, NULL, &classNumber);
int classidx = classNumber.x;
printf("\n The input image classiffcation: %s,possible:%.2f", labels.at(classidx).c_str(), classProb);
putText(input, labels.at(classidx), Point(20, 20), FONT_HERSHEY_PLAIN, 1.0, Scalar(0, 0, 255), 2, 8);
imshow("OUTPUT", input);
waitKey(0);
return 0;
}
vector<String>readLabels()
{
vector<String>classNames;
ifstream fp(labels_txt_file);
if (!fp.is_open())
{
cout << "not open the file";
exit(-1);
}
string name;
while (!fp.eof())
{
getline(fp, name);
if (name.length())
{
classNames.push_back(name.substr(name.find
(' ') + 1));
}
}
fp.close();
return classNames;
}