1+ classdef Blob < handle
2+ % Wrapper class of caffe::Blob in matlab
3+
4+ properties (Access = private )
5+ hBlob_self
6+ end
7+
8+ methods
9+ function self = Blob(hBlob_blob )
10+ CHECK(is_valid_handle(hBlob_blob ), ' invalid input handle' );
11+
12+ % setup self handle and attributes
13+ self.hBlob_self = hBlob_blob ;
14+ end
15+ function shape = shape(self )
16+ shape = caffe_(' blob_get_shape' , self .hBlob_self);
17+ end
18+ function reshape(self , shape )
19+ shape = self .check_and_preprocess_shape(shape );
20+ caffe_(' blob_reshape' , self .hBlob_self, shape );
21+ end
22+ function data = get_data(self )
23+ data = caffe_(' blob_get_data' , self .hBlob_self);
24+ end
25+ function set_data(self , data )
26+ data = self .check_and_preprocess_data(data );
27+ caffe_(' blob_set_data' , self .hBlob_self, data );
28+ end
29+ function diff = get_diff(self )
30+ diff = caffe_(' blob_get_diff' , self .hBlob_self);
31+ end
32+ function set_diff(self , diff )
33+ diff = self .check_and_preprocess_data(diff );
34+ caffe_(' blob_set_diff' , self .hBlob_self, diff );
35+ end
36+ end
37+
38+ methods (Access = private )
39+ function shape = check_and_preprocess_shape(~, shape )
40+ CHECK(isempty(shape ) || isnumeric(shape ) && isrow(shape ), ...
41+ ' shape must be a integer row vector' );
42+ shape = double(shape );
43+ end
44+ function data = check_and_preprocess_data(self , data )
45+ CHECK(isnumeric(data ), ' data or diff must be numeric types' );
46+ self .check_data_size_matches(data )
47+ data = single(data );
48+ end
49+ function check_data_size_matches(self , data )
50+ % check whether size of data matches shape of this blob
51+ % note: matlab arrays always have at least 2 dimensions. To compare
52+ % shape between size of data and shape of this blob, extend shape of
53+ % this blob to have at least 2 dimensions
54+ data_size = size(data );
55+ self_shape_extended = self .shape;
56+ if isempty(self_shape_extended )
57+ % target blob is a scalar (0 dim)
58+ self_shape_extended = [1 , 1 ];
59+ elseif isscalar(self_shape_extended )
60+ % target blob is a vector (1 dim)
61+ self_shape_extended = [self_shape_extended , 1 ];
62+ end
63+ is_matched = (length(self_shape_extended ) == length(data_size )) ...
64+ && all(self_shape_extended == data_size );
65+ CHECK(is_matched , ...
66+ sprintf(' %s , data size: [ %s ], blob shape: [ %s ]' , ...
67+ ' data size does not match blob shape' , ...
68+ sprintf(' %d ' , data_size ), sprintf(' %d ' , self_shape_extended )));
69+ end
70+ end
71+ end
0 commit comments