Python,在循环中打开文件(dicom)

2024-10-01 17:35:26 发布

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

我目前正在使用以下代码手动读取200幅dicom图像:

ds1 = dicom.read_file('1.dcm')

到目前为止,这是有效的,但我正在尝试通过创建一个循环来读取使用此代码的文件,使我的代码更短、更易于使用:

^{pr2}$

此代码当前不工作,我收到错误:

"raise InvalidDicomError("File is missing 'DICM' marker. "
dicom.errors.InvalidDicomError: File is missing 'DICM' marker. Use         
force=True to force reading

有谁能告诉我我哪里出错了吗?在


Tags: 代码图像readis手动markerfiledicom
2条回答

我认为这句话:

dicom_file = os.path.join("/",dirName,filename) 

可能是个问题?它将把这三者连接起来,形成一条以“/”为根的路径。例如:

^{pr2}$

将为您提供“/directory/file”(绝对路径),同时:

os.path.join("directory","file")

将为您提供“目录/文件”(相对路径)

如果你知道你想要的所有文件都是“*.dcm” 您可以尝试glob模块:

import glob

files_with_dcm = glob.glob("*.dcm")

这也适用于完整路径:

import glob

files_with_dcm = glob.glob("/full/path/to/files/*.dcm")

但同时,操作系统列表目录(dirName)将包括目录中的所有内容,包括其他目录、点文件等

您的存在=os.path.isfile文件(dicom_文件)行将过滤掉所有非文件,如果你使用“如果存在:”之前阅读。在

如果您知道模式,我建议使用glob方法,否则:

if exists:
   try:
      ds = dicom.read_file(dicom_file)
   except InvalidDicomError as exc:
      print "something wrong with", dicom_file

如果你做了一个尝试/例外,如果存在:有点多余,但不伤害。。。在

尝试添加:

dicom_file = os.path.join("/",dirName,filename) 
if not dicom_file.endswith('.dcm'):
    continue 

相关问题 更多 >

    热门问题