Python读入mnist二进制图像文件并显示实例
2020-04-25 12:03
555 查看
图像文件是自己仿照mnist格式制作,每张图像大小为128*128
import struct import matplotlib.pyplot as plt import numpy as np #读入整个训练数据集图像 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') #读取一个图片,16384=128*128 im = struct.unpack_from('>16384B', buf, index) index += struct.calcsize('>16384B') im=np.array(im) im=im.reshape(128,128) fig = plt.figure() plotwindow = fig.add_subplot(111) plt.imshow(im, cmap = 'gray') plt.show()
补充知识:Python 图片转数组,二进制互转
前言
需要导入以下包,没有的通过pip安装
import matplotlib.pyplot as plt import cv2 from PIL import Image from io import BytesIO import numpy as np
1.图片和数组互转
# 图片转numpy数组 img_path = "images/1.jpg" img_data = cv2.imread(img_path) # numpy数组转图片 img_data = np.linspace(0,255,100*100*3).reshape(100,100,-1).astype(np.uint8) cv2.imwrite("img.jpg",img_data) # 在当前目录下会生成一张img.jpg的图片
2.图片和二进制格式互转
# 以 二进制方式 进行图片读取 with open("img.jpg","rb") as f: img_bin = f.read() # 内容读取 # 将 图片的二进制内容 转成 真实图片 with open("img.jpg","wb") as f: f.write(img_bin) # img_bin里面保存着 以二进制方式读取的图片内容,当前目录会生成一张img.jpg的图片
3.数组 和 图片二进制数据互转
""" 以上两种方式"合作"也可以实现,但是中间会有对外存的读写 一般这些到磁盘的IO操作还是很耗时间的 所以在内存直接处理会较好 """ # 将数组转成 图片的二进制数据 img_data = np.linspace(0,255,100*100*3).reshape(100,100,-1).astype(np.uint8) ret,buf = cv2.imencode(".jpg",img_data) img_bin = Image.fromarray(np.uint8(buf)).tobytes() # 将图片二进制数据 转为数组 img_data = plt.imread(BytesIO(img_bin),"jpg") print(type(img_data)) print(img_data.shape) """ out: <class 'numpy.ndarray'> (100, 100, 3) """
或许还有别的方式也能实现 图片二进制数据 和 数组的转换,不足之处希望大家指出
以上这篇Python读入mnist二进制图像文件并显示实例就是小编分享给大家的全部内容了,希望能给大家一个参考
您可能感兴趣的文章:
相关文章推荐
- Python读入mnist二进制图像文件并显示
- 图像文件读入和显示
- Opencv学习手册(一)--- 图像文件读入和显示
- OpenCV- 图像文件读入和显示
- 读入图像文件并显示【C#图像处理学习笔记】
- python opencv入门(读 / 写 显示以及转换图像 和 视频读入)
- 利用Python+opencv进行视频文件的读取和保存,打开笔记本摄像头拍照保存、图像在窗口显示等操作
- 初学openCV 之从文件中读入一幅图像,将之反色并显示
- FileReader详解与实例---读取并显示图像文件
- OpenCV与Python之图像的读入与显示以及利用Numpy的图像转换
- Python读取MRI并显示为灰度图像实例代码
- FileReader详解与实例---读取并显示图像文件
- 利用opencv进行图像文件读入和显示
- python实例26[将log同时写入文件和显示到UI的控件中]
- FileReader详解与实例---读取并显示图像文件 | JS Mix
- 图像文件的读入、显示、保存
- FileReader详解与实例---读取并显示图像文件
- python实例26[将log同时写入文件和显示到UI的控件中]
- 图像文件读入和显示
- FileReader详解与实例---读取并显示图像文件