Caffe图片训练分类研究、深度学习图片分类

来源:互联网 发布:本田数据库 编辑:程序博客网 时间:2024/03/29 00:10

Caffe图片训练分类研究、深度学习图片分类
转载请注明:http://blog.csdn.net/forest_world
一、NSFW研究

1、安装Docker

http://www.linuxidc.com/Linux/2014-08/105656.htm安装Docker使用apt-get命令:$ apt-get install docker.io创建软连接ln -sf /usr/bin/docker.io /usr/local/bin/dockersudo service docker stopsudo service docker start 

这里写图片描述

2、

sudo docker build -t caffe:cpu https://raw.githubusercontent.com/BVLC/caffe/master/docker/standalone/cpu/DockerfileStep 0 : FROM ubuntu:14.04 ---> 35b394a6f7a2Step 1 : MAINTAINER caffe-maint@googlegroups.com ---> Using cache ---> ca50125d0951Step 2 : RUN apt-get update && apt-get install -y --no-install-recommends         build-essential         cmake         git         wget         libatlas-base-dev         libboost-all-dev         libgflags-dev         libgoogle-glog-dev         libhdf5-serial-dev         libleveldb-dev         liblmdb-dev         libopencv-dev         libprotobuf-dev         libsnappy-dev         protobuf-compiler         python-dev         python-numpy         python-pip         python-scipy &&     rm -rf /var/lib/apt/lists/* ---> Running in d6856e1b4740Ign http://archive.ubuntu.com trusty InReleaseGet:1 http://archive.ubuntu.com trusty-updates InRelease [65.9 kB]Get:2 http://archive.ubuntu.com trusty-security InRelease [65.9 kB]Get:3 http://archive.ubuntu.com trusty Release.gpg [933 B]Get:4 http://archive.ubuntu.com trusty-updates/main Sources [474 kB]Get:5 http://archive.ubuntu.com trusty-updates/main Sources [474 kB]Get:6 http://archive.ubuntu.com trusty-updates/restricted Sources [5247 B]Get:7 http://archive.ubuntu.com trusty-updates/universe Sources [209 kB]Get:8 http://archive.ubuntu.com trusty-updates/main amd64 Packages [1131 kB]......Removing intermediate container d3643cce1d7eStep 7 : ENV PYCAFFE_ROOT $CAFFE_ROOT/python ---> Running in e4e4019889f8 ---> e982c669b99bRemoving intermediate container e4e4019889f8Step 8 : ENV PYTHONPATH $PYCAFFE_ROOT:$PYTHONPATH ---> Running in a9ee4331bbe8 ---> 8a1867b64b5cRemoving intermediate container a9ee4331bbe8Step 9 : ENV PATH $CAFFE_ROOT/build/tools:$PYCAFFE_ROOT:$PATH ---> Running in bc2a271a95bd ---> 864daab5c633Removing intermediate container bc2a271a95bdStep 10 : RUN echo "$CAFFE_ROOT/build/lib" >> /etc/ld.so.conf.d/caffe.conf && ldconfig ---> Running in d0af6f3e69ea ---> fa8b1e810492Removing intermediate container d0af6f3e69eaStep 11 : WORKDIR /workspace ---> Running in ab94152a0a18 ---> 49ffbf2d8fefRemoving intermediate container ab94152a0a18Successfully built 49ffbf2d8fef

3、
git clone https://github.com/yahoo/open_nsfw
$ cd open_nsfw

@ubuntu:~$ git clone https://github.com/yahoo/open_nsfwCloning into 'open_nsfw'...remote: Counting objects: 31, done.remote: Compressing objects: 100% (20/20), done.Unpacking objects:  32% (10/31) 

4、

