caffe源码阅读(一)convert_imageset.cpp注释

PS:本系列为本人初步学习caffe所记,由于理解尚浅,其中多有不足之处和错误之处,有待改正。

一、实现方法

首先,将文件名与它对应的标签用 std::pair 存储起来,其中first存储文件名,second存储标签,

其次,数据通过 Datum datum来存储,将图像与标签转为Datum 需要通过函数ReadImageToDatum() 来完成,

再次, Datum 数据又是通过datum.SerializeToString(&out)把数据序列化为字符串 string out;,

最后, 将字符串 string out ,通过txn->Put(string(key_cstr, length), out)写入数据库DB。

二、convert_imageset.cpp解析

1.头文件解析

 1 #include <algorithm>   //输出数组的内容、对数组进行升幂排序、反转数组内容、复制数组内容等操作
 2 #include <fstream>  // NOLINT(readability/streams)
 3 #include <string>
 4 #include <utility>    //utility头文件定义了一个pair类型,pair类型用于存储一对数据
 5 #include <vector>     //会自动扩展容量的数组
 6 
 7 #include "boost/scoped_ptr.hpp"   //智能指针头文件
 8 #include "gflags/gflags.h"       //Google的一个命令行参数库
 9 #include "glog/logging.h"        //日志头文件
10  
11 #include "caffe/proto/caffe.pb.h"  
12 #include "caffe/util/db.hpp"      //引入包装好的lmdb操作函数
13 #include "caffe/util/format.hpp"  
14 #include "caffe/util/io.hpp"      //引入opencv的图像操作函数
15 #include "caffe/util/rng.hpp"
16 
17 using namespace caffe;  // NOLINT(build/namespaces)引入全部caffe命名空间
18 using std::pair;        //引入pair对命名空间
19 using boost::scoped_ptr;
View Code

2.使用Flags宏定义变量

 1 DEFINE_bool(gray, false,
 2     "When this option is on, treat images as grayscale ones");    //是否为灰度图片 
 3 DEFINE_bool(shuffle, false,
 4     "Randomly shuffle the order of images and their labels");    //定义洗牌变量,是否随机打乱数据集的顺序  
 5 DEFINE_string(backend, "lmdb",
 6         "The backend {lmdb, leveldb} for storing the result");  //默认转换的数据类型
 7 DEFINE_int32(resize_width, 0, "Width images are resized to");   //定义resize的尺寸,默认为0,不转换尺寸  
 8 DEFINE_int32(resize_height, 0, "Height images are resized to");
 9 DEFINE_bool(check_size, false,
10     "When this option is on, check that all the datum have the same size");
11 DEFINE_bool(encoded, false,
12     "When this option is on, the encoded image will be save in datum");  //用于转换数据格式的  
13 DEFINE_string(encode_type, "",
14     "Optional: What type should we encode the image as ('png','jpg',...).");   //是否转换图像格式
View Code

注:gflags是google的一个开源处理命令行参数库,具体使用方法可以参照http://blog.csdn.net/lezardfu/article/details/23753741。

3.main函数

