Created
June 17, 2014 11:15
-
-
Save maedoc/eb754394300e1c75d7b1 to your computer and use it in GitHub Desktop.
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
""" | |
Find DICOM runs and scans, and print first image (e.g. for launching FreeSurfer) | |
""" | |
import re | |
import os | |
import sys | |
path = sys.argv[1] | |
dicom_dir = re.compile('([A-Z]+)(\d+)') | |
runs = {} | |
for root, _, files in os.walk(path, followlinks=True): | |
parts = root.split(os.path.sep) | |
if len(parts) > 1: | |
m1, m2 = map(dicom_dir.match, parts[-2:]) | |
if m1 and m2 and files: | |
base = os.path.sep.join(parts[:-1]) | |
if base not in runs: | |
runs[base] = [] | |
runs[base].append({ | |
'name': parts[-1], | |
'count': len(files), | |
'first': sorted(files)[0] | |
}) | |
# sort runs by shortest base path | |
run_path, run_scans = sorted(runs.items(), key=lambda (k, v): len(k))[0] | |
# sort scans by image count | |
scan = sorted(run_scans, key=lambda scan: scan['count'])[-1] | |
# build abs path to first image | |
parts = run_path, scan['name'], scan['first'] | |
first_image = os.path.abspath(os.path.join(*parts)) | |
assert os.path.exists(first_image) | |
print first_image |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment