构建网络
采用官方示例的的lenet网络
训练
相关文件都已编译好,下载后执行命令即可
.\caffe-bin.exe train --solver .\lenet_solver.prototxt
识别
#include <caffe/caffe.hpp>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>#include <string>
#include <vector>using namespace caffe;
using std::string;int main(int argc, char** argv)
{fLI::FLAGS_minloglevel = 2;string model_file = "lenet_deploy.prototxt";string trained_file = "lenet_iter_10000.caffemodel"; //for visualizationstring img_file = "Fmnist_images/test/test_0_7.jpg";Caffe::set_mode(Caffe::CPU);shared_ptr<Net<float> > net;/* Load the network. */net.reset(new Net<float>(model_file, caffe::TEST));net->CopyTrainedLayersFrom(trained_file);CHECK_EQ(net->num_inputs(), 1) << "Network should have exactly one input.";CHECK_EQ(net->num_outputs(), 1) << "Network should have exactly one output.";//net->set_debug_info(true);Blob<float>* input_layer = net->input_blobs()[0];int num_channels = input_layer->channels();int input_height = input_layer->height();int input_width = input_layer->width();CHECK(num_channels == 3 || num_channels == 1) << "Input layer should have 1 or 3 channels.";input_layer->Reshape(1, num_channels, input_height, input_width);/* Forward dimension change to all layers. */net->Reshape();std::vector<cv::Mat> input_channels;float* input_data = input_layer->mutable_cpu_data();for (int i = 0; i < input_layer->channels(); ++i) {cv::Mat channel(input_height, input_width, CV_32FC1, input_data);input_channels.push_back(channel);input_data += input_height * input_width;}// Input Datacv::Mat img = cv::imread(img_file, 1);CHECK(!img.empty()) << "Unable to decode image " << img_file;cv::Mat sample_resized;cv::resize(img, sample_resized, cv::Size(input_width, input_height));cv::Mat sample_float;if (num_channels == 3)sample_resized.convertTo(sample_float, CV_32FC3);elsesample_resized.convertTo(sample_float, CV_32FC1);sample_float *= 0.00390625;/* This operation will write the separate BGR planes directly to the* input layer of the network because it is wrapped by the cv::Mat* objects in input_channels. */cv::split(sample_float, input_channels);CHECK(reinterpret_cast<float*>(input_channels.at(0).data) == net->input_blobs()[0]->cpu_data())<< "Input channels are not wrapping the input layer of the network.";// predictnet->Forward();/* Copy the output layer to a std::vector */Blob<float>* output_layer = net->output_blobs()[0];std::cout << "output_blob(n,c,h,w) = " << output_layer->num() << ", " << output_layer->channels() << ", "<< output_layer->height() << ", " << output_layer->width() << std::endl;for (int n = 0; n<output_layer->num(); n++) {for (int c = 0; c < output_layer->channels(); c++) {for (int h = 0; h<output_layer->height(); h++) {for (int w = 0; w<output_layer->width(); w++) { std::cout << "output_blob(n,c,h,w) = " << n << ", " << c << ", "<< h << ", " << w<<":"<< output_layer->data_at(n, c, h, w) << std::endl;}}}}}
下载地址