Skip to content

Instantly share code, notes, and snippets.

@pvguerra
Last active August 28, 2018 15:54
Show Gist options
  • Save pvguerra/4058704d7b6b55666d5d02691e9b4e3c to your computer and use it in GitHub Desktop.
Save pvguerra/4058704d7b6b55666d5d02691e9b4e3c to your computer and use it in GitHub Desktop.
Save DICOM data from DCM4CHEE directories
import dicom, glob, os

files = []
output_file = open('filename.csv', 'w')

print('Creating list...\n')
i = 0

for root, dirs, files in os.walk('/Users/pauloguerra/DICOM_TEST/'):
    if files:
        for file in files:
            files.append(os.path.join(root, file))
            # PyDICOM Dictionary -> https://github.com/pieper/pydicom/blob/master/source/dicom/_dicom_dict.py
            ds = dicom.read_file(os.path.join(root, file), force=True)
            try:
                study_id = ds.StudyID
                patient_id = ds.PatientID
                patient_name = ds.PatientName
                patient_sex = ds.PatientSex
                modality = ds.Modality
                study_desc = ds.StudyDescription
                study_date = (ds.StudyDate + ' ' + ds.StudyTime).rsplit('.')[0]
                series_number = str(ds.SeriesNumber)
                accession_number = str(ds.AccessionNumber)
                institution_name = ds.InstitutionName
            except:
                study_id = ''
                patient_id = ''
                patient_name = ''
                patient_sex = ''
                modality = ''
                study_desc = ''
                study_date = ''
                series_number = ''
                accession_number = ''
                institution_name = ''
                pass

            output_file.write(
                os.path.join(root, file).rsplit('/', 2)[0] + ';' +
                study_id + ';' +
                patient_id + ';' +
                patient_name + ';' +
                patient_sex + ';' +
                modality + ';' +
                study_desc + ';' +
                study_date + ';' +
                series_number + ';' +
                accession_number + ';' +
                institution_name + '\n'
            )

            i += 1
            print(str(i) + ' line(s)')
            break

output_file.close()
print('End')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment