Skip to content

Commit 552a84a

Browse files
zoharbyzoharby
zoharby
authored and
zoharby
committed
Add a caffe.io.write_mean function to the MATLAB interface
Useful for exporting models from MATLAB (e.g. MatConvNet) to Caffe
1 parent 4f8775c commit 552a84a

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

matlab/+caffe/io.m

+8
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,13 @@
2929
CHECK_FILE_EXIST(mean_proto_file);
3030
mean_data = caffe_('read_mean', mean_proto_file);
3131
end
32+
function write_mean(mean_data, mean_proto_file)
33+
% write_mean(mean_data, mean_proto_file)
34+
% write image mean data to binaryproto file
35+
% mean_data should be W x H x C with BGR channels
36+
CHECK(ischar(mean_proto_file), 'mean_proto_file must be a string');
37+
CHECK(isa(mean_data, 'single'), 'mean_data must be a SINGLE matrix');
38+
caffe_('write_mean', mean_data, mean_proto_file);
39+
end
3240
end
3341
end

matlab/+caffe/private/caffe_.cpp

+24
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,29 @@ static void read_mean(MEX_ARGS) {
478478
mxFree(mean_proto_file);
479479
}
480480

481+
// Usage: caffe_('write_mean', mean_data, mean_proto_file)
482+
static void write_mean(MEX_ARGS) {
483+
mxCHECK(nrhs == 2 && mxIsSingle(prhs[0]) && mxIsChar(prhs[1]),
484+
"Usage: caffe_('write_mean', mean_data, mean_proto_file)");
485+
char* mean_proto_file = mxArrayToString(prhs[1]);
486+
int ndims = mxGetNumberOfDimensions(prhs[0]);
487+
mxCHECK(ndims >= 2 && ndims <= 3, "mean_data must have at 2 or 3 dimensions");
488+
const mwSize *dims = mxGetDimensions(prhs[0]);
489+
int width = dims[0];
490+
int height = dims[1];
491+
int channels;
492+
if (ndims == 3)
493+
channels = dims[2];
494+
else
495+
channels = 1;
496+
Blob<float> data_mean(1, channels, height, width);
497+
mx_mat_to_blob(prhs[0], &data_mean, DATA);
498+
BlobProto blob_proto;
499+
data_mean.ToProto(&blob_proto, false);
500+
WriteProtoToBinaryFile(blob_proto, mean_proto_file);
501+
mxFree(mean_proto_file);
502+
}
503+
481504
/** -----------------------------------------------------------------
482505
** Available commands.
483506
**/
@@ -515,6 +538,7 @@ static handler_registry handlers[] = {
515538
{ "get_init_key", get_init_key },
516539
{ "reset", reset },
517540
{ "read_mean", read_mean },
541+
{ "write_mean", write_mean },
518542
// The end.
519543
{ "END", NULL },
520544
};

0 commit comments

Comments
 (0)