从Python的PosixPath读取DICOM对象

2024-05-13 08:27:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有20000个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])

当我想使用.dcm文件的PosixPath读取该文件时,会出现一个错误:

^{pr2}$

任何帮助都将不胜感激。在


Tags: 文件topath对象代码fromimportdata
1条回答
网友
1楼 · 发布于 2024-05-13 08:27:06

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.

您还可以使用:

^{pr2}$

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

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

顺便说一句,python迭代所有路径的方式看起来更像这样:

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

相关问题 更多 >