Skip to content

Commit be6f31f

Browse files
committed
A python script to wrap image read and write for Nifti Images.
1 parent f72525e commit be6f31f

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

WrapImage/nifti_wrapper.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import argparse
2+
import json
3+
import os
4+
import nibabel as nib
5+
import numpy as np
6+
7+
def read_nifti_4d(input_file):
8+
"""
9+
For reading the 4d nifti image
10+
"""
11+
nifti_img = nib.load(input_file)
12+
return nifti_img.get_fdata()
13+
14+
def read_json_file(json_file):
15+
"""
16+
For reading the json file
17+
"""
18+
19+
if not os.path.exists(json_file):
20+
raise FileNotFoundError(f"File '{json_file}' not found.")
21+
22+
with open(json_file, "r") as f:
23+
try:
24+
json_data = json.load(f)
25+
except json.JSONDecodeError as e:
26+
raise ValueError(f"Error decoding JSON in file '{json_file}': {e}")
27+
28+
return json_data
29+
30+
def save_nifti_3d(data, output_file):
31+
"""
32+
For saving the 3d nifti images of the output of the algorithm
33+
"""
34+
output_img = nib.Nifti1Image(data, np.eye(4))
35+
nib.save(output_img, output_file)
36+
37+
if __name__ == "__main__":
38+
parser = argparse.ArgumentParser(description="Read a 4D NIfTI phantom file along with BIDS JSON, b-vector, and b-value files.")
39+
parser.add_argument("input_file", type=str, help="Path to the input 4D NIfTI file.")
40+
parser.add_argument("bids_dir", type=str, help="Path to the BIDS directory.")
41+
parser.add_argument("--algorithm", type=str, choices=["algorithm1", "algorithm2"], default="algorithm1", help="Select the algorithm to use.")
42+
parser.add_argument("algorithm_args", nargs=argparse.REMAINDER, help="Additional arguments for the algorithm.")
43+
44+
args = parser.parse_args()
45+
46+
try:
47+
# Read the 4D NIfTI file
48+
data = read_nifti_4d(args.input_file)
49+
50+
# Construct the full paths for the JSON, b-vector, and b-value files
51+
json_file = os.path.join(args.bids_dir, "dataset_description.json")
52+
bvec_file = os.path.join(args.bids_dir, "bvecs.json")
53+
bval_file = os.path.join(args.bids_dir, "bvals.json")
54+
55+
# Read the JSON, b-vector, and b-value files
56+
json_data = read_json_file(json_file)
57+
bvecs = read_json_file(bvec_file)
58+
bvals = read_json_file(bval_file)
59+
60+
# Pass additional arguments to the algorithm
61+
# Passing the values to the selectect algorithm and saving it
62+
63+
except Exception as e:
64+
print(f"Error: {e}")

0 commit comments

Comments
 (0)