LLNet模型實現——訓練數據準備之matlab循環遍歷指定文件格式

1. 背景

實現指定文件夾下的指定格式文件遍歷,並返回文件路徑。

2. 代碼實現

function filePaths = searchRoot(root_dir, format)
% Inputs:
%       root_dir: 需要搜索的文件夾的目錄路徑
%       format: 需要過濾識別的文件格式
% Outputs:
%       filePaths:
% Author: HSW
% Date: 2018-05-05 
%
if ~exist('format', 'var')
    format = '.pgm'; 
end 

searchPaths = search(root_dir, format); 

index = strfind(searchPaths, ','); 
N = length(index) - 1; 
filePaths = cell(N, 1); 
for idx = 1:N
    filePaths{idx} = searchPaths(index(idx) + 1 : index(idx + 1) - 1); 
end 

end 



function filePaths = search(root_dir, format)
% Inputs:
%       root_dir: 需要搜索的文件夾的目錄路徑
%       format: 需要過濾識別的文件格式
% Outputs:
%       filePaths: 文件路徑用逗號間隔
% Author: HSW
% Date: 2018-05-05 
%
if ~exist('format', 'var')
    format = '.pgm'; 
end 

sub_dirs  = dir(root_dir);
filePaths = [];  
for i = 1 : length(sub_dirs)
    if( isequal( sub_dirs( i ).name, '.' ) || isequal(sub_dirs( i ).name, '..'))
        continue;
    end
    if sub_dirs(i).isdir
        % 爲文件夾時
        searchDir = fullfile(root_dir, sub_dirs(i).name); 
        filePathParts = search(searchDir, format);
        isStart = 0; 
        filePath = []; 
        for idx = 1 : length(filePathParts) 
            if(filePathParts(idx) == ',' && isStart == 0)
                isStart = 1;
                continue; 
            elseif(filePathParts(idx) == ',' && isStart == 1)
                filePaths = [filePaths, ',',filePath]; 
                isStart = 0; 
                filePath = []; 
            elseif(filePathParts(idx) ~= ',' && isStart == 1)
                    filePath = [filePath, filePathParts(idx)]; 
            end  
        end 
    else
        fileName = sub_dirs(i).name; 
        if isempty(strfind(fileName, format)) 
            continue;
        else
            filePath = fullfile(root_dir, sub_dirs(i).name); 
            filePaths = [filePaths, ',', filePath, ',']; 
        end 
    end
end
end 

3. 效果


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章