【问题标题】:KeyError due to missing tag when converting DCM to CSV将 DCM 转换为 CSV 时由于缺少标签而导致 KeyError
【发布时间】:2020-03-13 21:47:57
【问题描述】:

感谢您在这方面的帮助。 我想将 DCM 转换为 CSV 这是我尝试的代码

PathDicom = "path image"
dicom_image_description = pd.read_csv("dicom_image_description.csv")
# Specify the .dcm folder path
folder_path = PathDicom
images_path = os.listdir(folder_path)
# Patient's information will be stored in working directory #'Patient_Detail.csv'
with open('Patient_Detail.csv', 'w', newline ='') as csvfile:
    fieldnames = list(dicom_image_description["Description"])
    writer = csv.writer(csvfile, delimiter=',')
    writer.writerow(fieldnames)
    for n, image in enumerate(images_path):
        ds = dicom.dcmread(os.path.join(folder_path, image))
        rows = []
        for field in fieldnames:
            if ds.data_element(field) is None:
                rows.append('')
            else:
                x = str(ds.data_element(field)).replace("'", "")
                y = x.find(":")
                x = x[y+2:]
                rows.append(x)
        writer.writerow(rows)

结果

if ds.data_element(field) is None:

    return self[tag]

    data_elem = self._dict[tag]
KeyError: (0008, 0064)

那我该怎么办?

提前感谢您在此问题上的帮助。

【问题讨论】:

  • 您遇到了 KeyError。先解决这个问题。
  • 是的,KeyError 是因为该元素不在数据集中。请改用if ds.get(field, None) is None。或者查看我的答案以寻找替代方案......
  • 您从该错误消息中了解/不了解什么?你能改进一下标题吗?

标签: python csv dicom pydicom


【解决方案1】:

您将遇到幼稚转换的问题,因为您可能需要处理 sequence 元素(将数据集视为树状数据结构)和具有字节 VR 的元素的原始数据,如 OB、OD 、OF、OL、OW(见here)。但是,如果您只关心数据集中顶层的元素:

# Make sure that `fieldnames` is a list of element tags
for tag in fieldnames:
    if tag not in ds:
        writer.writerow('')
        continue

    elem = ds[tag]
    # Parse elem however you wish, watch out for elements with a byte VR though!
    value = elem.value
    if isinstance(value, bytes):
        value = "Binary data of length {}".format(elem.length)
    row = "{}, {}, {}".format(elem.tag, elem.VR, value)
    writer.writerow(row)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多