Instantly share code, notes, and snippets.

@eruffaldi /binload.m
Last active Jan 14, 2017

Embed
What would you like to do?
Loading binary tensor in matlab
function r = binload(fid,type,xsize,loadall,order)
% BINLOAD loads a binary tensor from file.
%
% r = binload(fid,type,xsize,loadall=1,order='column')
%
% This function loads tensor data from a file stored in binary form, it allows to reload
% data from numpy when saved with tofile. Also a raw image file can be loaeded. For example
% an RGB image stored by row is:
%
% A = binload(fid,'uint8',[height,width,3],'row')
%
% % but clearly
%
% A = binload(fid,'uint8',[3,width,height],'column')
%
% Arguments:
% - fid is the file identifier from fopen or a filename
% - type is the type of content compatible with fread (e.g. float64,int64...)
% - xsize is a vector of the data dimensions [s1,s2,...]
% - loadall forces to repeat the loading of elements of size xsize until the end of file, this menas
% that the output has an extra dimension sX. This dimension goes at the beginning or at the
% end of the xsize depending on the parameter order (see below)
% - order (bool) specifies the storage order 'column' or 'row', rember that Matlab is column,
% and numpy is row
%
% Note: when loadall=1; row major the repetition of xsize is placed outer as first dimension,
% while in col order it is inner and it is placed last.
%
% Verification: generate using ngrid and compare result with meshgrid
% interpolant
%
% Note: in comparison to fread we do not pass: precision, skip and
% machinefmt, but they can be added easily.
%
% Emanuele Ruffaldi 2016 <emanuele.ruffaldi@gmail.com>
if nargin == 3
loadall = 1;
end
if nargin < 5
order = 'column';
end
if ischar(fid)
fid = fopen(fid,'r');
end
nl = prod(xsize);
if loadall
r = fread(fid,[nl,Inf],type);
n = size(r,2);
r = r(:);
else
r = fread(fid,nl,type);
n = 0;
end
if n == 0
% we have exactly the content
if strcmp(order,'column')
r = reshape(r,xsize);
else
r = reshape(r,xsize(end:-1:1));
r = permute(r,length(xsize):-1:1);
end
else
% add one dimension
% we have n blocks with given columns:
% row order = blocks are outer
% col order = blocks are inner
if strcmp(order,'column')
r = reshape(r,[xsize n]);
else
xsize = [n xsize];
r = reshape(r,xsize(end:-1:1));
r = permute(r,length(xsize):-1:1);
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment