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))
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.file_meta
(ds
being the dataset). file_meta
is also of type Dataset
and can be accessed the same way. Note that file_meta
may be None
if no meta information is present in the dataset:
from pydicom import dcmread
ds = dcmread(file_name)
file_meta = ds.file_meta
if file_meta is not None:
for element in file_meta:
print(element)