matcaffe的blob维度顺序

matcaffe是caffe的matlab接口。caffe本身是C++写的,其blob的维度顺序是[N,C,H,W],N表示batchSize,C表示channel数目,H表示feature map的Height, W则是width
而在matcaffe中,blob的顺序则是[W,H,C,N]。这是默认的顺序!所以在faster-rcnn的matlab代码中,当加载了proposal_test.prototxt后,发现其网络输入是:

input: "data"
input_dim: 1
input_dim: 3
input_dim: 224
input_dim: 224

一开始还奇怪,为啥在matlab中设定断点后输出网络的blob的结构是这样的:

K>> rpn_net.blobs('data').shape

ans =

   224   224     3     1

为啥不是[1,3,224,224]这个在prototxt中指定的顺序呢?虽然官方caffe的tutorial里也说了,matcaffe的blob顺序就是[W,H,C,N]

翻看matcaffe的代码:caffe_.cpp,找到370行左右:

// Usage: caffe_('blob_get_shape', hBlob)
static void blob_get_shape(MEX_ARGS) {
  mxCHECK(nrhs == 1 && mxIsStruct(prhs[0]),
      "Usage: caffe_('blob_get_shape', hBlob)");
  Blob<float>* blob = handle_to_ptr<Blob<float> >(prhs[0]);
  const int num_axes = blob->num_axes();
  mxArray* mx_shape = mxCreateDoubleMatrix(1, num_axes, mxREAL);
  double* shape_mem_mtr = mxGetPr(mx_shape);
  for (int blob_axis = 0, mat_axis = num_axes - 1; blob_axis < num_axes;
       ++blob_axis, --mat_axis) {
    shape_mem_mtr[mat_axis] = static_cast<double>(blob->shape(blob_axis));
  }
  plhs[0] = mx_shape;
}

其中最关键的是这个:

  for (int blob_axis = 0, mat_axis = num_axes - 1; blob_axis < num_axes;
       ++blob_axis, --mat_axis) {
    shape_mem_mtr[mat_axis] = static_cast<double>(blob->shape(blob_axis));
  }

这里面mat_axis这个索引是倒序的,从3到0;而blob_axis这个索引是正序增加的,从0到3。因此最终的结果是:matcaffe中的blob维度顺序和caffe中顺序完全相反,是[W,H,C,N]

原文地址:https://www.cnblogs.com/zjutzz/p/6275789.html