将mnist数据集存储到本地文件

本文介绍了一种使用Python从MNIST数据集中读取图像和标签的方法,并将其转换为数组形式,同时展示了如何将这些图像保存为本地文件。通过解析二进制文件,实现了对图像像素值的预处理,将所有像素值大于1的设为1,便于后续的机器学习任务。

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

参考文章:

http://www.csuldw.com/2016/02/25/2016-02-25-machine-learning-MNIST-dataset/

import numpy as np
import struct
import matplotlib.pyplot as plt
import os
filename = 'data_AI/MNIST/train-images.idx3-ubyte'
binfile = open(filename , 'rb')
buf = binfile.read()
 
index = 0
magic, numImages , numRows , numColumns = struct.unpack_from('>IIII' , buf , index)
index += struct.calcsize('IIII' )
images = []
for i in range(numImages):
    imgVal = struct.unpack_from('>784B', buf, index)
    index += struct.calcsize('>784B')
    imgVal = list(imgVal)
    for j in range(len(imgVal)):
        if imgVal[j] > 1:
            imgVal[j] = 1

    images.append(imgVal)
arrX = np.array(images)

# 读取标签
binFile = open('data_AI/MNIST/train-labels.idx1-ubyte','rb')
buf = binFile.read()
binFile.close()
index = 0
magic, numItems= struct.unpack_from('>II', buf,index)
index += struct.calcsize('>II')
labels = []
for x in range(numItems):
    im = struct.unpack_from('>1B',buf,index)
    index += struct.calcsize('>1B')
    labels.append(im[0])
arrY = np.array(labels)
print(np.shape(arrY))

# print(np.shape(trainX))
#以下内容是将图像保存到本地文件中
path_trainset = "data_AI/MNIST/imgs_train"
path_testset = "data_AI/MNIST/imgs_test"
if not os.path.exists(path_trainset):
   os.mkdir(path_trainset)
if not os.path.exists(path_testset):
   os.mkdir(path_testset)
for i in range(1):
    img = np.array(arrX[i])
    print(img)
    img = img.reshape(28,28)
    outfile = str(i) + "_" +  str(arrY[i]) + ".png"
    # outfile = str(i)+".png"
    plt.figure()
    plt.imshow(img, cmap = 'binary') #将图像黑白显示
    plt.savefig(path_trainset + "/" + outfile)
    print("save"+str(i)+"")

 

转载于:https://www.cnblogs.com/ncuhwxiong/p/9726936.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值