上一篇博文,正确跑通了mnist数据集,得到了lenet_iter_5000.caffemodel lenet_iter_5000.solverstate lenet_iter_10000.caffemodel lenet_iter_10000.solverstate 四个文件
一、按照下面步骤修改caffe-master\examples\mnist文件夹中的 lenet_train_test.prototxt 文件
1、去掉数据输入层,即将top 为 “data” 的layers 去掉。 即将下面的内容删掉
layer {
name: "mnist"
type: "Data"
top: "data"
top: "label"
include {
phase: TRAIN
}
transform_param {
scale: 0.00390625
}
data_param {
source: "examples/mnist/mnist_train_lmdb"
batch_size: 64
backend: LMDB
}
}
layer {
name: "mnist"
type: "Data"
top: "data"
top: "label"
include {
phase: TEST
}
transform_param {
scale: 0.00390625
}
data_param {
source: "examples/mnist/mnist_test_lmdb"
batch_size: 100
backend: LMDB
}
}
2、重新建立输入,即添加下面的内容
input: "data"
input_shape {
dim: 1 # batchsize
dim: 1 # number of channels
dim: 28 # width
dim: 28 # height
}
3、去掉输出层,即将bottom 为 “label” 的layers 去掉,即将下面的内容删掉
layer {
name: "accuracy"
type: "Accuracy"
bottom: "ip2"
bottom: "label"
top: "accuracy"
include {
phase: TEST
}
}
layer {
name: "loss"
type: "SoftmaxWithLoss"
bottom: "ip2"
bottom: "label"
top: "loss"
}
4、重新建立输出,即添加下面的内容
layer {
name: "prob"
type: "Softmax"
bottom: "ip2"
top: "prob"
}
#include
#include
#include
using namespace std;
using namespace cv;
using namespace cv::dnn;
/* Find best class for the blob (i. e. class with maximal probability) */
static void getMaxClass(const Mat &probBlob, int *classId, double *classProb)
{
Mat probMat = probBlob.reshape(1, 1);
Point classNumber;
minMaxLoc(probMat, NULL, classProb, NULL, &classNumber);
*classId = classNumber.x;
}
int main()
{
string modelTxt = "lenet_train_test.prototxt";
string modelBin = "lenet_iter_10000.caffemodel";
//read image
Mat img = imread("4.bmp", 0);
Mat inputBlob = dnn::blobFromImage(img, 0.00390625f, Size(28, 28), Scalar(), false); //Convert Mat to batch of images
dnn::Net net;
try{
net = dnn::readNetFromCaffe(modelTxt, modelBin);
}
catch (cv::Exception &ee){
cerr << "Exception: " << ee.what() << endl;
if (net.empty()){
cout << "Can't load the network by using the flowing files:" << endl;
cout << "modelTxt: " << modelTxt << endl;
cout << "modelBin: " << modelBin << endl; exit(-1);
}
}
Mat pred;
net.setInput(inputBlob, "data");//set the network input, "data" is the name of the input layer
pred = net.forward("prob");//compute output, "prob" is the name of the output layer
cout << pred << endl; int classId; double classProb; getMaxClass(pred, &classId, &classProb);
cout << "Best Class: " << classId << endl;
cout << "Probability: " << classProb * 100 << "%" << endl;
}
http://blog.csdn.net/sushiqian/article/details/78555891
https://www.cnblogs.com/messier/p/7997951.html#_caption_1
https://docs.opencv.org/master/d5/de7/tutorial_dnn_googlenet.html
工程代码及caffemodel的下载