Reference article:
http://www.csuldw.com/2016/02/25/2016-02-25-machine-learning-MNIST-dataset/
ImportNumPy as NPImportstructImportMatplotlib.pyplot as PltImportOsfilename='Data_ai/mnist/train-images.idx3-ubyte'Binfile= open (filename,'RB') BUF=binfile.read () index=0magic, Numimages, NumRows, NumColumns= Struct.unpack_from ('>IIII', buf, index) index+ = Struct.calcsize ('IIII') Images= [] forIinchRange (numimages): Imgval= Struct.unpack_from ('>784b', buf, index) index+ = Struct.calcsize ('>784b') Imgval=list (imgval) forJinchRange (len (imgval)):ifIMGVAL[J] > 1: Imgval[j]= 1images.append (imgval) Arrx=Np.array (IMAGES)#Reading LabelsBinfile = open ('Data_ai/mnist/train-labels.idx1-ubyte','RB') BUF=Binfile.read () binfile.close () index=0magic, NumItems= Struct.unpack_from ('>ii', Buf,index) index+ = Struct.calcsize ('>ii') Labels= [] forXinchRange (NumItems): Im= Struct.unpack_from ('>1b', Buf,index) index+ = Struct.calcsize ('>1b') Labels.append (im[0]) Arry=Np.array (labels)Print(Np.shape (arry))#Print (Np.shape (trainx))#The following is an image saved to a local filePath_trainset ="Data_ai/mnist/imgs_train"Path_testset="data_ai/mnist/imgs_test"if notos.path.exists (Path_trainset): Os.mkdir (Path_trainset)if notos.path.exists (Path_testset): Os.mkdir (Path_testset) forIinchRange (1): IMG=Np.array (Arrx[i])Print(IMG) img= Img.reshape (28,28) outfile= str (i) +"_"+ str (arry[i]) +". PNG" #outfile = str (i) + ". png"plt.figure () plt.imshow (IMG, cmap='binary')#display the image in black and whitePlt.savefig (Path_trainset +"/"+outfile)Print("Save"+str (i) +"Zhang")
Storing the Mnist dataset to a local file