Last active
January 27, 2020 11:19
-
-
Save jstutters/e3372591ab2c0f2d164fb3f65c60a549 to your computer and use it in GitHub Desktop.
Calculate brain parenchymal fraction from a GIFv2 segmentation
This file contains hidden or 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
#!/usr/bin/env python3.7 | |
"""Calculate brain parenchymal fraction from a GIFv2 segmentation. | |
Intracranial volume (ICV) is grey-matter + CSF + white-matter. | |
Brain parenchymal fraction is (grey-matter + white-matter) / ICV. | |
""" | |
import os | |
import subprocess | |
import sys | |
import tempfile | |
def read_next_volume(lines): | |
return float(lines.pop(0).split("=")[1].strip()) | |
segmentation = sys.argv[1] | |
tfh, tf = tempfile.mkstemp(suffix=".nii.gz") | |
# flatten the segmentation to a single volume | |
flatten_command = [ | |
"seg_maths", | |
segmentation, | |
"-tpmax", | |
tf | |
] | |
subprocess.run(flatten_command) | |
# read volume of each label | |
volumes_command = [ | |
"seg_stats", | |
tf, | |
"-vl" | |
] | |
output = subprocess.run(volumes_command, capture_output=True, text=True) | |
# parse output | |
output_lines = output.stdout.split("\n") | |
output_lines = output_lines[2:] # discard header and background | |
csf = read_next_volume(output_lines) | |
cgm = read_next_volume(output_lines) | |
wm = read_next_volume(output_lines) | |
dgm = read_next_volume(output_lines) | |
brain_stem = read_next_volume(output_lines) | |
# do calculations | |
icv = cgm + dgm + wm + brain_stem + csf | |
bpf = (cgm + dgm + wm + brain_stem) / icv | |
print("Brain parenchymal fraction:", bpf) | |
# clean up | |
os.unlink(tf) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment