我有一个10位值的数组,打包成连续的8位整数。在python中,我使用以下命令解压缩这些文件:
def unpack_10bit(data, nx, ny):
packed = np.frombuffer(data, dtype='uint8').astype('uint16')
unpacked = np.zeros([ny, nx], dtype='uint16')
unpacked.flat[::4] = (packed[::5] << 2) | (packed[1::5] >> 6)
unpacked.flat[1::4] = ((packed[1::5] & 0b00111111) << 4) | (packed[2::5] >> 4)
unpacked.flat[2::4] = ((packed[2::5] & 0b00001111) << 6) | (packed[3::5] >> 2)
unpacked.flat[3::4] = ((packed[3::5] & 0b00000011) << 8) | packed[4::5]
return unpacked
在MATLAB中,我是这样做的,但是速度很慢:
dat = fread(f,imsize,'uint8'); % read in data
tmp = dec2bin(dat);
bits = reshape(tmp',[1,length(dat)*8]); % reshape into long vector
unpacked = zeros(nx,ny,'uint16'); % initialise
for k = 1:(nx*ny) % for each point in the array
unpacked(k) = bin2dec(bits((k-1)*10+1 : 10*k)); % convert the 10 bits into a decimal
end
关于改善MATLAB版本性能的任何建议吗?
答案 0 :(得分:0)
此解决方案是:
packed= fread(f,h.nx*h.ny*1.25,'uint16');
unpacked= zeros(h.nx,h.ny,'uint16');
unpacked(1:4:end) = bitor(bitshift(packed(1:5:end),2),bitshift(packed(2:5:end),-6));
unpacked(2:4:end) = bitor(bitshift(bitand(packed(2:5:end),63),4),bitshift(packed(3:5:end),-4));
unpacked(3:4:end) = bitor(bitshift(bitand(packed(3:5:end),15),6),bitshift(packed(4:5:end),-2));
unpacked(4:4:end) = bitor(bitshift(bitand(packed(4:5:end),3),8),packed(5:5:end));
花费0.23秒解开260万个值如果有人对提高速度有建议,那就太好了!