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
CodePudding user response:
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)])
CodePudding user response:
You can do this by adding the 'imagefile','img.mean()','np.mean(stat)' into an empty list and add that list into the csv file as data.. Here is the code
import csv
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())
csvData = list()
for imageFile in listOfImageFiles:
tempData = list()
im = Image.open(os.path.join(dir_path, imageFile))
stat = ImageStat.Stat(im)
img = mahotas.imread(os.path.join(dir_path, imageFile))
tempData.append(imageFile)
tempData.append(str(img.mean()))
tempData.append(str(np.mean(stat)))
print(imageFile, ' | ', img.mean(), ' | ', np.mean(stat.stddev))
csvData.append(tempData)
csvfile = open('demo.csv', 'w', newline='')
heads = ['Imagefiel', 'Imagemean', 'Np.mean'] # give the heading of the csv columns
writecsvfile = csv.writer(csvfile)
writecsvfile.writerow(heads) # to write the headering to the csv file
writecsvfile.writerows(csvData) # write the csv file data
Hope it will be helpfull