从MATLAB中的文件夹中读取许多.img文件时出错

Bow*_*cho 0 matlab image image-processing

我有100个.img文件,我试图使用以下代码从目录中读取:

srcFiles = dir('/Users/Adrian/Documents/Foam_Data/ssd0/2013-10-25_09-01-12/000000/*.img'); % the folder in which ur images exists

for i = 1:100   % length(srcFiles)

     filename = srcFiles(i).name;
    fid = fopen(filename);
    image = fread(fid, 2048*2048, 'uint8=>uint8');
    fclose(fid);
    image = reshape(image, 2048, 2048);
    figure;
    imshow(image);

end
Run Code Online (Sandbox Code Playgroud)

'/Users/Adrian/Documents/Foam_Data/ssd0/2013-10-25_09-01-12/000000/'是我的.img文件所在目录的路径.我似乎在定义文件标识符时出错,但我不知道我错过了什么:

Error using fread
Invalid file identifier.  Use fopen to generate a valid file identifier.

Error in sequenceimage (line 32)
    image = fread(fid, 2048*2048, 'uint8=>uint8');
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我修复错误吗?

ray*_*ica 5

您收到该错误的原因是因为dir返回列出的每个文件的相对名称,而不是每个文件的绝对路径.因此,通过这样做srcFiles(i).name,您只能获得文件名本身 - 而不是文件的完整路径.

因此,您需要在调用时将目录附加到文件本身的顶部fopen.

为了使事情更加灵活,将目录放在一个单独的字符串中,这样您只需要在一个地方而不是两个地方修改代码.

非常简单:

%// Change here
loc = '/Users/Adrian/Documents/Foam_Data/ssd0/2013-10-25_09-01-12/000000/';

%// Change here
srcFiles = dir([loc '*.img']); % the folder in which ur images exists

for i = 1:100   % length(srcFiles)

     filename = srcFiles(i).name;

    %// Change here!
    fid = fopen([loc filename]);
    image = fread(fid, 2048*2048, 'uint8=>uint8');
    fclose(fid);
    image = reshape(image, 2048, 2048);
    figure;
    imshow(image);

end
Run Code Online (Sandbox Code Playgroud)