Python讀入mnist二進(jìn)制圖像文件并顯示實(shí)例
圖像文件是自己仿照mnist格式制作,每張圖像大小為128*128
import structimport matplotlib.pyplot as pltimport numpy as np#讀入整個(gè)訓(xùn)練數(shù)據(jù)集圖像filename = ’train-images-idx3-ubyte’binfile = open(filename, ’rb’)buf = binfile.read()#讀取頭四個(gè)32bit的intergerindex = 0magic, numImages, numRows, numColumns = struct.unpack_from(’>IIII’, buf, index)index += struct.calcsize(’>IIII’)#讀取一個(gè)圖片,16384=128*128im = 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ǔ)充知識(shí):Python 圖片轉(zhuǎn)數(shù)組,二進(jìn)制互轉(zhuǎn)
前言
需要導(dǎo)入以下包,沒(méi)有的通過(guò)pip安裝
import matplotlib.pyplot as pltimport cv2from PIL import Imagefrom io import BytesIOimport 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)前目錄下會(huì)生成一張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)前目錄會(huì)生成一張img.jpg的圖片
3.數(shù)組 和 圖片二進(jìn)制數(shù)據(jù)互轉(zhuǎn)
'''以上兩種方式'合作'也可以實(shí)現(xiàn),但是中間會(huì)有對(duì)外存的讀寫(xiě)一般這些到磁盤(pán)的IO操作還是很耗時(shí)間的所以在內(nèi)存直接處理會(huì)較好'''# 將數(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)換,不足之處希望大家指出
以上這篇Python讀入mnist二進(jìn)制圖像文件并顯示實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. java實(shí)現(xiàn)圖形化界面計(jì)算器2. IntelliJ Idea2017如何修改緩存文件的路徑3. IntelliJ IDEA設(shè)置條件斷點(diǎn)的方法步驟4. IIS Express 取代 ASP.NET Development Server的配置方法5. python flask框架快速入門(mén)6. Spring-Richclient 0.1.0 發(fā)布7. javascript設(shè)計(jì)模式 ? 建造者模式原理與應(yīng)用實(shí)例分析8. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式9. Python使用oslo.vmware管理ESXI虛擬機(jī)的示例參考10. Express 框架中使用 EJS 模板引擎并結(jié)合 silly-datetime 庫(kù)進(jìn)行日期格式化的實(shí)現(xiàn)方法
