【问题标题】:How to tell MATLAB to open and save specific files in the same directory如何告诉 MATLAB 在同一目录中打开和保存特定文件
【发布时间】:2010-06-15 19:42:46
【问题描述】:

我必须对目录中的大量图像运行图像处理算法。

图像保存为name_typeX.tif,因此给定名称有 X 种不同类型的图像。

图像处理算法获取输入图像并输出图像结果。

我需要将此结果保存为name_typeX_number.tif,其中number 也是给定图像算法的输出。

现在..

如何告诉 MATLAB 打开特定的typeX 文件?另请注意,同一目录下还有其他非 tif 文件。

如何将结果保存为name_typeX_number.tif

结果必须保存在输入图像所在的同一目录中。如何告诉 MATLAB 不要处理已保存为输入图像的结果?

我必须在服务器上将其作为后台代码运行...所以不允许用户输入。

【问题讨论】:

    标签: matlab


    【解决方案1】:

    听起来您想要获取目录中名称与某种格式匹配的所有文件,然后自动处理它们。您可以使用函数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

    【讨论】:

    • 感谢新手!第 3 行 index = regexp(fileNames,'[A-Za-z]+_type\d+\.tif');如果我希望数字为 1、2 和 5(而不是所有其他可用数字)怎么办。我还没有运行你的代码.. 忙着搜索你用过的所有函数:P 但是代码的“+”部分?
    • @its-me:如果你想只匹配type后面的数字1、2或5中的一个,你可以去掉\d+并将其替换为[125]+ 是一个量词,表示前面的字符匹配 1 次或多次。我还在我的答案中添加了一些函数文档的额外链接。
    猜你喜欢
    • 2016-08-22
    • 2018-10-30
    • 2019-08-02
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 2012-01-31
    • 2014-01-25
    相关资源
    最近更新 更多