python struct.pack and write vs matlab fwrite
我正在尝试将这部分matlab代码移植到python
matlab
1 2 3 4 5 6 7 8 9 | function write_file(im,name) fp = fopen(name,'wb'); M = size(im); fwrite(fp,[M(1) M(2) M(3)],'int'); fwrite(fp,im(:),'float'); fclose(fp); |
其中
python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import struct import numpy as np def write_image(im, file_name): with open(file_name, 'wb') as f: l = im.shape[0]*im.shape[1]*im.shape[2] header = np.array([im.shape[0], im.shape[1], im.shape[2]]) header_bin = struct.pack("I"*3, *header) f.write(header_bin) im_bin = struct.pack("f"*l,*np.reshape(im, (l,1), order='F')) f.write(im_bin) f.close() |
其中
这对我来说没有意义,因为我正在15GB的RAM PC上运行该功能。 150MB的文件处理为何需要这么多的内存?
我很乐意使用其他方法,只要标题和数据列可以有两种格式即可。
无需使用
1 2 3 4 | def write_image(im, file_name): with open(file_name, 'wb') as f: np.array(im.shape).tofile(f) im.T.tofile(f) |