Skip to content

Instantly share code, notes, and snippets.

@FredLoney
Created September 25, 2013 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FredLoney/6693222 to your computer and use it in GitHub Desktop.
Save FredLoney/6693222 to your computer and use it in GitHub Desktop.
Creates links to DICOM files.
#!/usr/bin/env python
"""Creates links to DICOM files."""
import sys
import os
import argparse
import dicom
from dicom.filereader import InvalidDicomError
DCM_EXT = '.dcm'
"""The standard DICOM file extension."""
def main(argv=sys.argv):
# Parse the command line arguments.
parser = argparse.ArgumentParser()
parser.add_argument('source', help='the DICOM input directory',
metavar='DIR')
parser.add_argument('dest', help='the destination directory',
metavar='DIR')
args = parser.parse_args()
# Link the input DICOM files in the destination directory.
for src_file in dicom_files(args.source):
# The link name does not have spaces and has a .dcm extension.
_, src_base = os.path.split(src_file)
src_root, src_ext = os.path.splitext(src_base)
tgt_root = src_root.replace(' ', '_')
tgt_base = tgt_root + DCM_EXT
tgt_file = os.path.join(args.dest, tgt_base)
# Link the DICOM file in the destination directory.
os.symlink(src_file, tgt_file)
def dicom_files(path):
"""
Recursively iterates over the DICOM files in the given directory.
:param path: the directory containing DICOM files
:yield: each DICOM file in the directory
"""
# The full input directory path.
src_dir = os.path.abspath(path)
# Iterate over each file with a DICOM header.
for root, _, files in os.walk(src_dir):
for f in files:
# Skip hidden files.
if f.startswith('.'):
continue
# The file path.
src_file = os.path.join(root, f)
# If the file has a DICOM header, then we have a
# winner. Otherwise, ignore the file.
try:
# Read only the header.
dicom.read_file(src_file, defer_size=256,
stop_before_pixels=True)
yield src_file
except InvalidDicomError:
pass
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment