mnist file to mat in matlab

To load an MNIST file in matlab, you can use the following code:

main.m
function data = loadMNISTImages(filename)
% This function reads in MNIST images and returns them in a matrix
fp = fopen(filename, 'rb');
assert(fp ~= -1, ['Could not open ', filename, '']);

magic = fread(fp, 1, 'int32', 0, 'ieee-be');
assert(magic == 2051, ['Bad magic number in ', filename, '']);

numImages = fread(fp, 1, 'int32', 0, 'ieee-be');
numRows = fread(fp, 1, 'int32', 0, 'ieee-be');
numCols = fread(fp, 1, 'int32', 0, 'ieee-be');

data = fread(fp, inf, 'unsigned char');
data = reshape(data, numCols, numRows, numImages);
data = permute(data,[2 1 3]);

fclose(fp);
end
582 chars
19 lines

Assuming that the filename variable contains the path to the MNIST image file, running the loadMNISTImages function will return a numRows x numCols x numImages matrix containing the MNIST images.

For example, to load the MNIST training images and display the first image, you can use the following code:

main.m
images = loadMNISTImages('train-images-idx3-ubyte');
imshow(images(:,:,1)');
77 chars
3 lines

Note that the transpose is used when displaying the image because matlab reads in the image data in row-major order, while images are usually displayed in column-major order.

gistlibby LogSnag