I1012 05:17:23.226325     1 net.cpp:228] relu_stage0_block0 does not need backward computation.I1012 05:17:23.226327     1 net.cpp:228] eltwise_stage0_block0 does not need backward computation.I1012 05:17:23.226331     1 net.cpp:228] scale_stage0_block0_branch2c does not need backward computation.I1012 05:17:23.226333     1 net.cpp:228] bn_stage0_block0_branch2c does not need backward computation.I1012 05:17:23.226336     1 net.cpp:228] conv_stage0_block0_branch2c does not need backward computation.I1012 05:17:23.226339     1 net.cpp:228] relu_stage0_block0_branch2b does not need backward computation.I1012 05:17:23.226342     1 net.cpp:228] scale_stage0_block0_branch2b does not need backward computation.I1012 05:17:23.226346     1 net.cpp:228] bn_stage0_block0_branch2b does not need backward computation.I1012 05:17:23.226348     1 net.cpp:228] conv_stage0_block0_branch2b does not need backward computation.I1012 05:17:23.226351     1 net.cpp:228] relu_stage0_block0_branch2a does not need backward computation.I1012 05:17:23.226354     1 net.cpp:228] scale_stage0_block0_branch2a does not need backward computation.I1012 05:17:23.226356     1 net.cpp:228] bn_stage0_block0_branch2a does not need backward computation.I1012 05:17:23.226359     1 net.cpp:228] conv_stage0_block0_branch2a does not need backward computation.I1012 05:17:23.226362     1 net.cpp:228] scale_stage0_block0_proj_shortcut does not need backward computation.I1012 05:17:23.226366     1 net.cpp:228] bn_stage0_block0_proj_shortcut does not need backward computation.I1012 05:17:23.226368     1 net.cpp:228] conv_stage0_block0_proj_shortcut does not need backward computation.I1012 05:17:23.226372     1 net.cpp:228] pool1_pool1_0_split does not need backward computation.I1012 05:17:23.226374     1 net.cpp:228] pool1 does not need backward computation.I1012 05:17:23.226378     1 net.cpp:228] relu_1 does not need backward computation.I1012 05:17:23.226380     1 net.cpp:228] scale_1 does not need backward computation.I1012 05:17:23.226383     1 net.cpp:228] bn_1 does not need backward computation.I1012 05:17:23.226387     1 net.cpp:228] conv_1 does not need backward computation.I1012 05:17:23.226389     1 net.cpp:228] data does not need backward computation.I1012 05:17:23.226392     1 net.cpp:270] This network produces output probI1012 05:17:23.226526     1 net.cpp:283] Network initialization done.I1012 05:17:23.277700     1 upgrade_proto.cpp:77] Attempting to upgrade batch norm layers using deprecated params: nsfw_model/resnet_50_1by2_nsfw.caffemodelI1012 05:17:23.277819     1 upgrade_proto.cpp:80] Successfully upgraded batch norm layers using deprecated params.I1012 05:17:23.283418     1 net.cpp:761] Ignoring source layer lossNSFW score:   0.000410715758335

二、

这里写图片描述

#include <caffe/caffe.hpp>#ifdef USE_OPENCV#include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc/imgproc.hpp>#endif  // USE_OPENCV#include <algorithm>#include <iosfwd>#include <memory>#include <string>#include <utility>#include <vector>#ifdef USE_OPENCVusing namespace caffe;  // NOLINT(build/namespaces)using std::string;/* Pair (label, confidence) representing a prediction. */typedef std::pair<string, float> Prediction;class Classifier { public:  Classifier(const string& model_file,             const string& trained_file,             const string& mean_file,             const string& label_file);  std::vector<Prediction> Classify(const cv::Mat& img, int N = 5); private:  void SetMean(const string& mean_file);  std::vector<float> Predict(const cv::Mat& img);  void WrapInputLayer(std::vector<cv::Mat>* input_channels);  void Preprocess(const cv::Mat& img,                  std::vector<cv::Mat>* input_channels); private:  shared_ptr<Net<float> > net_;  cv::Size input_geometry_;  int num_channels_;  cv::Mat mean_;  std::vector<string> 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<float>(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<float>* 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<float>* 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<float, int>& lhs,                        const std::pair<float, int>& rhs) {  return lhs.first > rhs.first;}/* Return the indices of the top N values of vector v. */static std::vector<int> Argmax(const std::vector<float>& v, int N) {  std::vector<std::pair<float, int> > pairs;  for (size_t i = 0; i < v.size(); ++i)    pairs.push_back(std::make_pair(v[i], static_cast<int>(i)));  std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);  std::vector<int> result;  for (int i = 0; i < N; ++i)    result.push_back(pairs[i].second);  return result;}/* Return the top N predictions. */std::vector<Prediction> Classifier::Classify(const cv::Mat& img, int N) {  std::vector<float> output = Predict(img);  N = std::min<int>(labels_.size(), N);  std::vector<int> maxN = Argmax(output, N);  std::vector<Prediction> 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<float> */  Blob<float> 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<cv::Mat> 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<float> Classifier::Predict(const cv::Mat& img) {  Blob<float>* 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<cv::Mat> input_channels;  WrapInputLayer(&input_channels);  Preprocess(img, &input_channels);  net_->Forward();  /* Copy the output layer to a std::vector */  Blob<float>* output_layer = net_->output_blobs()[0];  const float* begin = output_layer->cpu_data();  const float* end = begin + output_layer->channels();  return std::vector<float>(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<cv::Mat>* input_channels) {  Blob<float>* 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<cv::Mat>* 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<float*>(input_channels->at(0).data)        == net_->input_blobs()[0]->cpu_data())    << "Input channels are not wrapping the input layer of the network.";}int main(int argc, char** argv) {  if (argc != 6) {    std::cerr << "Usage: " << argv[0]              << " deploy.prototxt network.caffemodel"              << " mean.binaryproto labels.txt img.jpg" << std::endl;    return 1;  }  ::google::InitGoogleLogging(argv[0]);  string model_file   = argv[1];  string trained_file = argv[2];  string mean_file    = argv[3];  string label_file   = argv[4];  Classifier classifier(model_file, trained_file, mean_file, label_file);  string file = argv[5];  std::cout << "---------- Prediction for "            << file << " ----------" << std::endl;  cv::Mat img = cv::imread(file, -1);  CHECK(!img.empty()) << "Unable to decode image " << file;  std::vector<Prediction> predictions = classifier.Classify(img);  /* Print the top N predictions. */  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;  }}#elseint main(int argc, char** argv) {  LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";}#endif  // USE_OPENCV

