2013-09-28 31 views
1

我運行一個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 
+0

這是因爲您沒有關閉在matlab代碼中打開的圖像文件。你可以更新你的問題與你的matlab代碼?... – TheCodeArtist

+0

其實,我只'copyfile'和'imwrite'到該文件夾​​。我如何釋放與這些圖像文件相關的資源?我嘗試了「全部清除」,但沒有奏效。 – user2727676

+0

請給你正在使用的代碼。現在編輯代碼 – shunyo

回答

0

你可以告訴MATLAB與

fclose('all'); 

關閉所有打開的文件在我的經驗fclose適用於所有打開的文件,而不僅僅是那些與fopen打開。

此外,由於您運行的是matlabpool,因此每個工作人員(MATLAB.exe進程)都需要釋放其文件。爲此,我建議在這樣的parfor內部創建一個try - catch

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,因爲這應該釋放工作人員擁有的任何文件鎖定。

+0

我在問這個問題之前試過這個,它不起作用... – user2727676

+1

查看我更新的答案以解決'matlabpool'方面的問題。文件讀取發生在工作人員,這是獨立的MATLAB.exe進程,所以他們需要被殺死或釋放他們的文件鎖'fclose'。 – chappjc

+1

非常感謝,這聽起來很合理。 – user2727676