我想知道是否有可能将输出数据导出到。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())
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))
我的输出是这样的…
a.png | 220.31203392330383 | 5.57431258447292
b.png | 220.40567772861357 | 5.3170114428831745
c.png | 220.0692477876106 | 5.596059878150036
,输出需要导出到。csv文件
可以通过使用csv模块来实现。你需要创建并打开一个。csv文件,并为你的文件写标题,在你的例子中是ImageFile, ImageMean和Np.Mean。
然后循环遍历所有图像并进行mahotas处理,然后将结果写入csv文件的新行。
该方法与Manvi提供的方法完全相似,但代码可读性要差得多。
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)])
您可以将'imagefile',' image .mean()','np.mean(stat)'添加到一个空列表中,并将该列表添加到csv文件中作为数据。下面是代码
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
希望对大家有所帮助