要根据已有caffemodel等文件进行图像分类,需要阅读classification.cpp文件,然后在此cpp文件基础上修改相应代码即可。
打开E:\study_materials\Caffe\caffe-master\caffe-master\windows根目录下的Caffe.sln,然后找到如图所示的cpp文件
解读此cpp文件,可参考网址:
http://m.blog.csdn.net/wanggao_1990/article/details/78118062
主要的调用函数
Classifier classifier(model_file, trained_file, mean_file, label_file); std::vector
http://blog.csdn.net/shakevincent/article/details/52995253
http://blog.csdn.net/sinat_30071459/article/details/50974695
model下载地址:链接:http://pan.baidu.com/s/1hs3CF9y 密码:j7m4
该代码逐张读取文件夹下的图像并将分类结果显示在图像左上角,按任意键(除Esc键)进入下一张,按Esc键结束程序。
结果显示在左上角,有英文和中文两种标签可选,如果显示中文,需要使用Freetype库。
vs2013上新建一个 Win32控制台应用程序空项目
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "io.h"
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
#include"caffe_layers_registry.hpp"
using namespace caffe; // NOLINT(build/namespaces)
using std::string;
/* Pair (label, confidence) representing a prediction. */
typedef std::pair Prediction;
class Classifier {
public:
Classifier(const string& model_file,
const string& trained_file,
const string& mean_file,
const string& label_file);
std::vector Classify(const cv::Mat& img, int N = 5);
private:
void SetMean(const string& mean_file);
std::vector Predict(const cv::Mat& img);
void WrapInputLayer(std::vector* input_channels);
void Preprocess(const cv::Mat& img,
std::vector* input_channels);
private:
shared_ptr > net_;
cv::Size input_geometry_;
int num_channels_;
cv::Mat mean_;
std::vector labels_;
};
Classifier::Classifier(const string& model_file,
const string& trained_file,
const string& mean_file,
const string& label_file) {
#ifdef CPU_ONLY
Caffe::set_mode(Caffe::CPU);
#else
Caffe::set_mode(Caffe::GPU);
#endif
/* Load the network. */
net_.reset(new Net(model_file, 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.";
Blob* input_layer = net_->input_blobs()[0];
num_channels_ = input_layer->channels();
CHECK(num_channels_ == 3 || num_channels_ == 1)
<< "Input layer should have 1 or 3 channels.";
input_geometry_ = cv::Size(input_layer->width(), input_layer->height());
/* Load the binaryproto mean file. */
SetMean(mean_file);
/* Load labels. */
std::ifstream labels(label_file.c_str());
CHECK(labels) << "Unable to open labels file " << label_file;
string line;
while (std::getline(labels, line))
labels_.push_back(string(line));
Blob* output_layer = net_->output_blobs()[0];
CHECK_EQ(labels_.size(), output_layer->channels())
<< "Number of labels is different from the output layer dimension.";
}
static bool PairCompare(const std::pair& lhs,
const std::pair& rhs) {
return lhs.first > rhs.first;
}
/* Return the indices of the top N values of vector v. */
static std::vector Argmax(const std::vector& v, int N) {
std::vector > pairs;
for (size_t i = 0; i < v.size(); ++i)
pairs.push_back(std::make_pair(v[i], static_cast(i)));
std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);
std::vector result;
for (int i = 0; i < N; ++i)
result.push_back(pairs[i].second);
return result;
}
/* Return the top N predictions. */
std::vector Classifier::Classify(const cv::Mat& img, int N) {
std::vector output = Predict(img);
N = std::min(labels_.size(), N);
std::vector maxN = Argmax(output, N);
std::vector predictions;
for (int i = 0; i < N; ++i) {
int idx = maxN[i];
predictions.push_back(std::make_pair(labels_[idx], output[idx]));
}
return predictions;
}
/* Load the mean file in binaryproto format. */
void Classifier::SetMean(const string& mean_file) {
BlobProto blob_proto;
ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);
/* Convert from BlobProto to Blob */
Blob mean_blob;
mean_blob.FromProto(blob_proto);
CHECK_EQ(mean_blob.channels(), num_channels_)
<< "Number of channels of mean file doesn't match input layer.";
/* The format of the mean file is planar 32-bit float BGR or grayscale. */
std::vector channels;
float* data = mean_blob.mutable_cpu_data();
for (int i = 0; i < num_channels_; ++i) {
/* Extract an individual channel. */
cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
channels.push_back(channel);
data += mean_blob.height() * mean_blob.width();
}
/* Merge the separate channels into a single image. */
cv::Mat mean;
cv::merge(channels, mean);
/* Compute the global mean pixel value and create a mean image
* filled with this value. */
cv::Scalar channel_mean = cv::mean(mean);
mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);
}
std::vector Classifier::Predict(const cv::Mat& img) {
Blob* input_layer = net_->input_blobs()[0];
input_layer->Reshape(1, num_channels_,
input_geometry_.height, input_geometry_.width);
/* Forward dimension change to all layers. */
net_->Reshape();
std::vector input_channels;
WrapInputLayer(&input_channels);
Preprocess(img, &input_channels);
net_->Forward();
/* Copy the output layer to a std::vector */
Blob* output_layer = net_->output_blobs()[0];
const float* begin = output_layer->cpu_data();
const float* end = begin + output_layer->channels();
return std::vector(begin, end);
}
/* Wrap the input layer of the network in separate cv::Mat objects
* (one per channel). This way we save one memcpy operation and we
* don't need to rely on cudaMemcpy2D. The last preprocessing
* operation will write the separate channels directly to the input
* layer. */
void Classifier::WrapInputLayer(std::vector* input_channels) {
Blob* input_layer = net_->input_blobs()[0];
int width = input_layer->width();
int height = input_layer->height();
float* input_data = input_layer->mutable_cpu_data();
for (int i = 0; i < input_layer->channels(); ++i) {
cv::Mat channel(height, width, CV_32FC1, input_data);
input_channels->push_back(channel);
input_data += width * height;
}
}
void Classifier::Preprocess(const cv::Mat& img,
std::vector* input_channels) {
/* Convert the input image to the input image format of the network. */
cv::Mat sample;
if (img.channels() == 3 && num_channels_ == 1)
cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);
else if (img.channels() == 4 && num_channels_ == 1)
cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
else if (img.channels() == 4 && num_channels_ == 3)
cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
else if (img.channels() == 1 && num_channels_ == 3)
cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
else
sample = img;
cv::Mat sample_resized;
if (sample.size() != input_geometry_)
cv::resize(sample, sample_resized, input_geometry_);
else
sample_resized = sample;
cv::Mat sample_float;
if (num_channels_ == 3)
sample_resized.convertTo(sample_float, CV_32FC3);
else
sample_resized.convertTo(sample_float, CV_32FC1);
cv::Mat sample_normalized;
cv::subtract(sample_float, mean_, sample_normalized);
/* 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_normalized, *input_channels);
CHECK(reinterpret_cast(input_channels->at(0).data)
== net_->input_blobs()[0]->cpu_data())
<< "Input channels are not wrapping the input layer of the network.";
}
//获取路径path下的文件,并保存在files容器中
void getFiles(string path, vector& files)
{
//文件句柄
long hFile = 0;
//文件信息
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
getFiles(p.assign(path).append("\\").append(fileinfo.name), files);
}
else
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
int main(int argc, char** argv) {
string model_file("E:\\study_materials\\Caffe\\caffe-master\\caffe-master\\examples\\vehicle_type_recognition1\\model\\deploy.prototxt");
string trained_file("E:\\study_materials\\Caffe\\caffe-master\\caffe-master\\examples\\vehicle_type_recognition1\\model\\type.caffemodel");
string mean_file("E:\\study_materials\\Caffe\\caffe-master\\caffe-master\\examples\\vehicle_type_recognition1\\model\\type_mean.binaryproto");
string label_file("E:\\study_materials\\Caffe\\caffe-master\\caffe-master\\examples\\vehicle_type_recognition1\\model\\labels.txt");
string picture_path("E:\\study_materials\\Caffe\\caffe-master\\caffe-master\\examples\\vehicle_type_recognition1\\model\\type");
Classifier classifier(model_file, trained_file, mean_file, label_file);
vector files;
getFiles(picture_path, files);
for (int i = 0; i < files.size(); i++)
{
clock_t start, finish;
double duration;
start = clock();
cv::Mat img = cv::imread(files[i], -1);
cv::Mat img2;
std::vector predictions = classifier.Classify(img);
//Prediction p = predictions[i];
IplImage* show;
CvSize sz;
sz.width = img.cols;
sz.height = img.rows;
float scal = 0;
scal = sz.width > sz.height ? (300.0 / (float)sz.height) : (300.0 / (float)sz.width);
sz.width *= scal;
sz.height *= scal;
resize(img, img2, sz, 0, 0, CV_INTER_LINEAR);
show = cvCreateImage(sz, IPL_DEPTH_8U, 3);
cvCopy(&(IplImage)img2, show);
CvFont font;
cvInitFont(&font, CV_FONT_HERSHEY_COMPLEX, 0.5, 0.5, 0, 1, 8); //初始化字体
//cvPutText(show, text.c_str(), cvPoint(10, 30), &font, cvScalar(0, 0, 255, NULL));
string name_text;
name_text = files[i].substr(files[i].find_last_of("\\") + 1);
name_text = "Test picture ID::" + name_text;
cvPutText(show, name_text.c_str(), cvPoint(10, 130), &font, cvScalar(0, 0, 255, NULL));
for (size_t i = 0; i < predictions.size(); ++i)
{
Prediction p = predictions[i];
std::cout << std::fixed << std::setprecision(4) << p.second << " - \""
<< p.first << "\"" << std::endl;
string text = p.first;
char buff[20];
_gcvt(p.second, 4, buff);
text = text + ":" + buff;
/***************************输出英文标签*****************************************/
//CvFont font;
//cvInitFont(&font, CV_FONT_HERSHEY_COMPLEX, 0.5, 0.5, 0, 1, 8); //初始化字体
//cvPutText(show, text.c_str(), cvPoint(10, 30), &font, cvScalar(0, 0, 255, NULL));
//string name_text;
cvPutText(show, text.c_str(), cvPoint(10, 30 + i * 20), &font, cvScalar(0, 0, 255, NULL));
/**********************************************************************************/
cvNamedWindow("结果");
cvShowImage("结果", show);
cvWaitKey(1);
}
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("Time to do is ::");
printf("%f seconds\n", duration);
int c = cvWaitKey();
cvDestroyWindow("结果");
cvReleaseImage(&show);
std::cout << "///////////////////////////////////////////////////////////" << std::endl;
if (c == 27)
{
return 0;
}
}
return 0;
}
#include
#include "caffe/layers/input_layer.hpp"
#include "caffe/layers/inner_product_layer.hpp"
#include "caffe/layers/dropout_layer.hpp"
#include "caffe/layers/conv_layer.hpp"
#include "caffe/layers/relu_layer.hpp"
#include "caffe/layers/prelu_layer.hpp"
#include "caffe/layers/pooling_layer.hpp"
#include "caffe/layers/lrn_layer.hpp"
#include "caffe/layers/softmax_layer.hpp"
#include "caffe/layers/flatten_layer.hpp"
#include "caffe/layers/concat_layer.hpp"
#include "caffe/layers/reshape_layer.hpp"
#include "caffe/layers/softmax_layer.hpp"
#include "caffe/layers/rpn_layer.hpp"
#include "caffe/layers/roi_pooling_layer.hpp"
#include "caffe/layers/frcnn_proposal_layer.hpp""
namespace caffe
{
namespace Frcnn{
extern INSTANTIATE_CLASS(FrcnnProposalLayer);
REGISTER_LAYER_CLASS(FrcnnProposal);
}
extern INSTANTIATE_CLASS(InputLayer);
REGISTER_LAYER_CLASS(Input);
extern INSTANTIATE_CLASS(SplitLayer);
REGISTER_LAYER_CLASS(Split);
extern INSTANTIATE_CLASS(ConvolutionLayer);
REGISTER_LAYER_CLASS(Convolution);
extern INSTANTIATE_CLASS(InnerProductLayer);
REGISTER_LAYER_CLASS(InnerProduct);
extern INSTANTIATE_CLASS(DropoutLayer);
REGISTER_LAYER_CLASS(Dropout);
extern INSTANTIATE_CLASS(ReLULayer);
REGISTER_LAYER_CLASS(ReLU);
extern INSTANTIATE_CLASS(PReLULayer);
REGISTER_LAYER_CLASS(PReLU);
extern INSTANTIATE_CLASS(PoolingLayer);
REGISTER_LAYER_CLASS(Pooling);
extern INSTANTIATE_CLASS(LRNLayer);
REGISTER_LAYER_CLASS(LRN);
extern INSTANTIATE_CLASS(SoftmaxLayer);
REGISTER_LAYER_CLASS(Softmax);
extern INSTANTIATE_CLASS(RPNLayer);
REGISTER_LAYER_CLASS(RPN);
extern INSTANTIATE_CLASS(ROIPoolingLayer);
REGISTER_LAYER_CLASS(ROIPooling);
extern INSTANTIATE_CLASS(FlattenLayer);
REGISTER_LAYER_CLASS(Flatten);
extern INSTANTIATE_CLASS(ConcatLayer);
REGISTER_LAYER_CLASS(Concat);
extern INSTANTIATE_CLASS(ReshapeLayer);
REGISTER_LAYER_CLASS(Reshape);
}
编译运行,结果如下图所示:
Trick:Classifier classifier(model_file, trained_file, mean_file, label_file);
主要是修改这四个参数即可实现对不同模型的分类
参考资料
https://www.cnblogs.com/k7k8k91/p/7806232.html
根据我的博文“用已有模型进行微调finetune”,在“..\mydata1”根目录下新建文件deploy.prototxt
打开根目录下的train_val.prototxt文件,删除训练用的输入数据层,即前两个layer内容(训练阶段和测试阶段),如下图所示。
并添加:
layer {
name: "data"
type: "Input"
top: "data"
input_param { shape: { dim: 1 dim: 3 dim: 224 dim: 224 } }
}
删除最后两个layer(Accuracy 和 SoftmaxWithLoss),如下图所示。
并添加:
layer {
name: "prob"
type: "Softmax"
bottom: "fc8"
top: "prob"
}
分别是 caffenet_train_iter_1000.caffemodel 和 modelre_train_mean.binaryproto
..\mydata1根目录下新建文件夹type,存放需要测试的图片
四个参数修改并新建了文件夹type之后,就可以成功运行了!!!