Created
May 9, 2022 11:22
-
-
Save satra/28b797fa858ff5c603d77f1cc2241098 to your computer and use it in GitHub Desktop.
Convert Nifti to NGFF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import numpy as np | |
import nibabel as nb | |
import zarr | |
from numcodecs import Blosc | |
from ome_zarr.writer import write_multiscale | |
from skimage.transform import pyramid_gaussian | |
img = nb.load("sub-S01_T2w.nii.gz") | |
data = img.get_fdata() | |
data5d = data.swapaxes(0,2)[None, None, :, :, :] | |
pyramid = [val for val in pyramid_gaussian(data5d, max_layer=4, downscale=2, preserve_range=True)] | |
storage_options = [] | |
for key in range(len(pyramid)): | |
chunkdim = min(64, 2**math.floor(math.log2(min([val for val in pyramid[key].shape if val > 1])))) | |
chunks = (1, 1, chunkdim, chunkdim, chunkdim) | |
storage_options.append( | |
{ | |
"chunks": chunks, | |
"compressor": Blosc(cname="zstd", clevel=5, shuffle=Blosc.SHUFFLE), | |
} | |
) | |
for idx, val in enumerate(pyramid): | |
pyramid[idx] = np.round(val).astype(np.uint16) | |
ngff_file = "sub-S01_T2w.ngff" | |
store = zarr.NestedDirectoryStore(ngff_file) | |
root = zarr.group(store=store, overwrite=True) | |
write_multiscale( | |
pyramid, | |
group=root, | |
axes=["t", "c", "z", "y", "x"], | |
storage_options=storage_options, | |
) | |
multiscales = root.attrs["multiscales"] | |
for level in range(len(pyramid)): | |
multiscales[0]["datasets"][level]["coordinateTransformations"][0]["scale"] = [1.0, 1.0, (2**level)*0.05, (2**level)*0.05, (2**level)*0.05] | |
root.attrs["multiscales"] = multiscales | |
for i in range(5): | |
root[i].attrs['_ARRAY_DIMENSIONS'] = ['time', 'channel', 'z', 'y', 'x'] | |
zarr.consolidate_metadata(store) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment