Skip to content

Instantly share code, notes, and snippets.

@jpeoples
Last active September 8, 2023 19:52
Show Gist options
  • Save jpeoples/eb5dade1da21b5c452ac324d564b5068 to your computer and use it in GitHub Desktop.
Save jpeoples/eb5dade1da21b5c452ac324d564b5068 to your computer and use it in GitHub Desktop.
Accessing Dates and DICOM headers on XNAT
import xnat
with xnat.connect(XNAT_SERVER_URL, MY_ALIAS_TOKEN, MY_ALIAS_TOKEN_SECRET) as conn:
project = conn.projects[MY_PROJECT_ID]
for sub in project.subjects.values():
for exp in sub.experiments.values():
for scan in exp.scans.values():
print(f"{sub.label} - {exp.label} - {exp.date} - {exp.time} - {scan.id} - {scan.start_time}")

Using the same scan object there are two methods: dicom_dump and read_dicom.

If you do

scan.read_dicom()

you get a pydicom object with all the headers (and there is an argument for whether to include pixel data or not) https://xnat.readthedocs.io/en/latest/xnat.html#xnat.mixin.ImageScanData.read_dicom

If you want only a couple header values, use dicom_dump, which will return a list of dicts representing the headers

scan.dicom_dump([“StudyDate”, “SeriesDate”])

sample output:

[{'tag1': '(0008,0020)', 'vr': 'DA', 'value': '20070917', 'tag2': '', 'desc': 'Study Date'}, {'tag1': '(0008,0021)', 'vr': 'DA', 'value': '20070917', 'tag2': '', 'desc': 'Series Date'}]

Doc: https://xnat.readthedocs.io/en/latest/xnat.html#xnat.mixin.ImageScanData.dicom_dump

The input is a list of strings – either the tag keywords like above (these are the same used in pydicom) or the tag number in “GGGGEEEE” format (for group and element). The equivalent call to the above would be

scan.dicom_dump([“00080020”, “00080021”])

Finally, note that a scan consists of (potentially) multiple dicom files. There is no way to get the header values for all files from the XNAT api as far as I can tell. From what I recall, it picks a random file to get the header from. For headers that are consistent across an entire series it doesn’t matter (like the dates), but for something that varies per image, it is less useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment