0

I want to loop over dicom tags and image series in my script in a user interactive way. But I am unable to create a loop, which can ask user: Do you want to modify or add tags? if add then How many tags you want to add? and if no then which tags you want to modify? and then ask for the tags details and then later add them into my image series..

I have written a user interactive script which i will share with you, which can ask user to add any two tags in any image series(MRI, PET or CT).

tag1 = input("Enter the tag: ")
VR1 = input("Enter VR: ")
Value1 = input("Enter the value at VR: ")
tag2 = input("Enter the tag: ")
VR2 = input("Enter VR: ")
Value2 = input("Enter the value at VR: ")
for imagePath in image_path_list:
    image = dcmread(imagePath)   
    image.add_new(tag1, VR1, Value1)
    image.add_new(tag2, VR2, Value2)
    image.add_new(0x00180020, 'CS', 'GR')
    image.add_new(0x00180021, 'CS', 'SP\OSP')
    src_fname, ext = os.path.splitext(imagePath)
                                           '''

I expect a loop over my tags and image series in a interactive way.

1 Answers1

0

The code below will ask for a number of tags and values to enter. This assumes the tags are all in the DICOM dictionary, in which case you do not need the VR; pydicom will look it up. With the latest code in the pydicom repository, the 'tag' can also be the DICOM keyword, e.g. 'PatientName', 'PatientID'.

As per usual pydicom assignment, the code will modify the data element if it already exists; otherwise it will be added.

All datasets are changed in the same way. If that is not what you wanted, you could loop first over the datasets, and enter tags and values only for that dataset.

from pydicom import dcmread
from pydicom.tag import Tag
import glob

image_path_list = glob.glob(r"c:\temp\dicom\*.dcm")

datasets = [dcmread(filepath) for filepath in image_path_list]

print("\n\nEnter tag=value, one per line. When done, enter blank and datasets will be written)")
while True:
    pair = input("Enter in form tag=value...:")
    if pair == "":
        break

    if "=" not in pair:
        print("Entry must contain an = sign")
        print()
        continue

    # Parse line, stripping away extra spaces        
    tag, value = [x.strip() for x in pair.split("=")]

    try:
        tag = Tag(tag)
    except:
        print("Tag not in a valid format")
        print()
        continue

    for ds in datasets:
        ds[tag].value = value

# Write all the modifications:
for ds in datasets:
    ds.save_as(ds.filename)

Example use:

Enter in form tag=value...:0x100010=Lastname^Firstname
Enter in form tag=value...:0x100020=id123
Enter in form tag=value...:SliceLocation=23.5
Enter in form tag=value...:
darcymason
  • 1,223
  • 6
  • 9