溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python如何讀入mnist二進(jìn)制圖像文件并顯示

發(fā)布時間:2020-07-31 09:36:34 來源:億速云 閱讀:217 作者:小豬 欄目:開發(fā)技術(shù)

小編這次要給大家分享的是Python如何讀入mnist二進(jìn)制圖像文件并顯示,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。

圖像文件是自己仿照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()

補(bǔ)充知識: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)成 真實(shí)圖片
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)

"""
以上兩種方式"合作"也可以實(shí)現(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)
"""

或許還有別的方式也能實(shí)現(xiàn) 圖片二進(jìn)制數(shù)據(jù) 和 數(shù)組的轉(zhuǎn)換,不足之處希望大家指出

看完這篇關(guān)于Python如何讀入mnist二進(jìn)制圖像文件并顯示的文章,如果覺得文章內(nèi)容寫得不錯的話,可以把它分享出去給更多人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI