Python讀入mnist二進制圖像文件并顯示實例
圖像文件是自己仿照mnist格式制作,每張圖像大小為128*128
import struct import matplotlib.pyplot as plt import numpy as np #讀入整個訓練數(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 圖片轉數(shù)組,二進制互轉
前言
需要導入以下包,沒有的通過pip安裝
import matplotlib.pyplot as plt import cv2 from PIL import Image from io import BytesIO import numpy as np
1.圖片和數(shù)組互轉
# 圖片轉numpy數(shù)組 img_path = "images/1.jpg" img_data = cv2.imread(img_path) # numpy數(shù)組轉圖片 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() # 內(nèi)容讀取 # 將 圖片的二進制內(nèi)容 轉成 真實圖片 with open("img.jpg","wb") as f: f.write(img_bin) # img_bin里面保存著 以二進制方式讀取的圖片內(nèi)容,當前目錄會生成一張img.jpg的圖片
3.數(shù)組 和 圖片二進制數(shù)據(jù)互轉
""" 以上兩種方式"合作"也可以實現(xiàn),但是中間會有對外存的讀寫 一般這些到磁盤的IO操作還是很耗時間的 所以在內(nèi)存直接處理會較好 """ # 將數(shù)組轉成 圖片的二進制數(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() # 將圖片二進制數(shù)據(jù) 轉為數(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) 圖片二進制數(shù)據(jù) 和 數(shù)組的轉換,不足之處希望大家指出
以上這篇Python讀入mnist二進制圖像文件并顯示實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python框架Django實戰(zhàn)商城項目之工程搭建過程圖文詳解
這篇文章主要介紹了python框架Django實戰(zhàn)商城項目之工程搭建過程,這個項目很像京東商城,項目開發(fā)采用前后端不分離的模式,本文通過圖文并茂的形式給大家介紹的非常詳細,需要的朋友可以參考下2020-03-03virtualenv隔離Python環(huán)境的問題解析
virtualenv為應用提供了隔離的Python運行環(huán)境,解決了不同應用間多版本的沖突問題,這篇文章主要介紹了virtualenv隔離Python環(huán)境,需要的朋友可以參考下2022-06-06Python探索之靜態(tài)方法和類方法的區(qū)別詳解
這篇文章主要介紹了Python探索之靜態(tài)方法和類方法的區(qū)別詳解,小編覺得還是挺不錯的,這里分享給大家,供需要的朋友參考。2017-10-10Python機器學習應用之基于BP神經(jīng)網(wǎng)絡的預測篇詳解
BP(back?propagation)神經(jīng)網(wǎng)絡是1986年由Rumelhart和McClelland為首的科學家提出的概念,是一種按照誤差逆向傳播算法訓練的多層前饋神經(jīng)網(wǎng)絡,是應用最廣泛的神經(jīng)網(wǎng)絡模型之一2022-01-01