【MNIST/Python】手寫體數字訓練/測試資料集(圖片格式)下載及分割預處理
阿新 • • 發佈:2018-11-01
MNIST手寫體數字資料集
MNIST是一個手寫數字資料庫,它有60000個訓練樣本集和10000個測試樣本集
由Yann LeCun等人建立,是NIST資料庫的一個子集
官方網址連結:Link
官網上的資料庫檔案形式如下:
train-images-idx3-ubyte.gz: training set images (9912422 bytes)
train-labels-idx1-ubyte.gz: training set labels (28881 bytes)
t10k-images-idx3-ubyte.gz: test set images (1648877 bytes)
t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes)
下載並解壓縮後發現這些檔案並不是標準的影象格式,而是以二進位制的形式儲存在檔案中,每個樣本影象的邊長尺寸均為28*28
現今已經有不少方法將原始的二進位制資料樣本轉化為如下的圖片格式:
這裡提供一種按照訓練/測試樣本和數字類別(2×10)進行分類的圖片格式資料集(*.jpg),幷包含對應的預處理程式碼,下載連結:Link
單個數字分割預處理
轉換為圖片後,資料集變為了多個數字圖片的整體堆疊,仍然不利於進一步使用
因此需要對其進行一些預處理,將整張圖片分割為多個單獨的手寫體數字,並進行額外儲存
使用Python編寫的預處理程式碼示例如下:
【MNIST_extraction.py】
#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
MNIST Preprocessing
@Author: Alex Pan
@From: CASIA
@Date: 2017.03
'''
import os
import cv2
import ipdb
########################### Global Parameters ###################################
trainFolder = 'train'
testFolder = 'test'
trainPrefix = 'mnist_train'
testPrefix = 'mnist_test'
postfix = '.jpg'
sideLength = 28
########################### Global Parameters ###################################
############################ Initialization #####################################
ROOT = os.getcwd() # MUST run in the directory of this very script
############################ Initialization #####################################
# Extract & Save each single-number image of MNIST
def MNIST_extract(folder, prefix):
print 'Category:', folder, prefix
# For each number from 0 to 9
for i in xrange(0, 10):
print 'Class:', str(i)
# Read over-all image of each class
allImage = cv2.imread(os.path.join(ROOT, folder, prefix + str(i) + postfix))
print 'Shape:', allImage.shape[0 : 2]
count = 0
print 'Processing ...'
for corY in xrange(0, allImage.shape[1] / sideLength):
for corX in xrange(0, allImage.shape[0] / sideLength):
count += 1
# Cropped image of single-number
singleImage = allImage[corX * sideLength : (corX + 1) * sideLength,
corY * sideLength : (corY + 1) * sideLength,
:]
''' Show
cv2.imshow('Single Number', singleImage)
cv2.waitKey(1)
# '''
# ''' Save
saveLocation = os.path.join(ROOT, folder, str(i), prefix + str(i) + '_' + str(count) + postfix)
cv2.imwrite(saveLocation, singleImage)
# ipdb.set_trace()
# '''
print 'Count:', count, 'All Saved.'
cv2.destroyAllWindows()
##########################
if __name__ == '__main__':
# ''' \SWITCH/ : train OR test
MNIST_extract(trainFolder, trainPrefix)
''' # \Division/
MNIST_extract(testFolder, testPrefix)
# ''' # \END/
注意事項:
- 程式須在程式碼原始檔目錄執行(包含train和test目錄)
- 分割出的單個數字圖片儲存在train和test目錄中的子資料夾中,子資料夾名對應數字類別(0~9),單個數字的檔名也具有一定的格式,便於後續呼叫
- 以上引數均可根據需要自行修改
- 程式程式碼亦包含在資料集的下載連結中:Link
Reference
[1] THE MNIST DATABASE of handwritten digits
[2] MNIST資料庫介紹及轉換 - fengbingchun
希望能夠對大家有所幫助~