这里写图片描述

这里写图片描述

  string model_file   ("E:\\ cpp_classification\\caffe.prototxt");  string trained_file ("E:\\ cpp_classification\\caffe.caffemodel");  string mean_file    ("E:\\cpp_classification\\mean.binaryproto");  string label_file   ("E:\\ cpp_classification\\labels.txt");  Classifier classifier(model_file, trained_file, mean_file, label_file);  string file ("E:\\ cpp_classification\\test.jpg");

参考学习资料:
http://m.blog.csdn.net/article/details?id=52443126 基于深度学习的人脸识别系统系列(Caffe+OpenCV+Dlib)——【一】如何在Visual Studio中像使用OpenCV一样使用Caffe
http://mp.weixin.qq.com/s?__biz=MzI1NTE4NTUwOQ==&mid=2650325557&idx=1&sn=362d476d3b3820ea56e4672369565e4f&chksm=f235a53fc5422c2939f76b7e8f5265333f3159b0ec4275fe733d27e7a03f17395b0460a318d2&mpshare=1&scene=1&srcid=1017Le0xZeDhioc9DxPIGNN9#wechat_redirect IJCAI16论文速读:Deep Learning论文选读(上)

http://www.cnblogs.com/carle-09/p/5779304.html 4 .caffe:train_val.prototxt、 solver.prototxt 、 deploy.prototxt( 创建模型与编写配置文件)
http://blog.csdn.net/deeplearninglc007/article/details/40086503 使用Caffe对图片进行训练并分类的简单流程
http://blog.csdn.net/wang4959520/article/details/51841110 将train_val.prototxt 转换成deploy.prototxt
http://blog.csdn.net/hyman_yx/article/details/51732656 Caffe均值文件mean.binaryproto转mean.npy
http://blog.csdn.net/shakevincent/article/details/51694686微软Caffe编译
http://www.cnblogs.com/alexcai/p/5469436.html caffe简易上手指南(二)—— 训练我们自己的数据
http://www.aiuxian.com/article/p-1659539.html 深度学习–如何利用Caffe进行训练ImageNet网络
http://www.th7.cn/system/win/201602/153606.shtml caffe for windows 下使用caffemodel 实现cifar10的图像分类
http://blog.csdn.net/dcxhun3/article/details/52021296 用训练好的caffemodel来进行分类
http://neuralnetworksanddeeplearning.com/chap1.html CHAPTER 1 Using neural nets to recognize handwritten digits

http://www.cnblogs.com/shishupeng/p/5694775.html 深度卷积网络CNN与图像语义分割

本文地址:http://blog.csdn.net/forest_world

1 0
原创粉丝点击