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

时间:2015-03-18 16:46:34

标签: image matlab 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

'/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');

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

1 个答案:

答案 0 :(得分: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