Recently, I was assigned a small task to output information of Series folder path and its corresponding DICOM tags.
Here, we suppose following requirements:
- One folder contains at most 1 series;
- User specify DICOM root folder path, the code tool ouputs information for all series under the root path;
- Output information only contains: relative path to DICOM root folder path, and tag value of patient id, patient name, and series uid.
- Output information is recorded into log file under DICOM root folder.
The following is python code for this small task.
import os
import time
import pydicom
from pydicom.valuerep import PersonName3
def generate_id():
ct = time.time()
local_time = time.localtime(ct)
data_head = time.strftime("%Y%m%d%H%M%S", local_time)
data_millisec = (ct - int(ct)) * 1000
time_stamp = "%s%03d" % (data_head, data_millisec)
return time_stamp
dicom_dir = "<Here is your absolute folder path for DICOM data>"
log_file = dicom_dir + "\\" + generate_id() + ".log"
log_handle = open(log_file, 'a')
for root, dirs, files in os.walk(dicom_dir):
relative_dir = root[len(dicom_dir):]
# suppose 1 folder contains at most 1 series
for file_name in files:
src_file = root + '\\' + file_name
try:
ds = pydicom.read_file(src_file)
try:
char_set = ds.get("SpecificCharacterSet", "")
if char_set != "":
ds.decode()
except:
ds.SpecificCharacterSet = "ISO_IR 100"
pass
patient_id = ds.get("PatientID", "")
series_uid = ds.get("SeriesInstanceUID", "")
patient_name = ds.get("PatientName", "")
if isinstance(patient_name, list):
patient_name = ", ".join([str(x) for x in patient_name])
elif isinstance(patient_name, PersonName3):
patient_name = str(patient_name)
if patient_id == "" or series_uid == "":
continue
out_str = ("###dir: " + relative_dir + " ; ")
out_str += ("###patient id: " + patient_id + " ; ")
out_str += ("###patient name: " + patient_name + " ; ")
out_str += ("###series uid: " + series_uid + " ; ")
log_handle.write(out_str + '\n')
break
except Exception as err:
print(err)
# log_handle.write(src_file + '\n')
log_handle.close()