python读取,显示,保存mnist图片
python处理二进制
python的struct模块可以将整型(或者其它类型)转化为byte数组.看下面的代码.
# coding: utf-8
from struct import *
# 包装成大端的byte数组
print(pack('>hhl', 1, 2, 3)) # b'\x00\x01\x00\x02\x00\x00\x00\x03'
pack('>hhl', 1, 2, 3)作用是以大端的方式把1(h表示2字节整型),2,3(l表示4字节整型),转化为对于的byte数组.大端小端的区别看参数资料2,>hhl的含义见参考资料1.输出为长度为8的byte数组,2个h的长度为4,1个l的长度为4,加起来一共是8.
再体会下面代码的作用.
# coding: utf-8
from struct import *
# 包装成大端的byte数组
print(pack('>hhl', 1, 2, 3)) # b'\x00\x01\x00\x02\x00\x00\x00\x03'
# 以大端的方式还原成整型
print(unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')) # (1, 2, 3)
# 包装成小端的byte数组
print(pack('<hhl', 1, 2, 3)) # b'\x01\x00\x02\x00\x03\x00\x00\x00'
# 以小端的方式还原成整型
print(unpack('<hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')) # (256, 512, 50331648)
mnist显示
以t10k-images.idx3-ubyte为例,t10k-images.idx3-ubyte是二进制文件.其格式为
[offset] [type] [value] [description]
0000 32 bit integer 0x00000803(2051) magic number
0004 32 bit integer 10000 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
前4个整型代表文件头的一些信息.之后的无符号byte数组才是图片的内容.所以要先越过前4个整型,然后再开始读取,代码如下
import numpy as np
import struct
import matplotlib.pyplot as plt
filename = r'D:\source\technology_source\data\t10k-images.idx3-ubyte'
binfile = open(filename, 'rb')
buf = binfile.read()
index = 0
magic, numImages, numRows, numColumns = struct.unpack_from('>IIII', buf, index) # 读取前4个字节的内容
index += struct.calcsize('>IIII')
im = struct.unpack_from('>784B', buf, index) # 以大端方式读取一张图上28*28=784
index += struct.calcsize('>784B')
binfile.close()
im = np.array(im)
im = im.reshape(28, 28)
fig = plt.figure()
plotwindow = fig.add_subplot(111)
plt.axis('off')
plt.imshow(im, cmap='gray')
plt.show()
# plt.savefig("test.png") # 保存成文件
plt.close()
可以看到结果:
下面是读取多个图片并存盘的代码.
import numpy as np
import struct
import matplotlib.pyplot as plt
filename = r'D:\source\technology_source\data\t10k-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')
for i in range(30): # 读取前30张图片
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.axis('off')
plt.imshow(im, cmap='gray')
plt.savefig("test" + str(i) + ".png")
plt.close()
binfile.close()
另外一种方法
参考tensorflow中mnist模块的方法读取,代码如下
import gzip
import numpy
import matplotlib.pyplot as plt
filepath = r"D:\train-images-idx3-ubyte.gz"
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
def imagine_arr(filepath, index):
with open(filepath, 'rb') as f:
with gzip.GzipFile(fileobj=f) as bytestream:
magic = _read32(bytestream)
if magic != 2051:
raise ValueError('Invalid magic number %d in MNIST image file: %s' % (magic, f.name))
num = _read32(bytestream) # 几张图片
rows = _read32(bytestream)
cols = _read32(bytestream)
if index >= num:
index = 0
bytestream.read(rows * cols * index)
buf = bytestream.read(rows * cols)
data = numpy.frombuffer(buf, dtype=numpy.ubyte)
return data.reshape(rows, cols)
im = imagine_arr(filepath, 0) # 显示第0张
fig = plt.figure()
plotwindow = fig.add_subplot(111)
plt.axis('off')
plt.imshow(im, cmap='gray')
plt.show()
plt.close()
用的是numpy里面的方法.函数_read32作用是读取4个字节,以大端的方式转化成无符号整型.其余代码逻辑和之前的类似.
一次显示多张
import gzip
import numpy
import matplotlib.pyplot as plt
filepath = r"D:\PrjGit\AI\py35ts100\tstutorial\asset\data\mnist\train-images-idx3-ubyte.gz"
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
def imagine_arr(filepath):
with open(filepath, 'rb') as f:
with gzip.GzipFile(fileobj=f) as bytestream:
magic = _read32(bytestream)
if magic != 2051:
raise ValueError('Invalid magic number %d in MNIST image file: %s' % (magic, f.name))
_read32(bytestream) # 几张图片
rows = _read32(bytestream)
cols = _read32(bytestream)
img_num = 64
buf = bytestream.read(rows * cols * img_num)
data = numpy.frombuffer(buf, dtype=numpy.ubyte)
return data.reshape(img_num, rows, cols, 1)
im_data = imagine_arr(filepath)
fig, axes = plt.subplots(8, 8)
for l, ax in enumerate(axes.flat):
ax.imshow(im_data[l].reshape(28, 28), cmap='gray')
ax.set_xticks([])
ax.set_yticks([])
plt.show()
plt.close()
参考资料
- python struct官方文档
- Big and Little Endian
- python读取mnist 2012
- mnist数据集官网
- Not another MNIST tutorial with TensorFlow 2016
python读取,显示,保存mnist图片的更多相关文章
- Python读取excel中的图片
作为Java程序员,Java自然是最主要的编程语言.但是Java适合完成大型项目,对于平时工作中小的工作任务,需要快速完成,易于修改和调试,使用Java显得很繁琐,需要进行类的设计,打成jar包,出现 ...
- 读取多张MNIST图片与利用BaseEstimator基类创建分类器
读取多张MNIST图片 在读取多张MNIST图片之前,我们先来看下读取单张图片如何实现 每张数字图片大小都为28 * 28的,需要将数据reshape成28 * 28的,采用最近邻插值,如下 def ...
- python 读取、保存、二值化、灰度化图片+opencv处理图片的方法
http://blog.csdn.net/johinieli/article/details/69389980
- c++ 读取、保存单张图片
转载:https://www.jb51.net/article/147896.htm 实际上就是以二进制形式打开文件,将数据保存到内存,在以二进制形式输出到指定文件.因此对于有图片的文件,也可以用这种 ...
- Python 读取图像文件的性能对比
Python 读取图像文件的性能对比 使用 Python 读取一个保存在本地硬盘上的视频文件,视频文件的编码方式是使用的原始的 RGBA 格式写入的,即无压缩的原始视频文件.最开始直接使用 Pytho ...
- opencv-python教程学习系列2-读取/显示/保存图像
前言 opencv-python教程学习系列记录学习python-opencv过程的点滴,本文主要介绍图像的读取.显示以及保存,坚持学习,共同进步. 系列教程参照OpenCV-Python中文教程: ...
- python 读取并显示图片的两种方法
在 python 中除了用 opencv,也可以用 matplotlib 和 PIL 这两个库操作图片.本人偏爱 matpoltlib,因为它的语法更像 matlab. 一.matplotlib 1. ...
- DIB位图文件的格式、读取、保存和显示(转载)
一.位图文件结构 位图文件由三部分组成:文件头 + 位图信息 + 位图像素数据 1.位图文件头:BitMapFileHeader.位图文件头主要用于识别位图文件.以下是位图文件头结构的定义: type ...
- python读取mnist
python读取mnist 其实就是python怎么读取binnary file mnist的结构如下,选取train-images TRAINING SET IMAGE FILE (train-im ...
随机推荐
- Windows下Apache与PHP的安装与配置
下载Apache Apache的官网(http://httpd.apache.org) 1.把解压后的Apache拷贝到要安装的目标位置.建议拷贝到C盘根目录下,因为这是其默认设置. 2.我选择的是拷 ...
- PHP Laravel5实现的RBAC权限管理操作示例
根据不同的权限,在菜单栏显示不同的功能,只对菜单进行了限制,若对路由也进行限制,可以根据菜单的例子,请自行完善,开发.下面请认真学习一下laravel的RBAC设计 1.建表(用户表.角色表.权限表. ...
- hdu 1874 畅通工程续 (dijkstra(不能用于负环))
畅通工程续Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submis ...
- Linq三表连接查询加分组
1.Linq查询 2.数据库事例: 3.效果图:
- 领扣(LeetCode)寻找峰值 个人题解
峰值元素是指其值大于左右相邻值的元素. 给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引. 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位 ...
- 《Git的常用操作》
Git的常用操作: git checkout -b 本地分支 #创建本地的分支—本地分支,并切换到该分支下. git branch --set-upstream-to=origin/远程分支 本地分支 ...
- vim python extension
1. 检查vim 版本,需高于7.3. 2. Install extension manager : Vundle git clone https://github.com/gmarik/Vundle ...
- source for "Android 28 platform" not found
source for "Android 28 platform" not found 解决办法:点击右上角的Download,但是下载完点击Refresh之后没有反应,这时候需要重 ...
- 在WebView中加载HTML页面时显示进度对话框的方法
webView.setWebViewClient(new WebViewClient(){ ProgressDialog prDialog; @Overri ...
- [Odoo12基础教程]之第一篇-创建Todo应用
声明: 本教程基于 Ruter 老师的 [Odoo基础教程系列] ,Ruter老师教程的链接地址为:Odoo基础教程系列 . 至于为什么已经有了Ruter老师的教程,还要自己再搬移一份呢?是基于一 ...