pythondicomkeyerrorpydicom

PyDICOM Returns KeyError Even Though Field Exists


I'm reading in a DICOM with pydicom.read_file() like this:

x = pydicom.read_file(/path/to/dicom/)

This returns an instance of FileDataset but I get an error when trying to access a value like this:

x[0x20,0x32]
OUTPUT: *** KeyError: (0020, 0032)

I also tried accessing the value like this:

x.ImagePositionPatient
OUTPUT: *** AttributeError: 'FileDataset' object has no attribute 'ImagePositionPatient'

The reason this confuses me is because when I look at all the values using x.values I see the field is in fact present:

(0020, 0032) Image Position (Patient)

How can the key be missing if I can clearly see that it exists?

I'm not an expert on PyDICOM but it should work just like a regular Python dictionary.


Solution

  • For Enhanced SOP classes (Enhanced CT, Enhanced MR and some more) many tags are located in sequences: in the Shared Functional Groups Sequence for tags that are common for all slices, and in the Per frame Functional Groups Sequence for tags specific to each slice, with an item for each slice.
    (note that the links are specific to Enhanced MR to match your dataset)

    Image Position (Patient) is a slice-specific tag, so you can access the value for a each slice in the corresponding item. The functional group sequences do not directly contain the tags, but they are nested in another sequence - in the case of Image Position (Patient) this is the Plane Position Sequence. To access these values in pydicom you can do something like:

    ds = dcmread(filename)
    positions = []
    for item in ds.PerFrameFunctionalGroupsSequence:
        positions.append(item.PlanePositionSequence[0].ImagePositionPatient)
    print(positions)
    

    This will give you the image position for each slice. You should check that you have the correct SOP class, of course, and add checks for existence of the tags. Depending on your use case, you may only need the first of these positions, in which case you wouldn't have to iterate over the items.