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. SpringBoot 源码解析 (三)----- Spring Boot 精髓:启动时初始化数据

    在我们用 springboot 搭建项目的时候,有时候会碰到在项目启动时初始化一些操作的需求 ,针对这种需求 spring boot为我们提供了以下几种方案供我们选择: ApplicationRunn ...

  2. Algorithm: GCD、EXGCD、Inverse Element

    数论基础 数论是纯数学的一个研究分支,主要研究整数的性质.初等数论包括整除理论.同余理论.连分数理论.这一篇主要记录的是同余相关的基础知识. 取模 取模是一种运算,本质就是带余除法,运算结果就是余数. ...

  3. mysql 创建用户及授权(1)

    一. 创建用户 命令: CREATE USER 'username'@'host' IDENTIFIED BY 'password'; 说明: username:你将创建的用户名 host:指定该用户 ...

  4. nyoj 596-谁是最好的Coder (greater, less)

    596-谁是最好的Coder 内存限制:64MB 时间限制:1000ms 特判: No 通过数:15 提交数:28 难度:0 题目描述: 计科班有很多Coder,帅帅想知道自己是不是综合实力最强的co ...

  5. Unix, Linux以及NT内核和它们各自衍生的系统关系图

  6. 简单地迁移你的android jni代码逻辑到iOS - 编写iOS下jni.h的替代 - ocni.h

    1. jni的代码逻辑中与上层平台语言交互了. 2. 使用非Xcode的ide开发工具,希望使用纯净的c/c++代码,不掺杂其它平台相关的语言语法. 3. 只想简单地替换jni代码对上层平台语言的功能 ...

  7. SpringBoot学习(一)—— idea 快速搭建 Spring boot 框架

    简介 优点 Spring Boot 可以以jar包的形式独立运行,运行一个Spring Boot 项目只需要通过 java -jar xx.jar 来运行. Spring Boot 可以选择内嵌Tom ...

  8. js 根据指定的多个索引,删除相应的数组元素。splice + sort

    更新于2018-04-19 var productItems = ["a", "b", "c", "d"]; var i ...

  9. 实现自定义的参数解析器——HandlerMethodArgumentResolver

    1.为什么需要自己实现参数解析器 我们都知道在有注解的接口方法中加上@RequestBody等注解,springMVC会自动的将消息体等地方的里面参数解析映射到请求的方法参数中. 如果我们想要的信息不 ...

  10. 我的第一个python web 开发框架

    1:数据库结构设计与创建 小白做好前端html设计后,马上开始进入数据库结构设计步骤. 在开始之前,小白回忆了一下老大在公司里培训时讲过的数据库设计解说: 对于初学者来说,很多拿到原型时不知道怎么设计 ...