int main(int argc, char** argv) {
#ifdef USE_OPENCV
  ::google::InitGoogleLogging(argv[0]);   //初始化log
  // Print output to stderr (while still logging)
  FLAGS_alsologtostderr = 1;      //log写入stderr文件

#ifndef GFLAGS_GFLAGS_H_
  namespace gflags = google;
#endif

  gflags::SetUsageMessage("Convert a set of images to the leveldb/lmdb\n"
        "format used as input for Caffe.\n"
        "Usage:\n"
        "    convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME\n"
        "The ImageNet dataset for the training demo is at\n"
        "    http://www.image-net.org/download-images\n");
  gflags::ParseCommandLineFlags(&argc, &argv, true);   //初始化Flags,从命令行传入参数

  if (argc < 4) {
    gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/convert_imageset");
    return 1;
  }

  const bool is_color = !FLAGS_gray; //通过gflags把宏定义变量的值,赋值给常值变量
  const bool check_size = FLAGS_check_size;//检查图像的size  
  const bool encoded = FLAGS_encoded;    //是否编译(转换)图像格式      
  const string encode_type = FLAGS_encode_type; //要编译的图像格式 

  std::ifstream infile(argv[2]);  //创建指向train.txt的文件读入流
  std::vector<std::pair<std::string, int> > lines;  //定义向量变量,向量中每个元素为一个pair对,pair对有两个成员变量,
                                                    //一个为string类型,一个为int类型;其中string类型用于存储文件名,int类型,感觉用于存数对应类别的id
  std::string line;   
  size_t pos;
  int label;

  //读取train.txt中的文本行内容,将图片路径与label分离,存储在lines中
  while (std::getline(infile, line)) {          //读取train.txt中每行的内容,存在line中
    pos = line.find_last_of(' ');               //找出line中最后一个''所在的位置
    label = atoi(line.substr(pos + 1).c_str()); //获取line字符串中对应的label字符,并将其转换为整型
    lines.push_back(std::make_pair(line.substr(0, pos), label)); //将图片地址与label存在vector变量lines中
  }

  if (FLAGS_shuffle) {
    // randomly shuffle data(打乱数据,发现lines的成员顺序和值发生了变化)
    LOG(INFO) << "Shuffling data";    //LOG(INFO)日志输出
    shuffle(lines.begin(), lines.end());
  }
  LOG(INFO) << "A total of " << lines.size() << " images.";  //输出图片数据的数量

  if (encode_type.size() && !encoded)
    LOG(INFO) << "encode_type specified, assuming encoded=true.";

  int resize_height = std::max<int>(0, FLAGS_resize_height);
  int resize_width = std::max<int>(0, FLAGS_resize_width);

  // Create new DB(以智能指针的方式创建db::DB类型的对象 db)
  scoped_ptr<db::DB> db(db::GetDB(FLAGS_backend)); // 智能指针的创建方式类似泛型的格式,
                                                   //上面通过db.cpp内定义的命名的子命名空间中db的“成员函数”GetDB函数来初始化db对象
  db->Open(argv[3], db::NEW);                    //argv[3]的文件夹下创建并打开lmdb的操作环境  
  scoped_ptr<db::Transaction> txn(db->NewTransaction());//创建lmdb文件的操作句柄txn

  // Storing to db(源数据中提取图像数据)
  std::string root_folder(argv[1]);
  Datum datum;
  int count = 0;
  int data_size = 0;
  bool data_size_initialized = false;

  for (int line_id = 0; line_id < lines.size(); ++line_id) {
    bool status;
    std::string enc = encode_type;
    if (encoded && !enc.size()) {
      // Guess the encoding type from the file name
      string fn = lines[line_id].first;   //读取图片的绝对路径
      size_t p = fn.rfind('.');
      if ( p == fn.npos )
        LOG(WARNING) << "Failed to guess the encoding of '" << fn << "'";
      enc = fn.substr(p);
      std::transform(enc.begin(), enc.end(), enc.begin(), ::tolower);
    } 

    //通过ReadImageToDatum把图片和标签转换为Datum
    status = ReadImageToDatum(root_folder + lines[line_id].first,
        lines[line_id].second, resize_height, resize_width, is_color,
        enc, &datum);   //通过ReadImageToDatum把图片和标签转换为Datum

    if (status == false) continue;
    if (check_size) {
      if (!data_size_initialized) {
        data_size = datum.channels() * datum.height() * datum.width();
        data_size_initialized = true;
      } else {
        const std::string& data = datum.data();
        CHECK_EQ(data.size(), data_size) << "Incorrect data field size "
            << data.size();
      }
    }
    // sequential
    string key_str = caffe::format_int(line_id, 8) + "_" + lines[line_id].first; //序列化键值

    // Put in db
    string out;
    CHECK(datum.SerializeToString(&out));  //把数据序列转换为string out
    txn->Put(key_str, out);                //把键值放入到数据库

   //批量提交到lmdb文件
    if (++count % 1000 == 0) {
      // Commit db
      txn->Commit(); //保存到lmdb类型的文件
      txn.reset(db->NewTransaction()); //重新初始化操作句柄
      LOG(INFO) << "Processed " << count << " files.";
    }
  }
  // write the last batch
  if (count % 1000 != 0) {
    txn->Commit();
    LOG(INFO) << "Processed " << count << " files.";
  }
#else
  LOG(FATAL) << "This tool requires OpenCV; compile with USE_OPENCV.";
#endif  // USE_OPENCV
  return 0;
}
View Code

注:main函数中的主要函数为

ReadImageToDatum(root_folder + lines[line_id].first,lines[line_id].second, resize_height, resize_width, is_color,enc, &datum);

该函数内部有两个子函数:ReadImageToCVMat(filename, height, width, is_color)和CVMatToDatum(cv_img, datum)。

ReadImageToCVMat(filename, height, width, is_color)的主要功能是将图像的存储格式由3通道存储形式转换为cv空间存储形式,我的理解是由一个指针指向的存储空间,里面依次存放每个通道的像素值。

CVMatToDatum(cv_img, datum)的功能事将cv空间存储的像素值传递到datum.data。

参考:http://blog.csdn.net/whiteinblue/article/details/45330801

原文地址:https://www.cnblogs.com/yyxf1413/p/6104626.html