Search code examples
pythonpydicom

Pydicom: AttributeError when trying to change Patientname Tag


Let's say I have a dicom file where I want to show, and subsequently change the Patients Name. Since our users can't be trusted with adding the separator (^) properly, I show the User six fields (three for old data, three for new data), labeled "Title", "First Name" and "Last Name", respectively. While trying several approaches, I noticed that the tag "PatientName" has the attributes "family_name", "given_name" and "name_prefix", along with others, which is ideal for what I want. While I can read the attributes with FirstName = ds.PatientName.given_name, I can't write them with ds.PatientName.given_name = FirstName. This throws an attribute error: AttributeError: can't set attribute 'given_name'.

I am out of ideas on what to do. Of course I could add the three name strings together and write that as ds.PatientName, but that feels rather clunky.

For better reference, here's part of my code (I use a tkinter form so there is some syntax from that):

## Retrieves Patient Name from first Dicom-File found
def GetName():
    file = (os.listdir(path))[0]
    filepath = path + file
    ds = dc.dcmread(filepath)
    OldTitle.configure(state='normal')
    OldTitle.delete(1.0, END)
    OldTitle.insert('end', ds.PatientName.name_prefix)
    OldTitle.configure(state='disabled')
    OldLName.configure(state='normal')
    OldLName.delete(1.0, END)
    OldLName.insert('end', ds.PatientName.family_name)
    OldLName.configure(state='disabled')
    OldFName.configure(state='normal')
    OldFName.delete(1.0, END)
    OldFName.insert('end', ds.PatientName.given_name)
    OldFName.configure(state='disabled')

## Changes Patient Name to specified value
def ChangeName():
    newtitle = NewTitle.get(1.0, 'end-1c')
    newfname = NewFName.get(1.0, 'end-1c')
    newlname = NewLName.get(1.0, 'end-1c')
    file = (os.listdir(path))[0]
    filepath = path + file
    ds = dc.dcmread(filepath)
    ds.PatientName.name_prefix = newtitle ## This is where I get the error
    ds.PatientName.given_name = newfname
    ds.PatientName.family_name = newlname
    ds.save_as(filepath)

Solution

  • There is a class method from_named_components that returns a new PersonName instance from the different components.

    Here is an example from the docs linked above:

    from pydicom.valuerep import PersonName
    pn = PersonName.from_named_components(
        family_name='Adams',
        given_name='John Robert Quincy',
        name_prefix='Rev.',
        name_suffix='B.A. M.Div.'
    )
    print(pn)
    
    --> Adams^John Robert Quincy^^Rev.^B.A. M.Div.
    

    There is another example on the page which includes encodings.