How to read all DICOM attributes/tags with pydicom?

Viewed 4741

I'm trying to get a list of all the attributes (tags) of a given DICOM instance using pydicom.

The list should include the attribute key/id, its vr, the value, and also the corresponding name.

For example:

Tag: (2,0)
VR: UL
Name: File Meta Information Group Length
Value: 246

I'd like to get some guidance on how to obtain this information since I can't find anything useful in the pydicom docs.

My code is the following:

import pydicom
from io import BytesIO

dicom_data = await client.download_dicom_file(image_id)
data = pydicom.dcmread(BytesIO(dicom_data))
2 Answers

To get all tags, you just iterate over all elements in a dataset. Here is an example in the documentation that does that. It boils down to:

from pydicom import dcmread

ds = dcmread(file_name)
for element in ds:
    print(element)

The example also shows how to handle sequences (by recursively iterating the sequence items). Here is a simple example for handling sequence items using just the string representation of the elements:

def show_dataset(ds, indent):
    for elem in ds:
        if elem.VR == "SQ":
            indent += 4 * " "
            for item in elem:
                show_dataset(item, indent)
            indent = indent[4:]
        print(indent + str(elem))

def print_dataset(file_name):
    ds = dcmread(file_name)
    show_dataset(ds, indent="")

If you want to print your own representation of the data elements, you can access the element attributes. Each element is a DataElement, which has the information you need:

>>> from pydicom import dcmread
>>> ds = dcmread("ct_small.dcm")  # from the test data
>>> len(ds)
258
>>> element = ds[0x00080008]
>>> element
(0008, 0008) Image Type                          CS: ['ORIGINAL', 'PRIMARY', 'AXIAL']
>>> type(element)
<class 'pydicom.dataelem.DataElement'>
>>> element.VR
'CS'
>>> element.tag
(0008, 0008)
>>> element.name
'Image Type'
>>> element.value
['ORIGINAL', 'PRIMARY', 'AXIAL']
>>> element.VM
3

You will find similar information in the documentation of Dataset, and probably in other examples.

Note that there is also a command line interface that shows the contents of a DICOM file.

Edit:
As this has been asked in the other answer: if you want to access the file meta information, e.g. the tags in group 2, you can do so by iterating over ds.meta_info (ds being the dataset). meta_info is also of type Dataset and can be accessed the same way. Note that meta_info may be None if no meta information is present in the dataset:

from pydicom import dcmread

ds = dcmread(file_name)
meta_info = ds.meta_info
if meta_info is not None:
    for element in meta_info:
        print(element)
Related