File size: 1,914 Bytes
d950cc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""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"])