如何修复 pydicom 的 dcmread() 前导错误?

j. *_*doe 2 dicom python-3.x pydicom

dcmread()在处理给定路径中确实存在的 DICOM 文件时遇到问题。我不确定出了什么问题。这是我的代码:

import pydicom

f = "/exact/path/hi.dcm"
fn = get_testdata_file(f)
ds = pydicom.dcmread(fn)

ds.SOPClassUID = ds.MediaStorageSOPClassUID
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Traceback (most recent call last):
  File "addfields.py", line 14, in <module>
    ds = pydicom.dcmread(fn)
  File "/Users/user/opt/anaconda3/lib/python3.7/site-packages/pydicom/filereader.py", line 871, in dcmread
    force=force, specific_tags=specific_tags)
  File "/Users/user/opt/anaconda3/lib/python3.7/site-packages/pydicom/filereader.py", line 668, in read_partial
    preamble = read_preamble(fileobj, force)
  File "/Users/user/opt/anaconda3/lib/python3.7/site-packages/pydicom/filereader.py", line 605, in read_preamble
    preamble = fp.read(128)
AttributeError: 'NoneType' object has no attribute 'read'
Run Code Online (Sandbox Code Playgroud)

But I am not sure why, because "hi.dcm" is a file that exists (path is correct) and has metadata inside. I do not know what is preamble and whether it present in the image I am dealing with.

MrB*_*men 7

免责声明:我是 pydicom 的贡献者。

发生错误是因为get_testdata_file返回None,然后将其用作文件名。错误消息本身有点误导 -在这种情况下,提出FileNotFound或提出可能会更好ValueError。相反,读取的第一件事是前导码(DICOM 图像的标记,由 128 个零字节组成,后跟“DICM”),在尝试读取它时,由于文件指针为None.

这是文档get_testdata_file

返回具有文件名名称的第一个匹配数据集的绝对路径。

首先搜索本地 pydicom 数据存储,然后搜索任何本地可用的外部源,最后搜索 pydicom/pydicom-data 存储库中可用的文件。

所以这是一个方便的功能,主要是为了查找pydicom测试数据文件。
如果您已经有了文件路径,则可以使用它:

import pydicom

fn = "/exact/path/hi.dcm"
ds = pydicom.dcmread(fn)
Run Code Online (Sandbox Code Playgroud)

至于序言,如果 DICOM 文件没有序言(旧的 ACR-NEMA 格式),您可以使用force=True参数读取此类文件:

ds = pydicom.dcmread(fn, force=True)
Run Code Online (Sandbox Code Playgroud)

虽然我只会在你真的有这样的文件时才使用它,因为它也会尝试将非 DICOM 文件作为 DICOM 处理,这可能会导致一些意外的异常。如前所述,这种情况下的错误与缺少前导码无关,而是与不正确的文件路径有关。

更新:
自 2.1 版以来,pydicom此行为已更改。如果通过,dcmread现在将引发TypeError有意义的消息None