使用fread和imageparser

时间:2016-03-29 16:47:36

标签: matlab fread

你好,当我运行上面的代码时,我得到了这个错误。 l不在哪里出错,我的代码(.m)和训练样例都在同一工作目录中。

  

使用fread时出错       文件标识符无效。使用fopen生成有效的文件标识符       MNISTParser出错(第3行)
          magic_number = fread(fp,1,'uint32',0,'b');
      MNIST_gen错误(第2行)
      train_labels = MNISTParser('./ MNIST / train-labels-idx1-ubyte');

MNIST_gen.m

clear
**train_labels = MNISTParser('./MNIST/train-labels-idx1-ubyte');**
train_images = MNISTParser('./MNIST/train-images-idx3-ubyte');
test_labels = MNISTParser('./MNIST/t10k-labels-idx1-ubyte');
test_images = MNISTParser('./MNIST/t10k-images-idx3-ubyte');
test_item_number = length(test_labels);
train_item_number = length(train_labels);
image_scale = size(test_images,2);
test_images_unfold = reshape(test_images,test_item_number,image_scale^2)';
test_labels_unfold = full(ind2vec(test_labels'+1));
train_images_unfold = reshape(train_images,train_item_number,image_scale^2)';
train_labels_unfold = full(ind2vec(train_labels'+1));
save MNIST.mat;

colormap(gray);
axis off
axis image

%show an image of a digit in test samples
for i=1:1
    j=randi(length(test_labels),1);
    image(reshape(255-test_images(j,:,:),28,28));
    title(sprintf('%d',test_labels(j)));
    pause(1);
    image(reshape(test_images_unfold(:,j),28,28));
    title(vec2ind(test_labels_unfold(:,j))-1);
    pause(1);
end    

%show an image of a digit in train samples
for i=1:1
    j=randi(length(train_labels),1);
    image(reshape(255-train_images(j,:,:),28,28));
    title(sprintf('%d',train_labels(j)));
    pause(1);
    image(reshape(train_images_unfold(:,j),28,28));
    title(vec2ind(train_labels_unfold(:,j))-1);
    pause(1);
end

MNISTParser.m

function res = MNISTParser(filename)
    fp = fopen(filename,'r');
    **magic_number = fread(fp,1,'uint32',0,'b');**
    items_number = fread(fp,1,'uint32',0,'b');
    if 2049==magic_number
        res = fread(fp,items_number,'uint8',0,'b');
    else
        if 2051==magic_number
            img_rows = fread(fp,1,'uint32',0,'b');
            img_cols = fread(fp,1,'uint32',0,'b');
            res = zeros(items_number,img_rows,img_cols);
            for i=1:items_number
                res(i,:,:) = fread(fp,[img_cols,img_rows],'uint8',0,'b')';
            end
        else
            error('wrong magic number');
        end
    end
    fclose(fp);

end

感谢帮助

1 个答案:

答案 0 :(得分:0)

找到错误。它与文件的扩展有关。  这是帮助我找出错误的指令[fp,msg] = fopen(filename,'r');     if fp< 1,error([msg'File:'filename]);