0

I'm trying to write pixel_array data and patientID from multiple Dicom files to a CSV.

The pixel arrays, which are np arrays get saved like this;

[[0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n ...\n [0 0 0 ... 0 0 0]\n [0 0 0 ...    0 0 0]\n [0 0 0 ... 0 0 0]]

how do I get back the original np array?

if you could pls give me some advice on writing these properly to CSV so the np arrays are preserved as they are? Below is the loop

def tryer(a, b):   
if b == 'pixel_array':
    return(a.pixel_array)
else:
    try:
        return(getattr(a, b))
    except AttributeError:
        return('No')

tryer is as defined above;

a_list = ['PatientID', 'pixel_array']


with open('imgs_n_patied_train1.csv', 'w', newline = '') as f:
thewriter = writer(f)
thewriter.writerow(['PatientID', 'pixel_array\n'])
for i in imgs:
    #iterating through each file and writing all the metadata to a csv row-wise
    a = dicom.read_file(r'pathto\stage_2_train_images' + '\\' + i, force = True) 
    app = []
    for j in a_list:
        app.append(tryy.tryer(a, j))            
    thewriter.writerow(app)
Akshay Ram
  • 25
  • 9
  • `csv` is suitable for writing **one** array that is 2d. Multiple arrays can only be save (and loaded) if they are joined into one. `np.savetxt` works for numeric dtypes (but read its docs). The `csv` is a text file, so you have to pay attention to how the array values are formatted. Using the print/string representation of the array is not useful. – hpaulj Jun 29 '20 at 15:57
  • `pandas` has a good `csv` writer. But all the data has to be in one dataframe. – hpaulj Jun 29 '20 at 16:35

0 Answers0