0

Hi I have a folder of dcm files i want to change into png files to put into a png folder. Here is the code I have done:

dcm_folder= '/Users/riaroque/Desktop/DCM Pneumonia cases'
PNG_folder= '/Users/riaroque/Desktop/PNG folder'

os.makedirs(PNG_folder, exist_ok=True)
for dcm_file in os.listdir(dcm_folder):
    dcm_file_path = os.path.join(dcm_folder, dcm_file)
    png_file_path = os.path.join(PNG_folder, '%s.png' % dcm_file)
    try:
        convert_file(dcm_file_path, png_file_path)
        print (dcm_file_path, '-->', png_file_path)
    except:
        print ('FAIL>', dcm_file_path, '-->', png_file_path)

It's giving me a list this error

FAIL> /Users/riaroque/Desktop/DCM Pneumonia cases/UP0084.dcm --> /Users/riaroque/Desktop/PNG folder/UP0084.dcm.png

I can see that from the error its not properly converted having .dcm.png at the end, How do I remove the .dcm and just replace it with .png?

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
Ria Roque
  • 13
  • 3
  • Answer here does exactly what you want and will also handle the .DS_store files correctly (i.e. skip them): https://stackoverflow.com/a/72367480/784171 – Wouter May 24 '22 at 18:47

1 Answers1

0

Replace the following line:

png_file_path = os.path.join(PNG_folder, '%s.png' % dcm_file)

with

png_file_path = os.path.join(PNG_folder, dcm_file.replace('.dcm', '.png')

This uses a string's replace method to change '.dcm' to '.png'.

It assumes that '.dcm' only occurs as the suffix at the end of the file name. If there is an earlier occurrence of '.dcm' in the string, you'll have to do something more sophisticated.

Dave Chen
  • 1,905
  • 1
  • 12
  • 18
  • Thanks! I tried putting it with your code (with an extra bracket at the end) but I still get this error: ```FAIL> /Users/riaroque/Desktop/DCM Pneumonia cases/UP0084.dcm --> /Users/riaroque/Desktop/PNG folder/UP0084.png FAIL> /Users/riaroque/Desktop/DCM Pneumonia cases/UP0090.dcm --> /Users/riaroque/Desktop/PNG folder/UP0090.png``` – Ria Roque Jul 29 '20 at 10:06
  • I just want to ask one of the error has also this in between: ```FAIL> /Users/riaroque/Desktop/DCM Pneumonia cases/.DS_Store --> /Users/riaroque/Desktop/PNG folder/.DS_Store``` Do you think that's the one causing everything to fail? – Ria Roque Jul 29 '20 at 10:09
  • .DS_Store is clearly not a Dicom image. That's an attribute file put in by Mac OS. Clearly you should ignore that file. – Dave Chen Jul 29 '20 at 18:14
  • As far as the first FAIL, if I had to guess, maybe the convert_file function doesn't like path names with spaces in them. Often the OS doesn't handle them correctly. – Dave Chen Jul 29 '20 at 18:15