基于opencv分类(基于TensorFlow 的训练模型inception_v1)

#include
#include 
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 readClassNames(string filename) //将文件内容以每行,读到一个String vector中
{
	std::vector 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 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;
}

你可能感兴趣的:(深度学习)