利用keras(tensorflow) 做cnn mnist識(shí)別
使用Python解析MNIST數(shù)據(jù)集(IDX文件格式)
python中range()和len()函數(shù)區(qū)別
Python圖像處理庫PIL中圖像格式轉(zhuǎn)換(一)
Numpy數(shù)據(jù)類型對(duì)象(dtype)
需要解決有兩個(gè)方案:
方案1:修改python代碼,使用下載的mnist數(shù)據(jù)集
JPG、PNG與MNIST數(shù)據(jù)集之間的轉(zhuǎn)換
代碼解釋見下面

Label File
先是一個(gè)32位的整形 表示的是Magic Number,這是用來標(biāo)示文件格式的用的。一般默認(rèn)不變,為2049
第二是圖片的的數(shù)量
接下去就是一次排列圖片的標(biāo)示Label。
-
也是Magic Number。同上。保持不變2051.
圖片的數(shù)量
圖片的高
圖片的寬
圖片的像素點(diǎn)[灰度 256位]。
unpack(fmt, string) ? ? ? 按照給定的格式(fmt)解析字節(jié)流string,返回解析出來的tuple
> big-endian standard?????? 按原字節(jié)數(shù)
見上圖:圖片寬高分別為28,所以有28*28=784個(gè)值
代碼:
import os
import struct
import numpy as np
def load_mnist(path, kind='train'):
print("in load_mnist")
"""Load MNIST data from `path`"""? #注釋
labels_path = os.path.join(path,'%s-labels.idx1-ubyte'%kind) #路徑+train-labels-idx1-ubyte(gz文件)
images_path = os.path.join(path,'%s-images.idx3-ubyte'%kind) #路徑+train-labels-idx1-ubyte(gz文件)
with open(labels_path, 'rb') as lbpath: #以二進(jìn)制格式打開文件train-labels-idx1-ubyte用于只讀,lbpath代表此文件對(duì)象
#從文件中讀8個(gè)字節(jié),1-4個(gè)字節(jié)為magic number,4-8個(gè)字節(jié)為圖片數(shù)量,magic和n均為無符號(hào)整形? ? ?
magic, n = struct.unpack('>II',lbpath.read(8)) #>? big-endian 高字節(jié)在高位 II兩個(gè)無符號(hào)整形,每個(gè)占4個(gè)字節(jié)
labels = np.fromfile(lbpath,dtype=np.uint8)
print("labels length=%d"%len(labels))
with open(images_path, 'rb') as imgpath:
#從文件中讀16個(gè)字節(jié),1-4個(gè)字節(jié)為magic number,4-8個(gè)字節(jié)為圖片數(shù)量,rows為圖片的高,cols為圖片的寬,magic,num,rows,cols均為無符號(hào)整形
magic, num, rows, cols = struct.unpack('>IIII',imgpath.read(16))#> big-endian 高字節(jié)在高位IIII四個(gè)無符號(hào)整形,每個(gè)占4個(gè)字節(jié)
#讀取圖片數(shù)據(jù),并轉(zhuǎn)換為 60,000行784列的矩陣,也就是說一行是一張圖片
images = np.fromfile(imgpath,dtype=np.uint8).reshape(len(labels), 784)
print("images length=%d"%len(images))
return images, labels
if __name__=='__main__':
images_train,labels_train=load_mnist('', kind='train') #cd mnist python load_mnist.py執(zhí)行當(dāng)前程序
print("images")
print (images_train)
print("labels")
print (labels_train)
print('Rows: %d, columns: %d' % (images_train.shape[0], images_train.shape[1]))
count = np.zeros(10)
nTrain = len(images_train)
for i in range(nTrain):
label = labels_train[i]
count[label] += 1
filename = './train/' + str(label) + '/' + str(label) + '_' + str(int(count[label])) + '.png'
print(filename)
img = images_train[i].reshape(28,28)
cv2.imwrite(filename, img) #找不到圖片?
print(str(int(count[label])))
print("over")
方案2:mnist數(shù)據(jù)集轉(zhuǎn)成圖片用現(xiàn)在的代碼