python读取二进制mnist实例详解

yipeiwu_com6年前Python基础

python读取二进制mnist实例详解

training data 数据结构:

<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()

读取头四个32bit的interger:

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的Flask框架中实现单元测试的教程

 概要 在前面的章节里我们专注于在我们的小应用程序上一步步的添加功能上。到现在为止我们有了一个带有数据库的应用程序,可以注册用户,记录用户登陆退出日志以及查看修改配置文件。 在...

Python中正则表达式的详细教程

Python中正则表达式的详细教程

1.了解正则表达式     正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个“规则字符串”,这个“规则...

如何高效使用Python字典的方法详解

前言 众所周知字典(dict)对象是 Python 最常用的数据结构,社区曾有人开玩笑地说:"Python企图用字典装载整个世界",字典在Python中的重要性不言而喻,这里整理了几个关...

Python hashlib模块加密过程解析

这篇文章主要介绍了Python hashlib模块加密过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 hashlib模块  ...

详解Python的三种可变参数

可变参数 可变参数应该最简单,在C/C++和Java等语言中都有,就是用*号来表示,例如 def testArg(*arg) 你可以传入任意多个元素(包括0)到参数中,在函数内部...