python读取二进制mnist实例详解

yipeiwu_com5年前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实现二叉搜索树BST的方法示例

二叉排序树(BST)又称二叉查找树、二叉搜索树 二叉排序树(Binary Sort Tree)又称二叉查找树。它或者是一棵空树;或者是具有下列性质的二叉树: 1.若左子树不空,则左...

Python高级用法总结

列表推导(list comprehensions) 场景1:将一个三维列表中所有一维数据为a的元素合并,组成新的二维列表。 最简单的方法:新建列表,遍历原三维列表,判断一维数据是否为a,...

python计算两个数的百分比方法

工作中遇到了要计算两个数百分比的问题,python 2.7 环境。 代码: #!/usr/bin/env python #function: 计算百分比 #USAGE: python...

python字符串的拼接方法总结

python字符串的拼接方法总结

这篇文章主要介绍了python字符串的拼接方法总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 加号连接 1.通过+号连接起来 逗...

python学习之hook钩子的原理和使用

python学习之hook钩子的原理和使用

什么是钩子 之前有转一篇关于回调函数的文章 钩子函数、注册函数、回调函数,他们的概念其实是一样的。 钩子函数,顾名思义,就是把我们自己实现的hook函数在某一时刻挂接到目标挂载点上。...