File size: 1,019 Bytes
a4ba047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Mean of the b < 50 volumes as float32 NIfTI on the DWI grid (as noddi's meanVolumes).

Usage: python -I mean_b0.py DWI.nii.gz BVAL OUT.nii
"""

import sys

import nibabel as nb
import numpy as np

dwi_path, bval_path, out_path = sys.argv[1:4]
img = nb.load(dwi_path)
bvals = np.loadtxt(bval_path)
b0 = np.flatnonzero(bvals < 50)
data = np.asarray(img.dataobj)
# float32 accumulation, volume order, then divide: the order of noddi's meanVolumes.
mean = np.zeros(img.shape[:3], dtype=np.float32)
for v in b0:
    mean += data[..., v].astype(np.float32)
mean /= np.float32(len(b0))
hdr = img.header.copy()
hdr.set_data_dtype(np.float32)
hdr.set_data_shape(mean.shape)
out = nb.Nifti1Image(mean, img.affine, hdr)
out.header.set_slope_inter(1.0, 0.0)
out.header.set_qform(img.header.get_qform(), code=int(img.header["qform_code"]))
out.header.set_sform(img.header.get_sform(), code=int(img.header["sform_code"]))
out.to_filename(out_path)
print(f"b0 volumes: {b0.tolist()} mean range {mean.min():.1f}..{mean.max():.1f}")