-
Notifications
You must be signed in to change notification settings - Fork 2
/
readNPYheader.m
67 lines (46 loc) · 2.1 KB
/
readNPYheader.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
function [arrayShape, dataType, fortranOrder, littleEndian, totalHeaderLength, npyVersion] = readNPYheader(filename)
% function [arrayShape, dataType, fortranOrder, littleEndian, ...
% totalHeaderLength, npyVersion] = readNPYheader(filename)
%
% parse the header of a .npy file and return all the info contained
% therein.
%
% Based on spec at http://docs.scipy.org/doc/numpy-dev/neps/npy-format.html
fid = fopen(filename);
% verify that the file exists
if (fid == -1)
if ~isempty(dir(filename))
error('Permission denied: %s', filename);
else
error('File not found: %s', filename);
end
end
try
dtypesMatlab = {'uint8','uint16','uint32','uint64','int8','int16','int32','int64','single','double', 'logical'};
dtypesNPY = {'u1', 'u2', 'u4', 'u8', 'i1', 'i2', 'i4', 'i8', 'f4', 'f8', 'b1'};
magicString = fread(fid, [1 6], 'uint8=>uint8');
if ~all(magicString == [147,78,85,77,80,89])
error('readNPY:NotNUMPYFile', 'Error: This file does not appear to be NUMPY format based on the header.');
end
majorVersion = fread(fid, [1 1], 'uint8=>uint8');
minorVersion = fread(fid, [1 1], 'uint8=>uint8');
npyVersion = [majorVersion minorVersion];
headerLength = fread(fid, [1 1], 'uint16=>uint16');
totalHeaderLength = 10+headerLength;
arrayFormat = fread(fid, [1 headerLength], 'char=>char');
% to interpret the array format info, we make some fairly strict
% assumptions about its format...
r = regexp(arrayFormat, '''descr''\s*:\s*''(.*?)''', 'tokens');
dtNPY = r{1}{1};
littleEndian = ~strcmp(dtNPY(1), '>');
dataType = dtypesMatlab{strcmp(dtNPY(2:3), dtypesNPY)};
r = regexp(arrayFormat, '''fortran_order''\s*:\s*(\w+)', 'tokens');
fortranOrder = strcmp(r{1}{1}, 'True');
r = regexp(arrayFormat, '''shape''\s*:\s*\((.*?)\)', 'tokens');
shapeStr = r{1}{1};
arrayShape = str2num(shapeStr(shapeStr~='L'));
fclose(fid);
catch me
fclose(fid);
rethrow(me);
end