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

如何将MNIST数据集CSV中的强度数组转换为28×28灰度图像?

将MNIST CSV数据转换为28×28灰度图像

前置依赖

先安装所需的Python库:

pip install pandas pillow matplotlib

方法一:使用Pillow(PIL)批量转换并保存

Pillow是处理图像的常用库,适合批量生成图像文件:

import pandas as pd
from PIL import Image
import os

# 创建存储图像的目录,不存在则自动创建
save_dir = 'mnist_gray_images'
os.makedirs(save_dir, exist_ok=True)

# 读取MNIST CSV文件(替换为你的CSV路径)
df = pd.read_csv('mnist_dataset.csv')

# 遍历每一行数据生成图像
for index, row in df.iterrows():
    # 提取最后一列作为标签,前784列作为图像像素数据
    label = row[-1]
    pixel_data = row[:784].values
    
    # 将一维像素数组重塑为28×28的二维矩阵
    img_matrix = pixel_data.reshape(28, 28)
    
    # 转换为PIL灰度图像(mode='L'表示8位灰度图,对应0-255的像素值)
    img = Image.fromarray(img_matrix.astype('uint8'), mode='L')
    
    # 保存图像,命名格式为「索引_标签.png」,方便后续识别
    img.save(f"{save_dir}/{index}_{label}.png")

方法二:使用Matplotlib生成图像

如果需要同时预览图像,Matplotlib也是不错的选择:

import pandas as pd
import matplotlib.pyplot as plt
import os

save_dir = 'mnist_gray_images_matplotlib'
os.makedirs(save_dir, exist_ok=True)

df = pd.read_csv('mnist_dataset.csv')

for index, row in df.iterrows():
    label = row[-1]
    img_matrix = row[:784].values.reshape(28, 28)
    
    # 以灰度模式显示图像
    plt.imshow(img_matrix, cmap='gray')
    plt.axis('off')  # 隐藏坐标轴,避免干扰图像显示
    
    # 保存图像,去掉多余空白区域
    plt.savefig(f"{save_dir}/{index}_{label}.png", bbox_inches='tight', pad_inches=0)
    plt.close()  # 关闭画布,释放内存

注意事项

  • 确保CSV文件路径正确,如果文件较大,pandas.read_csv可通过chunksize参数分块读取,避免内存溢出
  • 70000张图像会占用约2-3GB存储空间,需确保目标磁盘有足够空间
  • 若仅需处理部分数据,可在循环中添加条件(如if index < 100)限制转换数量

内容的提问来源于stack exchange,提问作者Yasin Karayanık

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:05:15