2010-06-15 70 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

相关问题