从 PosixPath 读取 DICOM 对象,Python

Read DICOM objects from PosixPath, Python

我有 20,000 个 PosixPath,每个指向不同的 .dcm 对象。我需要一个一个地阅读 .dcm 对象。到目前为止,这是我的代码:

from pathlib import Path
import glob
import dicom
data = Path('/data')
path_to_dcm_objects = list(data.glob('**/*.dcm'))
for i in len(path_to_dcm_objects):
    record = dicom.read_file(path_to_dcm_objects[i])

当我想使用其 PosixPath 读取 .dcm 文件时出现错误:

AttributeError: 'PosixPath' object has no attribute 'read'

如有任何帮助,我们将不胜感激。

dicom.read_file() 需要一个打开的文件对象或路径字符串而不是 Path 实例。如果它不是字符串,它会认为它是一个打开的文件并尝试从中读取。

Path 实例转换为字符串 str(path_object):

for i in len(path_to_dcm_objects):
    record = dicom.read_file(str(path_to_dcm_objects[i]))

Path对象转字符串的帮助:

Return the string representation of the path, suitable for passing to system calls.

您还可以使用:

 path_object.as_posix()

这为您提供了一个 Posix 路径:

Return the string representation of the path with forward (/) slashes.

顺便说一句,遍历所有路径的 pythonic 方式看起来更像这样:

for path_obj in data.glob('**/*.dcm'):
    record = dicom.read_file(str(path_obj))