OpenCV提供了resize函数来改变图像的大小,函数原型如下:
先解释一下各个参数的意思:
src:输入,原图像,即待改变大小的图像;
dst:输出,改变大小之后的图像,这个图像和原图像具有相同的内容,只是大小和原图像不一样而已;
dsize:输出图像的大小。如果这个参数不为0,那么就代表将原图像缩放到这个Size(width,height)指定的大小;如果这个参数为0,那么原图像缩放之后的大小就要通过下面的公式来计算:
dsize = Size(round(fx*src.cols), round(fy*src.rows))
其中,fx和fy就是下面要说的两个参数,是图像width方向和height方向的缩放比例。
fx:width方向的缩放比例,如果它是0,那么它就会按照(double)dsize.width/src.cols来计算;
fy:height方向的缩放比例,如果它是0,那么它就会按照(double)dsize.height/src.rows来计算;
interpolation:这个是指定插值的方式,图像缩放之后,肯定像素要进行重新计算的,就靠这个参数来指定重新计算像素的方式,有以下几种:
- INTER_NEAREST - 最邻近插值
- INTER_LINEAR - 双线性插值,如果最后一个参数你不指定,默认使用这种方法
- INTER_AREA - resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method.
- INTER_CUBIC - 4x4像素邻域内的双立方插值
- INTER_LANCZOS4 - 8x8像素邻域内的Lanczos插值
使用注意事项:
1. dsize和fx/fy不能同时为0,要么你就指定好dsize的值,让fx和fy空置直接使用默认值,就像
resize(img, imgDst, Size(30,30));
要么你就让dsize为0,指定好fx和fy的值,比如fx=fy=0.5,那么就相当于把原图两个方向缩小一倍!
2. 至于最后的插值方法,正常情况下使用默认的双线性插值就够用了。
几种常用方法的效率是:最邻近插值>双线性插值>双立方插值>Lanczos插值;
但是效率和效果成反比,所以根据自己的情况酌情使用。
3. 正常情况下,在使用之前dst图像的大小和类型都是不知道的,类型从src图像继承而来,大小也是从原图像根据参数计算出来。但是如果你事先已经指定好dst图像的大小,那么你可以通过下面这种方式来调用函数:
caffe,将数据转换为lmdb/leveldb的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
- //
- // 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
- // ....
- //这份代码是caffe提供的,在caffe里的tools文件目录里,用于将图像数据转换为lmdb或者leveldb格式。
- //使用方法: 在shell 脚本里写入以下代码
- // convert_imageset [参数设置] [图像存放路径] [图像的LISTFILE文件] [转换后数据存储位置]
- //例子:
- // $TOOLS/convert_imageset \
- // --resize_height=$RESIZE_HEIGHT \
- // --resize_width=$RESIZE_WIDTH \
- // --shuffle \
- // $VAL_DATA_ROOT \
- // $IMAGE_LIST_ROOT/val_2.list \
- // $ROOT_LMDB/val
- #include <algorithm> //输出数组的内容,对数组进行升幂排序,反转数组内容等操作
- #include <fstream> // NOLINT(readability/streams)
- #include <string>
- #include <utility> //定义了一个pair类型,pair类型用于存储一对数据
- #include <vector>
- #include "boost/scoped_ptr.hpp" //智能指针头文件
- #include "gflags/gflags.h"
- #include "glog/logging.h" //glog头文件,google的开源日志系统
- #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", //数据存储格式,默认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); //调用解析命令行函数
- //argc,传给main()的命令行参数个数
- //argv:字符串数组
- //argc,argv就是main函数的入口参数,因为这个函数会改变他们的值,所以都是以指针传入
- //第三个参数被称为remove_flags,若为true,ParseCommandLineFlags会从argv中移除标识和它们的参数,相应减少argc的值。然后 argv 只保留命令行参数;若为false,ParseCommandLineFlags会保留argc不变,但将会重新调整它们的顺序,使得标识在前面
- 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;
- //argv第二个参数为图像的LISTFILE
- std::ifstream infile(argv[2]);
- std::vector<std::pair<std::string, int> > lines;
- std::string filename;
- int label;
- //存储文件名和标注
- while (infile >> filename >> label) {
- lines.push_back(std::make_pair(filename, label));
- }
- //乱序存储
- if (FLAGS_shuffle) {
- // randomly shuffle data
- LOG(INFO) << "Shuffling data"; //打印,类似于C++的stream
- 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); //argv第三个参数为db存储位置
- scoped_ptr<db::Transaction> txn(db->NewTransaction());
- // Storing to db
- std::string root_folder(argv[1]); //argv第一个参数为图像路径
- Datum datum;
- int count = 0;
- int data_size = 0;
- bool data_size_initialized = false;
- //将LISTFILE里的记录,逐条转换为lmdb/leveldb格式
- 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; //list 里的第一个参数,即为文件的路径名
- 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;
- }
ReadImageToDatum 函数:
读入图像到Datum
ReadImageToDatum函数又是调用ReadImageToCVMat函数读入图像和resize的宽高进行缩放的
ReadImageToCVMat 函数:
以cvMat格式读入图像
可以看出caffe底层是使用opencv的默认双线性差值的resize方法,通过比较可知opencv的resize属性只有area后的图像质量较好,保存信息较为