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

参考资料

  1. python struct官方文档
  2. Big and Little Endian
  3. python读取mnist 2012
  4. mnist数据集官网
  5. Not another MNIST tutorial with TensorFlow 2016

python读取,显示,保存mnist图片的更多相关文章

  1. Python读取excel中的图片

    作为Java程序员,Java自然是最主要的编程语言.但是Java适合完成大型项目,对于平时工作中小的工作任务,需要快速完成,易于修改和调试,使用Java显得很繁琐,需要进行类的设计,打成jar包,出现 ...

  2. 读取多张MNIST图片与利用BaseEstimator基类创建分类器

    读取多张MNIST图片 在读取多张MNIST图片之前,我们先来看下读取单张图片如何实现 每张数字图片大小都为28 * 28的,需要将数据reshape成28 * 28的,采用最近邻插值,如下 def ...

  3. python 读取、保存、二值化、灰度化图片+opencv处理图片的方法

    http://blog.csdn.net/johinieli/article/details/69389980

  4. c++ 读取、保存单张图片

    转载:https://www.jb51.net/article/147896.htm 实际上就是以二进制形式打开文件,将数据保存到内存,在以二进制形式输出到指定文件.因此对于有图片的文件,也可以用这种 ...

  5. Python 读取图像文件的性能对比

    Python 读取图像文件的性能对比 使用 Python 读取一个保存在本地硬盘上的视频文件,视频文件的编码方式是使用的原始的 RGBA 格式写入的,即无压缩的原始视频文件.最开始直接使用 Pytho ...

  6. opencv-python教程学习系列2-读取/显示/保存图像

    前言 opencv-python教程学习系列记录学习python-opencv过程的点滴,本文主要介绍图像的读取.显示以及保存,坚持学习,共同进步. 系列教程参照OpenCV-Python中文教程: ...

  7. python 读取并显示图片的两种方法

    在 python 中除了用 opencv,也可以用 matplotlib 和 PIL 这两个库操作图片.本人偏爱 matpoltlib,因为它的语法更像 matlab. 一.matplotlib 1. ...

  8. DIB位图文件的格式、读取、保存和显示(转载)

    一.位图文件结构 位图文件由三部分组成:文件头 + 位图信息 + 位图像素数据 1.位图文件头:BitMapFileHeader.位图文件头主要用于识别位图文件.以下是位图文件头结构的定义: type ...

  9. python读取mnist

    python读取mnist 其实就是python怎么读取binnary file mnist的结构如下,选取train-images TRAINING SET IMAGE FILE (train-im ...

随机推荐

  1. QKD 一些术语的含义

    密钥率:每个信道使用的比特数. 系统开销:不能用来提取最终密钥的信号百分比. SNU:散粒噪声单元 RNG:随机数发生器 QRNG:量子随机数发生器 TRNG:真正的随机数生成器 PRNG:伪随机数发 ...

  2. nyoj 99-单词拼接 (euler, dfs)

    99-单词拼接 内存限制:64MB 时间限制:3000ms 特判: No 通过数:7 提交数:14 难度:5 题目描述: 给你一些单词,请你判断能否把它们首尾串起来串成一串. 前一个单词的结尾应该与下 ...

  3. django_5:表单1——文件上传

    上传文件1 class UserForm(forms.Form): name = forms.CharField() headImg = forms.FileField() def regist(re ...

  4. Redux第一节

    安装脚手架 npm i -g create-react-app 创建一个Dom create-react-app demo01 安装 Ant Design npm i antd --save 安装re ...

  5. vue的一些小记录

    1.在一个标签中,不推荐v-for 与 v-if 同时用 //当 v-if 与 v-for,v-for 具有比 v-if 更高的优先级. //当它们处于同一节点(同一标签 一起使用时),v-for 的 ...

  6. MyBatis 数值类型 where 条件配置的坑

    复现异常 我们先通过案例复现该类异常,测试项目地址:https://gitee.com/yin_jw/demo/tree/master/mybatis-demo/springboot-mybatis- ...

  7. 超速入门AT指令集 | 我的物联网成长记

    [摘要] 在物联网中,AT命令集可用于控制&调测设备.通信模块入网等.本文为您介绍NB-IoT常用的AT命令集及其调测工具. 什么是AT指令集 AT命令,用来控制TE(Terminal Equ ...

  8. DDCTF2019 的四道题wp

    MIsc:流量分析 这道题,在比赛的时候就差个key了,但是没想到要改高度,后来群里师傅说了下,就再试试, 导出来改高度. 导出来,把 把%5c(4)前面的hex删掉,改成png,就直接拿去那个img ...

  9. Shell - 长 ping 脚本监控网络时延

    生产环境中, 网络时延是一个很重要的指标. 为了方便检查网络时延的大小, 我们可以通过ping命令实现长时间的网络监控. 1 ping 命令的使用 1.1 常用参数 -i: 每次执行ping操作的间隔 ...

  10. 五分钟了解物联网SIM卡 | 我的物联网成长记10

    [摘要] SIM卡是移动通信中不可或缺的组成部分,在物联网解决方案中,设备移动上网也需要使用SIM卡.那么,SIM卡是什么?SIM卡有几种?各种SIM卡有什么区别?本文将为您答疑解惑. 通信进化史 过 ...