Here's how to read this picture and then train:
1. Create a new defined header file Include/caffe/layers/my_data_layer.hpp
Method for re-layer name: Virtual Inline const char* type () const {return "MyData";}
#ifndef caffe_my_data_layer_hpp_ #define CAFFE_MY_DATA_LAYER_HPP_ #include <string> #include <utility> # Include <vector> #include <algorithm>//std::random_shuffle #include <vector>//Std::vector # Include <ctime>//Std::time #include "caffe/blob.hpp" #include "caffe/data_transformer.hpp" #include "Caffe /internal_thread.hpp "#include" caffe/layer.hpp "#include" caffe/layers/base_data_layer.hpp "#include" caffe/proto/ Caffe.pb.h "namespace Caffe {Template <typename dtype> class Mydatalayer:public Baseprefetchingdatalayer<dty pe> {public:explicit mydatalayer (const layerparameter& param): baseprefetchingdatalayer<dtype> (para
m) {} virtual ~mydatalayer (); virtual void Datalayersetup (const vector<blob<dtype>*>& Bottom, const vector<blob<dtype>*
>& top);
Virtual Inline const char* type () const {return "MyData";} Virtual inline int exactnumbottomblobs () CONST {return 0;}
Virtual inline int exactnumtopblobs () const {return 2;}
Protected:shared_ptr<caffe::rng> Prefetch_rng_;
virtual void shuffleimages ();
virtual void Load_batch (batch<dtype>* batch); Inline Cv::mat get_one_sample (cv::mat whole_img,int pos_x,int pos_y,int width,int height) {return Source_image_ (CV
:: Rect (Pos_x,pos_y,width,height)). Clone ();
} VECTOR<STD::p air<cv::mat, int> > Samples_;
int lines_id_;
String Image_address_;
int Start_col_;
int End_col_;
int sample_width_;
int sample_height_;
Cv::mat Source_image_;
}; }//Namespace Caffe #endif//Caffe_my_data_layer_hpp_
2. Rewrite layersetup,shuffleimage,load_batch (see Code my_data_layer.cpp)
#ifdef USE_OPENCV #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include < Fstream>//Nolint (readability/streams) #include <iostream>//Nolint (readability/streams) #include < string> #include <utility> #include <vector> #include <stdio.h> #include "caffe/data_ Transformer.hpp "#include" caffe/layers/base_data_layer.hpp "#include" caffe/layers/my_data_layer.hpp "#include" Caffe/util/benchmark.hpp "#include" caffe/util/io.hpp "#include" caffe/util/math_functions.hpp "#include" caffe/util /rng.hpp "namespace Caffe {Template <typename dtype> mydatalayer<dtype>::~mydatalayer<dtype> () {th
Is->stopinternalthread (); } template <typename dtype> void mydatalayer<dtype>::D atalayersetup (const vector<blob<dtype>*
>& bottom,const vector<blob<dtype>*>& top) {//Init private variables. Image_address_ = This->layer_param_.my_data_param (). image_addrESS ();
Start_col_= This->layer_param_.my_data_param (). Start_col ();
End_col_ = This->layer_param_.my_data_param (). End_col ();
Sample_width_ = This->layer_param_.my_data_param (). Sample_width ();
Sample_height_= This->layer_param_.my_data_param (). Sample_height ();
lines_id_ = 0;
int label,x,y;
Cv::mat image;
Source_image_ = Cv::imread (Image_address_);
for (int i=0; i<; i++) {label = (int) (I/5);
for (int j=start_col_; J<end_col_; j + +) {y=20*i;
X=20*j;
Image = Get_one_sample (source_image_,x,y,20,20);
Samples_.push_back (Std::make_pair (Image,label));
}} CHECK (!samples_.empty ()) << "Data is empty";
Shuffle Images if (This->layer_param_.my_data_param (). Shuffle ()) {LOG (INFO) << "Shuffling data";
Shuffleimages ();
}//Save images if (This->layer_param_.my_data_param (). Is_save ()) {LOG (INFO) << "Saving images"; for (int i=0;i<samples_.size (); i++) {String save_folder = This->layer_param_.my_data_param (). Save_folder (
);
Char img_name[128];
sprintf (Img_name, "%s/%d.jpg", Save_folder.c_str (), i);
Cv::imwrite (Img_name,samples_[i].first);
}}//Read an image, and use it to initialize the top blob cv::mat cv_img = Samples_[lines_id_].first;
CHECK (cv_img.data) << "Could not load first image"; Use Data_transformer to infer the expected blob shape from a cv_image vector<int> top_shape = this->data_t
Ransformer_->inferblobshape (CV_IMG); This->transformed_data_.
Reshape (Top_shape);
Reshape Prefetch_data and top[0] according to the batch_size.
const int batch_size = This->layer_param_.my_data_param (). Batch_size ();
Top_shape[0] = batch_size; for (int i = 0; i < this->prefetch_.size (); ++i) {This->prefetch_[i]->data_.
Reshape (Top_shape);
} top[0]->reshape (Top_shape);LOG (INFO) << "Output data size:" << top[0]->num () << "," << top[0]->channels () << ","
<< top[0]->height () << "," << top[0]->width ();
Label Vector<int> Label_shape (1,batch_size);
Top[1]->reshape (Label_shape); for (int i = 0; i < this->prefetch_.size (); ++i) {this->prefetch_[i]->label_.
Reshape (Label_shape); }} template <typename dtype> void Mydatalayer<dtype>::shuffleimages () {Std::srand (unsigned (std::tim
E (0)));
Std::random_shuffle (Samples_.begin (), Samples_.end ()); } template <typename dtype> void Mydatalayer<dtype>::load_batch (batch<dtype>* batch) {CPUTimer BATC
H_timer; Batch_timer.
Start ();
Double read_time = 0;
Double trans_time = 0;
Cputimer timer;
CHECK (Batch->data_.count ());
CHECK (This->transformed_data_.count ());
Mydataparameter My_data_param = this-> Layer_param_.my_data_param (); Get Batch size const int batch_size = My_data_param.batch_size (); Reshape according to the first image of each batch//in single input batches allows for inputs of varying dimensio
n Cv::mat cv_img = Samples_[lines_id_].first;
CHECK (cv_img.data) << "Could not Load" <<lines_id_<< "sample"; Use Data_transformer to infer the expected blob shape from a cv_img vector<int> top_shape = This->data_tra
Nsformer_->inferblobshape (CV_IMG); This->transformed_data_.
Reshape (Top_shape);
Reshape batch According to the batch_size top_shape[0] = batch_size; Batch->data_.
Reshape (Top_shape);
dtype* prefetch_data = Batch->data_.mutable_cpu_data ();
dtype* prefetch_label= batch->label_.mutable_cpu_data ();
Datum scales int samples_size = Samples_.size (); for (int item_id=0;item_id<batch_size;++item_id) {//Get a blob timer.
Start (); CHECK_GT (Samples_size, lines_id_);
Cv::mat sample = Samples_[lines_id_].first;
CHECK (sample.data) << "Could not Load" <<lines_id_<< "sample"; Read_time + = timer.
microseconds (); Timer.
Start ();
Apply transformations to the image int offset = Batch->data_.offset (item_id);
This->transformed_data_.set_cpu_data (prefetch_data + offset);
This->data_transformer_->transform (sample,& (This->transformed_data_)); Trans_time + = timer.
microseconds ();
PREFETCH_LABEL[ITEM_ID] = Samples_[lines_id_].second;
Got the next ITER lines_id_++;
if (lines_id_>=samples_size) {///We have reached the end restart from the first.
DLOG (INFO) << "Restarting data prefetching from start.";
lines_id_=0;
if (My_data_param.shuffle ()) {shuffleimages (); }}} batch_timer.
Stop (); DLOG (INFO) << "Prefetch batch:" << batch_timer.milliseconds () <&lT
"Ms.";
DLOG (INFO) << "Read time:" << read_time/1000 << "Ms.";
DLOG (INFO) << "Transform time:" << trans_time/1000 << "Ms.";}
Instantiate_class (Mydatalayer);
Register_layer_class (MyData); }//Namespaces Caffe #endif//USE_OPENCV
3.proto/caffe.proto registering a new layer
Message Layerparameter {... //My new data layer for infer image data ++optional mydataparameter My_data_param = 1
50; } message V1layerparameter {... //My new data parameter ++optional mydataparameter my_data_param = 50;..
. } ...//Message that stores parameters used to apply a new data layer//To infer image data Message mydataparameter{&NB Sp
Image address Optional String image_address = 1; //Start column for calculation //traning and testing use different columns optional int32 start_col
= 2;
//End column for computing optional Int32 end_col = 3;
/Height of each image optional int32 sample_height = 4 [default = 0];
//Width of each image optional int32 sample_width = 5 [default = 0];
//Shuffle or not optional bool Shuffle = 6;
//Batch size for each computing optional int32 batch_size = 7; //Gray or color (equals to single channel or 3 ChanneLS) OPTIONAL BOOL Is_color = 8 [default = False];
/Save The image seperated from the image address or not optional BOOL Is_save = 9 [default = False];
/If Save, use this Save folder Optional String save_folder = 10;
}
test the newly defined data layer, use the original Lenet network, make changes to the input layer, the other does not change
Name: "LeNet"
layer {
name: "Mnist"
type: "MyData"
Top: "Data"
Top: "label"
include {
Phase:train
}
transform_param {
scale:0.00390625
}
my_data_param {
image_address: "/ Home/xyl/caffe/lesson2/lesson2-1/digits.png "
batch_size:64
start_col:0
end_col:70
Shuffle: True
sample_width:20
sample_height:20
is_save:true
save_folder: "/home/xyl/caffe/lesson2/ Lesson2-1/img "
}
}"
layer {
name: "Mnist"
type: "MyData"
Top: "Data"
Top: "Label"
include {
phase:test
}
transform_param {
scale:0.00390625
}
My_data_param {
image_address: "/home/xyl/caffe/lesson2/lesson2-1/digits.png"
batch_size:32
start_col:70
end_col:100
sample_width:20
sample_height:20
shuffle:true
}
}
Finally, create a new mydata.sh file
#!/usr/bin/env sh
set-e
./build/tools/caffe Train--solver=lesson2/lesson2-1/mydata_lenet_solver.prototxt $@
Run this file to do the test, as shown in the figure: