1

I am not able to write the details extracted from a DICOM file to a CSV file. Here's the code which I have used -

import pydicom
import os
import pandas as pd
import csv 
import glob 

data_dir= 'C:\\Users\\dmgop\\Personal\\TE Project - Pneumonia\\stage_1_test_images_dicom' 
patients= os.listdir(data_dir)
myFile= open('patientdata.csv','w')
for image in patients:
    lung = pydicom.dcmread(os.path.join(data_dir, image))
    print (lung)
    writer = csv.writer(myFile)
    writer.writerows(lung)
    break

The error which is coming up is as follows -

Traceback (most recent call last): File "C:\Users\dmgop\AppData\Local\Programs\Python\Python36\lib\site-packages\pydicom-1.2.0rc1-py3.6.egg\pydicom\dataelem.py",
line 344, in getitem
return self.value[key] TypeError: 'PersonName3' object does not support
indexing

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\dmgop\Personal\TE
Project - Pneumonia\detail_extraction.py", line 14, in
writer.writerows(lung) File
"C:\Users\dmgop\AppData\Local\Programs\Python\Python36\lib\site-packages\pydicom-1.2.0rc1-py3.6.egg\pydicom\dataelem.py",
line 346, in getitem
raise TypeError("DataElement value is unscriptable " TypeError: DataElement value is unscriptable (not a Sequence)

atline
  • 28,355
  • 16
  • 77
  • 113
Dev
  • 62
  • 7

1 Answers1

2

Assuming the "break" statement in your for loop means you only want the info of the first image, try:

import pydicom
import os
import csv 

data_dir = 'C:\\Users\\dmgop\\Personal\\TE Project-Pneumonia\\stage_1_test_images_dicom' 
patients = os.listdir(data_dir)
with open('file.csv','w') as myfile:
    writer = csv.writer(myFile)
    # patients[0] means get the first filename, no need for the for loop
    lung = pydicom.dcmread(os.path.join(data_dir, patients[0]))
    print(lung.formatted_lines)
    # pay attention to the function_call --> formatted_lines()
    writer.writerows(lung.formatted_lines())

Have a look at the Pydicom docs for FileDataset which is the return type for the dcmread method.
Should you want to write the data for all files in the directory, try the following:

import pydicom
import os
import csv 

data_dir = 'C:\\Users\\dmgop\\Personal\\TE Project-Pneumonia\\stage_1_test_images_dicom' 
patients = os.listdir(data_dir)
with open('file.csv','w') as myfile:
    writer = csv.writer(myfile)
    for patient in patients:
        if patient.lower().endswith('.dcm'):
            lung = pd.dcmread(os.path.join(data_dir, patient))
            writer.writerows(lung.formatted_lines())

Also have a look at the last part of this paragraph on the use of 'with open() as'

g_uint
  • 1,903
  • 3
  • 17
  • 30