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

使用Python将目录下图像批量转为类似FER2013格式的CSV文件求助

问题修复与实现方案

原代码无法生成符合要求的CSV,核心问题及解决方案如下:

  • 输出格式不匹配:FER2013的pixels列是单格内用空格分隔所有像素值,原代码用csv.writer每行写N个单元格(每个像素占一个单元格),和目标格式完全不符
  • 缺少必填列:标准FER2013包含emotion(情绪标签数字)、pixels、Usage(训练/验证/测试集标识)三列表头,原代码没有表头也没有这两个字段
  • 路径适配问题:要确认/test/surprise目录存在且内有对应格式的图片,否则文件列表为空不会生成任何内容
  • 写入逻辑问题:循环内反复打开文件追加,效率低且容易出现IO异常

修正后的完整代码如下:

from PIL import Image
import numpy as np
import os
import csv

def createFileList(myDir, format='.png'):
    fileList = []
    if not os.path.exists(myDir):
        print(f"目录{myDir}不存在")
        return fileList
    for root, dirs, files in os.walk(myDir, topdown=False):
        for name in files:
            if name.endswith(format):
                fullName = os.path.join(root, name)
                fileList.append(fullName)
    return fileList

if __name__ == "__main__":
    # 可根据实际需求修改配置参数
    img_dir = "/test/surprise"
    output_csv = "fer_format_output.csv"
    emotion_label = 3  # FER2013中惊喜对应标签为3
    usage = "Training"  # 可根据数据集划分改为PublicTest/PrivateTest
    target_img_size = (48,48) # 和FER2013图片尺寸一致
    
    # 先写表头
    with open(output_csv, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(["emotion", "pixels", "Usage"])
    
    # 遍历所有图片写入
    myFileList = createFileList(img_dir)
    if not myFileList:
        print("未找到符合格式的图片")
        exit()
    
    for file in myFileList:
        img_file = Image.open(file)
        # 统一调整尺寸
        img_resized = img_file.resize(target_img_size)
        # 转灰度图
        img_grey = img_resized.convert('L')
        # 转一维数组
        pixel_array = np.asarray(img_grey.getdata(), dtype=np.int32).flatten()
        # 转空格分隔的字符串
        pixel_str = " ".join(map(str, pixel_array))
        # 追加写入csv
        with open(output_csv, 'a', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow([emotion_label, pixel_str, usage])
    
    print(f"文件已生成,共写入{len(myFileList)}条数据")

若不需要匹配FER2013的表头结构,仅需要像素为单行空格分隔的格式,删除表头和emotion、Usage列的写入逻辑即可。

内容的提问来源于stack exchange,提问作者Carlos Berrocal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:15:05