DNN系列2_GoogleNet-Caffe模型实现图像分类

本例程用到的模型文件、源码和图片素材

贾志刚OpenCV3.3深度神经网络DNN模块系列学习资料整理

2 使用GoogleNet模型数据的图像分类

 Googlenet模型与数据介绍

Caffe - 模型下载

 bvlc_googlenet CNN模型

 基于100万张图像实现1000个分类

2.1 使用模型实现图像分类

 编码处理
- 加载Caffem模型
- 使用模型预测

实例2:GoogleNet-Caffe模型实现图像分类

​
#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <iostream>
//使用Googlenet Caffe模型实现图像分类
using namespace cv;
using namespace cv::dnn;
using namespace std;

String model_bin_file = "D:/opencv3.3/opencv/sources/samples/data/dnn/bvlc_googlenet.caffemodel";//模型二进制文件
String model_txt_file = "D:/opencv3.3/opencv/sources/samples/data/dnn/bvlc_googlenet.prototxt";//模型文本(描述)文件
String labels_txt_file = "D:/opencv3.3/opencv/sources/samples/data/dnn/synset_words.txt";//标签文本文件
vector<String> readLabels();//读写文件方法
int main(int argc, char** argv) {
	Mat src = imread("space_shuttle.jpg");
	if (src.empty()) {
		printf("could not load image...\n");
		return -1;
	}
	namedWindow("input image", CV_WINDOW_AUTOSIZE);
	imshow("input image", src);
	vector<String> labels = readLabels();
	//读取Caffe模型
	Net net = readNetFromCaffe(model_txt_file, model_bin_file);
	if (net.empty()) {//如果没读到模型
		printf("read caffe model data failure...\n");
		return -1;
	}
	//由bvlc_googlenet.prototxt知网络输入层大小为224*224
	Mat inputBlob = blobFromImage(src, 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 current image classification : %s, possible : %.2f", labels.at(classidx).c_str(), classProb);
	//图片上放置文本  红色显示
	putText(src, labels.at(classidx), Point(20, 20), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(0, 0, 255), 2, 8);
	imshow("Image Classification", src);

	waitKey(0);
	return 0;
}
vector<String> readLabels() {//读取标签文本文件
	vector<String> classNames;
	ifstream fp(labels_txt_file);//文件输入输出流
	if (!fp.is_open()) {//如果文件未打开
		printf("could 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;//返回分类名
}

​

航天飞机,概率100%

山地单车,概率93%

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亦我飞也

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值