idx-ubyte文件解析

2017-11-19 02:19

Mnist手寫數字數據庫是著名的神經網絡入門級訓練集,它圖像文件的後綴名一般爲idx3-ubyte,圖像標籤文件後綴名爲idx1-ubyte。它分爲兩種圖像集,一個訓練集,一個測試集。它內置的圖像大小爲28*28,可以在這裏下載:http://yann.lecun.com/exdb/mnist/
    一共四個文件,訓練集和它的標籤集,測試集和它的標籤集,解析規則在頁面中有說明。


這裏通過python的struct庫進行解析:
 

#需要導入的庫,struct是一個很常用的二進制解析庫
import numpy as np 
import struct

 def decode_idx3_ubyte(idx3_ubyte_file):#此函數用來解析idx3文件,idx3_ubyte_filec指定圖像文件路徑
    #讀取二進制數據
    bin_data=open(idx3_ubyte_file,'rb').read()
    #解析文件頭信息,依次爲魔數、圖片數量、每張圖片高、每張圖片寬
    offest=0
    fmt_header='>iiii'    magic_number,num_images,num_rows,num_cols=struct.unpack_from(fmt_header,bin_data,offest)
    print('魔數:%d,圖片數量:%d,圖片大小:%d%d' % (magic_number,num_images,num_rows,num_cols))
    #解析數據集
    image_size=num_rows*num_cols
    offest += struct.calcsize(fmt_header)
    fmt_image='>'+str(image_size)+'B'
    images=np.empty((num_images,num_rows,num_cols))
    for i in range(num_images):
        if (i+1)%10000==0:
            print('已解析%d'%(i+1)+'張')        images[i]=np.array(struct.unpack_from(fmt_image,bin_data,offest)).reshape((num_rows,num_cols))
        offest+=struct.calcsize(fmt_image)
    return images
'''images是一個三維數組,images[i][a][b]表示第i張圖片的倒數第a行,b列的像素'''
def decode_idx1_ubyte(idx1_ubyte_file):#解析idx1文件函數,idx1_ubyte_file指定標籤文件路徑
    #讀取二進制數據
    bin_data=open(idx1_ubyte_file,'rb').read()
    #解析文件頭信息,依次爲魔數和標籤數
    offest=0
    fmt_header='>ii'
    magic_number,num_images=struct.unpack_from(fmt_header,bin_data,offest)
    print('魔數:%d,圖片數量:%d張' % (magic_number,num_images))
    #解析數據集
    offest+=struct.calcsize(fmt_header)
    fmt_image='>B'
    labels=np.empty(num_images)
    for i in range(num_images):
        if (i+1)%10000==0:
            print('已解析:%d'%(i+1)+'張')
        labels[i]=struct.unpack_from(fmt_image,bin_data,offest)[0]
        offest+=struct.calcsize(fmt_image)
    print(labels[0])
    return labels
'''labels是一個一維數組,每個元素都一一對應images[i]'''


運行結果如下:

圖片

                                                                '''————霧雨流雲'''

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章