Skip to content

Instantly share code, notes, and snippets.

@effigies
Created January 9, 2021 16:00
Show Gist options
  • Save effigies/badcf6b6e7740ccbf8b115197268778d to your computer and use it in GitHub Desktop.
Save effigies/badcf6b6e7740ccbf8b115197268778d to your computer and use it in GitHub Desktop.
Comparing sizes of identical .nii.gz data saved as int16, float32, float64
import os
import nibabel as nb
import numpy as np
# Create an image with a "plausible" range of fMRI values
img = nb.Nifti1Image(np.random.uniform(500, 2000, (256,256,256,1)), np.eye(4))
# Verify numpy's giving us float64
assert img.get_data_dtype() == np.float64
# Quantize to 16 bits and reload
img.set_data_dtype(np.int16)
img.to_filename('int16.nii.gz')
del img
img = nb.load('int16.nii.gz')
# Save identical data with different representation
img.set_data_dtype(np.float32)
img.to_filename('float32.nii.gz')
img.set_data_dtype(np.float64)
img.to_filename('float64.nii.gz')
# Check that we did save the same data...
assert np.allclose(img.get_fdata(), nb.load('float32.nii.gz').get_fdata())
assert np.allclose(img.get_fdata(), nb.load('float64.nii.gz').get_fdata())
# Check sizes
def print_size(fname):
stat = os.stat(fname)
print(f"{fname}: {stat.st_size // 1048576}MiB")
print_size("int16.nii.gz")
print_size("float32.nii.gz")
print_size("float64.nii.gz")
int16.nii.gz: 32MiB
float32.nii.gz: 53MiB
float64.nii.gz: 99MiB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment