You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将图片计算结果导出至.csv文件

将图片统计数据导出至CSV文件的解决方案

当然可以导出到CSV文件,用Python内置的csv模块就能搞定,不用额外装第三方库。给你修改好的代码:

import os
import numpy as np
from PIL import Image, ImageStat
import mahotas
import csv  # 导入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())

# 用with语句打开CSV文件,自动处理文件关闭
with open('image_stats.csv', 'w', newline='', encoding='utf-8') as csvfile:
    # 创建CSV写入对象
    writer = csv.writer(csvfile)
    # 先写入表头,让CSV结构更清晰
    writer.writerow(['文件名', '图片均值', '标准差均值'])
    
    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))
        # 计算并存储数据
        img_mean = img.mean()
        std_mean = np.mean(stat.stddev)
        # 保留原打印输出的同时写入CSV
        print(imageFile, ' | ', img_mean, ' | ', std_mean)
        writer.writerow([imageFile, img_mean, std_mean])

几点说明:

  • with open语句会自动帮你关闭文件,避免手动关文件遗漏导致的资源问题
  • newline=''是为了防止Windows系统下生成的CSV出现多余空行
  • 生成的image_stats.csv会和你的脚本在同一目录下,打开后就是规整的表格格式,直接能用Excel或表格软件查看

生成的CSV内容示例:

文件名,图片均值,标准差均值
a.png,220.31203392330383,5.57431258447292
b.png,220.40567772861357,5.3170114428831745
c.png,220.0692477876106,5.596059878150036

内容的提问来源于stack exchange,提问作者Neko Lim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:05:37