caffe:把图片转为lmdb或者leveldb文件(四)

来源:互联网 发布:linux can驱动 编辑:程序博客网 时间:2024/05/21 08:03

废话少说,让我们开始深度学习的第一步:制作自己的数据

1.了解文件存放

在caffe中,原作者给我们提供了一个convert_imageset.cpp.该文件放在caffe/tools/文件下,当我们把它编译了之后就会在build/tools/下面生成可执行文件。
convert_imageset.cpp

这里写图片描述

2.源代码convert_imageset.cpp

// This program converts a set of images to a lmdb/leveldb by storing them// as Datum proto buffers.// Usage://   convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME//   FLAGS:图片参数数组。在tensorflow中也有类似参数组//      --gray:是否依灰度的方式打开图片,默认为false,程序调用的是opencv里面的函数imread()来打开图片。//      --shuffle:是否要打乱图片的顺序,默认为flase//      --backend:转为什么样格式的数据,默认为lmdb。可选leveldb//      --resize_width or resize_height:改变图片的大小(要求所有的图片大小一样),调用opencv//      中的resize()函数对图像放大或者缩小,默认为0,不改变//      --check_size:检查图像的大小是否一样,默认为false//      --encoded:是否将图片编码放入到最终的数据中,default:false//      --encode_type:与前一个参数对应,将图片编码为哪一种图像//   ROOTFLODER/ 图片放的绝对路径,/home/inc/caffe/data/..//   LISTFILE:图片文件列表,经常使用txt文件,好处理,囧.. 一行一个图片//   DB_NAME:生成的db文件要放的目录//   说明:文件列表需要自己建立,保存为一个txt文件就ok// where ROOTFOLDER is the root folder that holds all the images, and LISTFILE// should be a list of files as well as their labels, in the format as//   subfolder1/file1.JPEG 7//   ....#include <algorithm>#include <fstream>  // NOLINT(readability/streams)#include <string>#include <utility>#include <vector>#include "boost/scoped_ptr.hpp"#include "gflags/gflags.h"#include "glog/logging.h"#include "caffe/proto/caffe.pb.h"#include "caffe/util/db.hpp"#include "caffe/util/format.hpp"#include "caffe/util/io.hpp"#include "caffe/util/rng.hpp"using namespace caffe;  // NOLINT(build/namespaces)using std::pair;using boost::scoped_ptr;DEFINE_bool(gray, false,    "When this option is on, treat images as grayscale ones");DEFINE_bool(shuffle, false,    "Randomly shuffle the order of images and their labels");DEFINE_string(backend, "lmdb",        "The backend {lmdb, leveldb} for storing the result");DEFINE_int32(resize_width, 0, "Width images are resized to");DEFINE_int32(resize_height, 0, "Height images are resized to");DEFINE_bool(check_size, false,    "When this option is on, check that all the datum have the same size");DEFINE_bool(encoded, false,    "When this option is on, the encoded image will be save in datum");DEFINE_string(encode_type, "",    "Optional: What type should we encode the image as ('png','jpg',...).");int main(int argc, char** argv) {#ifdef USE_OPENCV  ::google::InitGoogleLogging(argv[0]);  // Print output to stderr (while still logging)  FLAGS_alsologtostderr = 1;#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);  if (argc < 4) {    gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/convert_imageset");    return 1;  }  const bool is_color = !FLAGS_gray;  const bool check_size = FLAGS_check_size;  const bool encoded = FLAGS_encoded;  const string encode_type = FLAGS_encode_type;  std::ifstream infile(argv[2]);  std::vector<std::pair<std::string, int> > lines;  std::string line;  size_t pos;  int label;  while (std::getline(infile, line)) {    pos = line.find_last_of(' ');    label = atoi(line.substr(pos + 1).c_str());    lines.push_back(std::make_pair(line.substr(0, pos), label));  }  if (FLAGS_shuffle) {    // randomly shuffle data    LOG(INFO) << "Shuffling data";    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  scoped_ptr<db::DB> db(db::GetDB(FLAGS_backend));  db->Open(argv[3], db::NEW);  scoped_ptr<db::Transaction> txn(db->NewTransaction());  // 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);    }    status = ReadImageToDatum(root_folder + lines[line_id].first,        lines[line_id].second, resize_height, resize_width, is_color,        enc, &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));    txn->Put(key_str, out);    if (++count % 1000 == 0) {      // Commit db      txn->Commit();      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;}

3.一个生成图片清单的脚本文件

在~/caffe/examples/images/下新建一个脚本文件,取名inc_filelist.sh

使用cat.jpg和另一张fish_bike.jpg表示两个类别。# /usr/bin/env shDATA=examples/imagesecho "Create inc_train.txt..."rm -rf $DATA/inc_train.txtfind $DATA -name *cat.jpg | cut -d '/' -f3 | sed "s/$/ 1/">>$DATA/inc_train.txtfind $DATA -name *bike.jpg | cut -d '/' -f3 | sed "s/$/ 2/">>$DATA/tmp.txtcat $DATA/tmp.txt>>$DATA/inc_train.txtrm -rf $DATA/tmp.txtecho "Done.."
执行前给文件加执行的chmod u+x inc_filelist.sh   解释如下:DATA:是在当前目录下开始的文件目录rm:linux 删除命令,在images/目录下如果有inc_train.txt 文件,就山删除find:在images/目录下找name为cat.jpg的文件。cut:截取路径。sed: 在每行的最后面加上标注。将找到的*cat.jpg文件加入标注为1,找到的*bike.jpg文件加入标注为2cat:将两个txt文件合并为一个文件。结果截图:

这里写图片描述

 - *cat.jpg为什么用*?        - 这样可以对所有cat的图片进行编号。

4.写一个脚本生成lmdb文件

在images/下新建一个create_lmdb.sh文件,内容如下:
#!/usr/bin/env shDATA=examples/imagesrm -rf $DATA/inc_train_lmdbbuild/tools/convert_imageset --shuffle --resize_height=256 --resize_width=256 \/home/inc/caffe/examples/images/ $DATA/inc_train.txt  $DATA/inc_train_lmdb

运行脚本,在images文件目录下生成lmdb文件。

待续。。。

0 0
原创粉丝点击