4
votes

I am currently reading in 200 dicom images manually using the code:

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

so far, this has worked but I am trying to make my code shorter and easier to use by creating a loop to read in the files using this code:

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)

This code is not currently working and I am receiving the error:

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

Could anyone advice me on where I am going wrong please?

2
Are there files other than .dcm files in that folder?user812786
Sounds like one or more of the files in your directory are not of the correct type.gkusner
Are there only ".dcm" files in the directory, or could there be other files or directories? You are checking if it is a file (exists) but then not using that information. I was anticipating seeing an "if exists:" line right after that.RobertB
How about printing dicom_file to see if you have the path right.tdelaney
The error seems to be that there were two .txt files in the folder with dicoms and when they were moved the code worked, thank you! I will add an if exists to ensure the problem doesn't happen again. Thank you everyone!smailliwharas

2 Answers

3
votes

I think the line:

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

might be an issue? It will join all three to form a path rooted at '/'. For example:

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

will give you "/directory/file" (an absolute path), while:

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

will give you "directory/file" (a relative path)

If you know that all the files you want are "*.dcm" you can try the glob module:

import glob

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

This will also work with full paths:

import glob

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

But also, os.listdir(dirName) will include everything in the directory including other directories, dot files, and whatnot

Your exists = os.path.isfile(dicom_file) line will filter out all the non files if you use an "if exists:" before reading.

I would recommend the glob approach, if you know the pattern, otherwise:

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

If you do a try/except, the if exists: is a bit redundant, but doesn't hurt...

2
votes

Try adding:

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