covert mnist binary file to mat in matlab in matlab

To convert binary mnist files to mat file in Matlab, you can use the following code. This assumes that the binary files are in the same directory as your Matlab script.

main.m
% Open the binary files for reading
trainImagesFile = fopen('train-images-idx3-ubyte','r','b');
trainLabelsFile = fopen('train-labels-idx1-ubyte','r','b');
testImagesFile = fopen('t10k-images-idx3-ubyte','r','b');
testLabelsFile = fopen('t10k-labels-idx1-ubyte','r','b');

% Read the magic numbers and dataset sizes
fread(trainImagesFile,1,'int32',0,'b');
fread(trainImagesFile,1,'int32',0,'b');
fread(trainImagesFile,1,'int32',0,'b');
fread(trainImagesFile,1,'int32',0,'b');
numTrain = fread(trainLabelsFile,1,'int32',0,'b');
fread(testImagesFile,1,'int32',0,'b');
fread(testImagesFile,1,'int32',0,'b');
fread(testImagesFile,1,'int32',0,'b');
fread(testImagesFile,1,'int32',0,'b');
numTest = fread(testLabelsFile,1,'int32',0,'b');

% Read the actual image and label data
trainData = permute(reshape(fread(trainImagesFile,[28,28,numTrain],'uchar'),[28 28 1 numTrain]),[2 1 3 4]);
trainLabels = fread(trainLabelsFile,numTrain,'uchar');
testData = permute(reshape(fread(testImagesFile,[28,28,numTest],'uchar'),[28 28 1 numTest]),[2 1 3 4]);
testLabels = fread(testLabelsFile,numTest,'uchar');

% Close the binary files
fclose(trainImagesFile);
fclose(trainLabelsFile);
fclose(testImagesFile);
fclose(testLabelsFile);

% Save the data to a mat file
save('mnist_data.mat','trainData','trainLabels','testData','testLabels');
1320 chars
33 lines

The above code will produce a mat file called "mnist_data.mat" which contains the training and test data as matrices.

gistlibby LogSnag