Download degibbs/validation/scripts/make_slab.py from neurodeskorg/webapps: direct link, hf CLI and curl.
- Browser
- Download file 1.91 kB
-
https://huggingface.co/datasets/neurodeskorg/webapps/resolve/main/degibbs/validation/scripts/make_slab.py
- Command line
-
hf download hf://datasets/neurodeskorg/webapps/degibbs/validation/scripts/make_slab.py
-
curl -L -o make_slab.py https://huggingface.co/datasets/neurodeskorg/webapps/resolve/main/degibbs/validation/scripts/make_slab.py
1.91 kB
| """Cut the axial slab of ds005577 sub-107 AP DWI for degibbs/examples (issue #432). | |
| Usage: python -I make_slab.py <input-dir> <out-dir> <z0> <z1> | |
| Keeps every volume and the full 120 x 120 in-plane grid; keeps slices z0..z1-1. | |
| """ | |
| import json | |
| import sys | |
| from pathlib import Path | |
| import nibabel as nib | |
| import numpy as np | |
| src, out, z0, z1 = Path(sys.argv[1]), Path(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]) | |
| stem = "sub-107_dir-AP" | |
| img = nib.load(src / f"{stem}_dwi.nii.gz") | |
| slab = img.slicer[:, :, z0:z1, :] | |
| data = np.asanyarray(slab.dataobj) | |
| assert data.dtype == np.int16, data.dtype | |
| assert np.array_equal(data, np.asanyarray(img.dataobj)[:, :, z0:z1, :]) | |
| hdr = img.header.copy() | |
| hdr.set_data_shape(data.shape) | |
| # The descrip holds the acquisition time (Time=); keep the other items. | |
| items = [i for i in hdr["descrip"].tobytes().rstrip(b"\0").decode().split(";") if not i.startswith("Time=")] | |
| hdr["descrip"] = ";".join(items).encode() | |
| new = nib.Nifti1Image(data, slab.affine, hdr) | |
| new.set_qform(slab.affine, code=int(img.header["qform_code"])) | |
| new.set_sform(slab.affine, code=int(img.header["sform_code"])) | |
| new.header["scl_slope"] = np.nan | |
| new.header["scl_inter"] = np.nan | |
| out.mkdir(parents=True, exist_ok=True) | |
| nib.save(new, out / f"{stem}_desc-slab_dwi.nii") | |
| for ext in ("bval", "bvec"): | |
| (out / f"{stem}_desc-slab_dwi.{ext}").write_bytes((src / f"{stem}_dwi.{ext}").read_bytes()) | |
| text = (src / f"{stem}_dwi.json").read_text() | |
| side = json.loads(text) | |
| # Check that a dump gives the published bytes, so only the edited keys change. | |
| assert json.dumps(side, indent=4) == text, "the sidecar does not round-trip" | |
| side["SliceTiming"] = side["SliceTiming"][z0:z1] | |
| del side["B0FieldSource"] | |
| (out / f"{stem}_desc-slab_dwi.json").write_text(json.dumps(side, indent=4)) | |
| print("slab", data.shape, "affine", slab.affine.tolist()) | |
| print("descrip", new.header["descrip"]) | |
| print("SliceTiming", side["SliceTiming"]) | |