Search code examples
pythonpython-3.xexport-to-csv

How to export calculation value output to .csv file (python)


I'm wondering is there possible to export the output data to the .csv file.

dir_path = "image path"
fileext = ('.png', 'jpg', 'jpeg')
listOfFiles = [imageFile for imageFile in os.listdir(dir_path) if imageFile.endswith(fileext)]
listOfImageFiles = sorted(listOfFiles, key=lambda x: x.lower())

for imageFile in listOfImageFiles:
    im = Image.open(os.path.join(dir_path, imageFile))
    stat = ImageStat.Stat(im)
    img = mahotas.imread(os.path.join(dir_path, imageFile))
    print(imageFile, ' | ', img.mean(), ' | ', np.mean(stat.stddev))

as my output is like this...

a.png | 220.31203392330383 | 5.57431258447292

b.png | 220.40567772861357 | 5.3170114428831745

c.png | 220.0692477876106 | 5.596059878150036

and the output needs it to be exported to a .csv file


Solution

  • You can achieve that by using the csv module. You will need to create and open a .csv file and write the headers for your file which in your case are ImageFile, ImageMean and Np.Mean.

    Then you will loop through all your images and do the mahotas processing and then write the results in a new row in your csv file.

    The approach is totally similar to what Manvi provided but with much less a more readable code.

    from PIL import Image, ImageStat
    import os, mahotas,csv
    import numpy as np
    
    dir_path = "image path"
    fileext = ('.png', 'jpg', 'jpeg')
    listOfFiles = [imageFile for imageFile in os.listdir(dir_path) if imageFile.endswith(fileext)]
    listOfImageFiles = sorted(listOfFiles, key=lambda x: x.lower())
    
    with open('output.csv', 'w', newline='') as file:
        csvWriter = csv.writer(file)
        csvWriter.writerow(['File Name', 'Mean', 'Standard Deviation'])
    
        for imageFile in listOfImageFiles:
            im = Image.open(os.path.join(dir_path, imageFile))
            stat = ImageStat.Stat(im)
            img = mahotas.imread(os.path.join(dir_path, imageFile))
            csvWriter.writerow([imageFile, img.mean(), np.mean(stat.stddev)])