我目前正在使用以下代码手动读取200张dicom图像:
ds1 = dicom.read_file('1.dcm')
到目前为止,这已经奏效了,但我正试图通过创建一个循环来读取使用以下代码的文件,使我的代码更短、更容易使用:
for filename in os.listdir(dirName):
dicom_file = os.path.join("/",dirName,filename)
exists = os.path.isfile(dicom_file)
print filename
ds = dicom.read_file(dicom_file)
此代码当前不起作用,我收到错误:
"raise InvalidDicomError("File is missing 'DICM' marker. "
dicom.errors.InvalidDicomError: File is missing 'DICM' marker. Use
force=True to force reading
有人能告诉我哪里出了问题吗?
我认为行:
dicom_file = os.path.join("/",dirName,filename)
可能是个问题?它将把这三者连接起来,形成一条植根于"/"的路径。例如:
os.path.join("/","directory","file")
会给你"/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")
但是,os.listdir(dirName)将包括目录中的所有内容,包括其他目录、点文件和其他
如果在读取之前使用"if exists:",则exists=os.path.isfile(dicom_file)行将过滤掉所有非文件。
如果你知道模式,我建议使用glob方法,否则:
if exists:
try:
ds = dicom.read_file(dicom_file)
except InvalidDicomError as exc:
print "something wrong with", dicom_file
如果你尝试/排除,If存在:有点多余,但不会造成伤害。。。
尝试添加:
dicom_file = os.path.join("/",dirName,filename)
if not dicom_file.endswith('.dcm'):
continue