to_gii.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import itertools
  2. import os
  3. from pathlib import Path
  4. import subprocess as sp
  5. import sys
  6. FS_HOME = os.environ["FREESURFER_HOME"]
  7. FSAVERAGE_DENSITY = {
  8. "fsaverage5": "10k",
  9. "fsaverage6": "41k",
  10. "fsaverage": "164k",
  11. }
  12. def invalid_fs():
  13. assert FS_HOME, "FreeSurfer not installed"
  14. try:
  15. proc = sp.run(("mri_convert", "-h"), stdout=sp.DEVNULL, stderr=sp.STDOUT)
  16. except OSError:
  17. print("FreeSurfer installation not found.")
  18. sys.exit(1)
  19. return proc.returncode
  20. def convert2gii(filename, hemi, den, suffix):
  21. outfile = f"tpl-fsaverage_hemi-{hemi}_den-{den}_{suffix}.shape.gii"
  22. cmd = ["mri_convert", str(filename), outfile]
  23. print(f"Running {' '.join(cmd)}")
  24. proc = sp.run(cmd, stdout=sp.PIPE)
  25. return proc
  26. if __name__ == "__main__":
  27. if invalid_fs():
  28. print("Error running FreeSurfer's ``mri_convert``.")
  29. sys.exit(1)
  30. FS_TEMPLATES_PATH = Path(FS_HOME) / "subjects"
  31. for template in ("fsaverage", "fsaverage5", "fsaverage6"):
  32. den = FSAVERAGE_DENSITY[template]
  33. template_curv = (FS_TEMPLATES_PATH / template).glob("surf/*h.curv")
  34. template_sulc = (FS_TEMPLATES_PATH / template).glob("surf/*h.sulc")
  35. for f in itertools.chain(template_curv, template_sulc):
  36. hemi = "L" if f.name.startswith('l') else "R"
  37. suffix = f.suffix.lstrip('.')
  38. convert2gii(f, hemi, den, suffix)