脚本崩溃后无法删除某些文件

时间:2013-09-28 13:59:26

标签: matlab file delete-file parfor matlabpool

我运行一个生成图像的MATLAB脚本,将它们保存到某个文件夹中。当代码崩溃时,我无法删除该文件夹中的一些图像,除非我重新启动MATLAB。

我可以在没有重启MATLAB程序的情况下解决这个问题吗?

代码:

clear,clc,close all
SRC1 = 'SRC1';
SRC2 = 'SRC2';
suffix1 = '_suffix1.png';
suffix2 = '_suffix2.png';
DST = 'DST';
GT = 'GT';
FEAS = {
    SRC1;
    };
feaSuffix = {
    '_suffix.png';
    };
if ~exist(DST, 'dir')
    mkdir(DST);
end
if matlabpool('size')<=0
    matlabpool('open','local',8);
else
    disp('Already initialized');
end
files1 = dir(fullfile(SRC1, strcat('*', suffix1)));
parfor k = 1:length(files1)
    disp(k);
    name1 = files1(k).name;

    gtName = strrep(name1, suffix1, '.bmp');
    gtImg = imread(fullfile(GT, gtName));
    if ~islogical(gtImg)
        gtImg = gtImg(:,:,1) > 128;
    end
    gtArea = sum(gtImg(:));
    if gtArea == 0
        error('no ground truth in %s', gtName);
    end

    img1 = imread(fullfile(SRC1, name1));
    mae1 = CalMAE(img1, gtImg);

    name2 = strrep(name1, suffix1, suffix2);
    img2 = imread(fullfile(SRC2, name2));
    mae2 = CalMAE(img2, gtImg);

    delta = mae1 - mae2 + 1;
    preffix = sprintf('%.2f_mae1_%.2f_mae2_%.2f_', delta, mae1, mae2);

    imwrite(img1, fullfile(DST, strcat(preffix, name1)));
    imwrite(img2, fullfile(DST, strcat(preffix, name2)));
    imwrite(gtImg, fullfile(DST, strcat(preffix, gtName)));

    for n = 1:length(FEAS)
        feaImgName = strrep(name1, suffix1, feaSuffix{n});
        copyfile(fullfile(FEAS{n}, feaImgName), ...
            fullfile(DST, strcat(preffix, feaImgName)));
    end
end

1 个答案:

答案 0 :(得分:0)

您可以告诉MATLAB使用

关闭所有打开的文件
fclose('all');

根据我的经验fclose适用于所有已打开的文件,而不仅仅是使用fopen打开的文件。

此外,由于您运行的是matlabpool,因此每个工作人员(MATLAB.exe进程)都需要释放他们的文件。为此,我建议在try内创建一个catch - parfor

parfor k = 1:length(files1)
    try
        % your loop content here
    catch ME
        % cleanup and terminate
        fclose('all');
        rethrow(ME);
    end
end

这样,在循环中轰炸的工作人员将运行fclose。在主MATLAB.exe中运行它可能没有帮助。

但是,在尝试删除文件之前,您还可以确保关闭matlabpool ,因为这会释放工作人员所拥有的任何文件锁。