2010-06-15 30 views
2

我必須在目錄中的許多圖像上運行圖像處理算法。如何讓MATLAB打開並保存同一目錄中的特定文件

圖像保存爲name_typeX.tif,因此給定名稱有X個不同類型的圖像。

圖像處理算法獲取輸入圖像並輸出圖像結果。

我需要將此結果保存爲name_typeX_number.tif,其中number也是給定圖像的算法輸出。

現在..

我如何告訴MATLAB打開特定文件typeX?另請注意,同一目錄中還有其他非tif文件。

如何將結果保存爲name_typeX_number.tif

結果必須保存在輸入圖像所在的目錄中。我如何告訴MATLAB不要將已保存爲輸入圖像的結果處理?

我必須將其作爲服務器上的後臺代碼運行...所以不允許用戶輸入。

回答

3

這聽起來像你想要獲得名稱匹配某種格式的目錄中的所有文件,然後自動處理它們。您可以使用函數DIR獲取當前目錄中的文件名列表,然後使用函數REGEXP查找與特定模式匹配的文件名。這裏有一個例子:

fileData = dir();    %# Get a structure of data for the files in the 
           %# current directory 
fileNames = {fileData.name}; %# Put the file names in a cell array 
index = regexp(fileNames,...     %# Match a file name if it begins 
       '^[A-Za-z]+_type\d+\.tif$'); %# with at least one letter, 
              %# followed by `_type`, followed 
              %# by at least one number, and 
              %# ending with '.tif' 
inFiles = fileNames(~cellfun(@isempty,index)); %# Get the names of the matching 
               %# files in a cell array 

一旦你有文件的inFiles單元陣列所需的命名模式相匹配,你可以簡單地遍歷所有的文件,並執行處理。例如,你的代碼可能是這樣的:

nFiles = numel(inFiles); %# Get the number of input files 
for iFile = 1:nFiles  %# Loop over the input files 
    inFile = inFiles{iFile}; %# Get the current input file 
    inImg = imread(inFile); %# Load the image data 
    [outImg,someNumber] = process_your_image(inImg); %# Process the image data 
    outFile = [strtok(inFile,'.') ... %# Remove the '.tif' from the input file, 
      '_' ...     %# append an underscore, 
      num2str(someNumber) ... %# append the number as a string, and 
      '.tif'];     %# add the `.tif` again 
    imwrite(outImg,outFile); %# Write the new image data to a file 
end 

上面的例子使用的功能NUMELSTRTOKNUM2STRIMREADIMWRITE

+0

謝謝gnovice! on line 3 index = regexp(fileNames,'[A-Za-z] + _ type \ d + \。tif'); 如果我希望數字是1,2和5(而不是所有其他可用數字),該怎麼辦? 我還沒有運行你的代碼呢..忙搜索你使用的所有功能:P,但是代碼的「+」部分? – 2010-06-15 21:32:25

+1

@ its-me:如果你想匹配單詞'type'後的數字1,2或5中的一個*,你可以刪除'\ d +'並用'[125]'替換它。 「+」是一個量詞,表示前面的字符匹配1次或更多次。我還爲我的答案添加了一些額外的功能文檔鏈接。 – gnovice 2010-06-15 23:49:43

+0

完美答案! – 2010-06-15 23:59:02

相關問題