久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Python讀入mnist二進制圖像文件并顯示實例

瀏覽:56日期:2022-07-27 16:36:16

圖像文件是自己仿照mnist格式制作,每張圖像大小為128*128

import structimport matplotlib.pyplot as pltimport numpy as np#讀入整個訓練數據集圖像filename = ’train-images-idx3-ubyte’binfile = open(filename, ’rb’)buf = binfile.read()#讀取頭四個32bit的intergerindex = 0magic, numImages, numRows, numColumns = struct.unpack_from(’>IIII’, buf, index)index += struct.calcsize(’>IIII’)#讀取一個圖片,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()

補充知識:Python 圖片轉數組,二進制互轉

前言

需要導入以下包,沒有的通過pip安裝

import matplotlib.pyplot as pltimport cv2from PIL import Imagefrom io import BytesIOimport 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 編程
相關文章:
主站蜘蛛池模板: 庆元县| 华安县| 隆尧县| 宣汉县| 锡林郭勒盟| 屏东县| 东光县| 错那县| 桓台县| 五河县| 株洲市| 深圳市| 吉木乃县| 拉萨市| 谢通门县| 英德市| 日喀则市| 黎川县| 枝江市| 科技| 吉安县| 夏邑县| 襄樊市| 屯昌县| 犍为县| 乐都县| 莫力| 固镇县| 高碑店市| 繁昌县| 台中县| 多伦县| 云林县| 临潭县| 达州市| 鹤岗市| 温宿县| 屏山县| 曲沃县| 新郑市| 牙克石市|