MNIST数据集的图片保存

本文介绍了如何使用TensorFlow读取MNIST数据集,并将训练数据的图像及其标签保存到本地文件夹中。文章详细展示了数据集的大小、形状,以及创建保存文件夹、检查文件和目录存在性的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#-*- conding:utf-8 -*-
import os
import numpy as np
from PIL import Image
import traceback

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data/", one_hot=False)

print("-"*50)

def check_file(file_path):
    if os.path.exists(file_path):
        os.remove(file_path)
    fp = open(file_path,"w")
    fp.close()

def check_dir(path):
    if os.path.exists(path):
        for filename in os.listdir(path):
            print("delete --",os.path.join(path, filename))
            os.remove(os.path.join(path, filename))
        os.removedirs(path)
    os.makedirs(path)


# 1,查看训练数据的大小
print("训练数据图片的形状{}".format(mnist.train.images.shape))
print("训练数据图片标签的形状{}".format(mnist.train.labels.shape))
print("-"*50)

# 2,查看测试数据的大小
print("测试数据图片的形状{}".format(mnist.test.images.shape))
print("测试数据图片标签的形状{}".format(mnist.test.labels.shape))
print("-"*50)

# 3,创建保存文件夹
path = "./img"
if os.path.exists(path):
    pass
else:
    os.makedirs(path)

# 4,设置保存路径
images_path = os.path.join(path, "train_images")   # 保存的图片
file_path = os.path.join(path, "train_label.txt")  # 保存的标签
print(images_path)
print(file_path)

# 5,检查文件和目录是否存在
check_dir(images_path)    # 检查保存的文件夹是否存在
check_file(file_path)     # 检查保存的标签是否存在

# 6,保存文件和标签
num = 10
for i in range(num):
    try:
        save_file = open(file_path, "a+")
        try:
            # 拿到图片
            im_data = np.array(np.reshape(mnist.train.images[i], (28, 28)) * 255, dtype=np.int8)
            img = Image.fromarray(im_data, "L")

            # 拿到标签
            label = mnist.train.labels[i]

            # 保存
            img.save(os.path.join(images_path, "{0}.jpg".format(i)))
            save_file.write("{0}.jpg {1}\n".format(i, label))
            save_file.flush()

        except Exception as e:
            traceback.print_exc()
    finally:
        save_file.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值