Python解析二进制MNIST数据集:从文件读取到图像显示

雨后青山
雨后青山
发布时间:2026-10-13 | 3人浏览过
原创

本文详解如何使用Python读取二进制格式的MNIST手写数字数据集。通过解析文件头部的魔数、图片数量及维度信息,并利用struct模块提取像素数据,最终将784维向量重塑为28x28图像进行可视化展示。

Python读取二进制MNIST实例详解

训练数据的内部结构如下:

<br>[offset] [type]     [value]     [description]
0000   32 bit integer 0x00000803(2051) magic number
0004   32 bit integer 60000      number of images
0008   32 bit integer 28        number of rows
0012   32 bit integer 28        number of columns
0016   unsigned byte  ??        pixel
0017   unsigned byte  ??        pixel
........
xxxx   unsigned byte  ??        pixel
 

首先需要将整个文件内容一次性加载到内存中:

filename = 'train-images.idx3-ubyte'
binfile = open(filename , 'rb')
buf = binfile.read()

接着读取文件头部的四个32位整数,分别对应魔数、图片数量、行数和列数:

index = 0
magic, numImages , numRows , numColumns = struct.unpack_from('>IIII' , buf , index)
index += struct.calcsize('>IIII')

随后读取单张图像数据,其像素总数为784(即28乘以28):

im = struct.unpack_from('>784B' ,buf, index)
index += struct.calcsize('>784B')
 
im = np.array(im)
im = im.reshape(28,28)
 
fig = plt.figure()
plotwindow = fig.add_subplot(111)
plt.imshow(im , cmap='gray')
plt.show()

感谢阅读,希望本文能对大家有所帮助,感谢各位对本站的支持!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表