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