利用matlab读取.npy文件的代码(另一种简单方法直接用python保存为.mat,matlab读取时候就不需要这么多代码)

利用matlab 读取.npy文件
(https://github.com/kwikteam/npy-matlab/blob/master/npy-matlab/readNPYheader.m)
下面展示代码

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 existsif (fid == -1)    if ~isempty(dir(filename))        error('Permission denied: %s', filename);    else        error('File not found: %s', filename);    endend
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
方法二  直接用python将.npy转换为.mat
from scipy import io
mat = np.load('light_light.npy')
io.savemat('light_light.mat', {'light_light': mat})

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值