Python讀入mnist二進(jìn)制圖像文件并顯示實例
圖像文件是自己仿照mnist格式制作,每張圖像大小為128*128
import struct
import matplotlib.pyplot as plt
import numpy as np
#讀入整個訓(xùn)練數(shù)據(jù)集圖像
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 圖片轉(zhuǎn)數(shù)組,二進(jìn)制互轉(zhuǎn)
前言
需要導(dǎo)入以下包,沒有的通過pip安裝
import matplotlib.pyplot as plt import cv2 from PIL import Image from io import BytesIO import numpy as np
1.圖片和數(shù)組互轉(zhuǎn)
# 圖片轉(zhuǎn)numpy數(shù)組
img_path = "images/1.jpg"
img_data = cv2.imread(img_path)
# numpy數(shù)組轉(zhuǎn)圖片
img_data = np.linspace(0,255,100*100*3).reshape(100,100,-1).astype(np.uint8)
cv2.imwrite("img.jpg",img_data) # 在當(dāng)前目錄下會生成一張img.jpg的圖片
2.圖片和二進(jìn)制格式互轉(zhuǎn)
# 以 二進(jìn)制方式 進(jìn)行圖片讀取
with open("img.jpg","rb") as f:
img_bin = f.read() # 內(nèi)容讀取
# 將 圖片的二進(jìn)制內(nèi)容 轉(zhuǎn)成 真實圖片
with open("img.jpg","wb") as f:
f.write(img_bin) # img_bin里面保存著 以二進(jìn)制方式讀取的圖片內(nèi)容,當(dāng)前目錄會生成一張img.jpg的圖片
3.數(shù)組 和 圖片二進(jìn)制數(shù)據(jù)互轉(zhuǎn)
"""
以上兩種方式"合作"也可以實現(xiàn),但是中間會有對外存的讀寫
一般這些到磁盤的IO操作還是很耗時間的
所以在內(nèi)存直接處理會較好
"""
# 將數(shù)組轉(zhuǎn)成 圖片的二進(jìn)制數(shù)據(jù)
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()
# 將圖片二進(jìn)制數(shù)據(jù) 轉(zhuǎn)為數(shù)組
img_data = plt.imread(BytesIO(img_bin),"jpg")
print(type(img_data))
print(img_data.shape)
"""
out:
<class 'numpy.ndarray'>
(100, 100, 3)
"""
或許還有別的方式也能實現(xiàn) 圖片二進(jìn)制數(shù)據(jù) 和 數(shù)組的轉(zhuǎn)換,不足之處希望大家指出
以上這篇Python讀入mnist二進(jìn)制圖像文件并顯示實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
keras tensorflow 實現(xiàn)在python下多進(jìn)程運行
今天小編就為大家分享一篇keras tensorflow 實現(xiàn)在python下多進(jìn)程運行,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02

