Skip to content

Instantly share code, notes, and snippets.

Created September 25, 2013 00:20
Show Gist options
  • 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',
parser.add_argument('dest', help='the destination directory',
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('.'):
# 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.
# Read only the header.
dicom.read_file(src_file, defer_size=256,
yield src_file
except InvalidDicomError:
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment