[1] 展示了用 scipy.io.savemat 压缩数据的写法,且在压缩二进制数据时优于 numpy.packbits。其实 numpy.savez_compressed 也能压缩,本文记录用之存压缩数据的写法,并比较其与 numpy.save 和 scipy.io.savemat 压缩效果。
用到 TotalSegmentator[2] 的数据,一些预处理见 [3]。
Code
import os, os.path as osp
import numpy as np
import scipy.io as sio
import nibabel as nibP = "totalsegmentator/data"# nibabel 读 .nii.gz
img = nib.load(osp.join(P, "s0000", "ct.nii.gz"))
print(img.shape) # (294, 192, 179)
lab = nib.load(osp.join(P, "s0000", "comb_label.nii.gz"))
print(lab.shape) # (294, 192, 179)
# 转为 numpy 数组
img_np = img.get_fdata().astype(np.float32)
lab_np = (lab.get_fdata() > 0.5).astype(np.uint8)# numpy.save
np.save("img_np", img_np)
np.save("lab_np", lab_np)# numpy.savez_compressed
np.savez_compressed("img", img=img_np)
np.savez_compressed("lab", lab=lab_np)
np.savez_compressed("img_lab", img=img_np, lab=lab_np)# scipy.io.savemat + do_compression
sio.savemat("img.mat", {"img": img_np}, do_compression=True)
sio.savemat("lab.mat", {"lab": lab_np}, do_compression=True)
sio.savemat("img_lab.mat", {"img": img_np, "lab": lab_np}, do_compression=True)
然后 ls -lh
查看各文件大小:
-rw-r--r-- 1 itom Research 39M Jun 17 10:11 img_np.npy
-rw-r--r-- 1 itom Research 9.7M Jun 17 10:11 lab_np.npy-rw-r--r-- 1 itom Research 13M Jun 17 10:11 img.npz
-rw-r--r-- 1 itom Research 101K Jun 17 10:11 lab.npz
-rw-r--r-- 1 itom Research 13M Jun 17 10:11 img_lab.npz-rw-r--r-- 1 itom Research 13M Jun 17 10:11 img.mat
-rw-r--r-- 1 itom Research 101K Jun 17 10:11 lab.mat
-rw-r--r-- 1 itom Research 13M Jun 17 10:11 img_lab.mat
结论:numpy.savez_compressed 与 scipy.io.savemat 压缩效果一样。
References
- 压缩二进制numpy数据
- wasserth/TotalSegmentator
- iTomxy/data/totalsegmentator