複数のファイル読み込み
    8 views (last 30 days)
  
       Show older comments
    
[IMG_0100_1.tif,IMG_0100_2.tif,IMG_0100_3.tif,IMG_0100_4.tif,IMG_0100_5.tif,IMG_0110_1.tif,IMG_0110_2.tif,IMG_0110_3.tif,IMG_0110_4.tif,IMG_0110_5.tif  ............]
といった末尾の数字に規則性があるファイル名を持つファイルがあるとき,末尾が2,3,4であるファイルだけを連続して読み込むにはどうすればよいでしょうか.
このような感じで...
[IMG_0100_2.tif,IMG_0100_3.tif,IMG_0100_4.tif,IMG_0110_2.tif,IMG_0110_3.tif,IMG_0110_4.tif,  ............]
0 Comments
Accepted Answer
  Akira Agata
    
      
 on 20 Nov 2019
        あるいは、ファイルが大量にあるようでしたら以下の方法ではいかがでしょうか。
% カレントフォルダにある .tifファイル一覧を作成
s = dir('*.tif');
s = struct2table(s);
% 末尾が _2.tif ~ _4.tif のみを抽出
idx = endsWith(s.name,{'_2.tif','_3.tif','_4.tif'});
s = s(idx,:);
for kk = 1:height(s)
  filePath = fullfile(s.folder{kk},s.name{kk});
  %
  % Read the file and do something
  %
end
3 Comments
  Akira Agata
    
      
 on 22 Nov 2019
				.tifファイルはすべてカラー画像で、各 IMG_xxxx に対して必ず _2.tif, _3.tif, _4.tif の3枚の画像が存在すると想定すると、たとえば下記のようになるかと思います。
s = dir('*.tif');
s = struct2table(s);
idx = endsWith(s.name,{'_2.tif','_3.tif','_4.tif'});
s = s(idx,:);
group = extractBetween(s.name,'_','_');
[s.group, uGroup] = findgroups(group);
for kk = 1:max(s.group)
  pt = find(s.group == kk);
  % Read 3 images for each group
  I1 = imread(fullfile(s.folder{pt(1)},s.name{pt(1)}));
  I2 = imread(fullfile(s.folder{pt(2)},s.name{pt(2)}));
  I3 = imread(fullfile(s.folder{pt(3)},s.name{pt(3)}));
  % Convert RGB to gray-scale
  I1gray = rgb2gray(I1);
  I2gray = rgb2gray(I2);
  I3gray = rgb2gray(I3);
  % Compsit of 3 images
  Iall = cat(3,I1gray,I2gray,I3gray);
  % Save as 'IMG_xxxx_all.tif'
  fileName = ['IMG_',uGroup{kk},'_all.tif'];
  imwrite(Iall,fileName);
end
More Answers (1)
  Kazuya
      
 on 20 Nov 2019
        
      Edited: Kazuya
      
 on 20 Nov 2019
  
      一案ですが、ファイルのリストを string 型で作って contains を使えば、該当するファイル名だけのリストを作れるので、それを for ループで回せば良いかと思いました。
例:
filelist = ["IMG_0100_1.tif","IMG_0100_2.tif","IMG_0100_3.tif","IMG_0100_4.tif","IMG_0100_5.tif",...
    "IMG_0110_1.tif","IMG_0110_2.tif","IMG_0110_3.tif","IMG_0110_4.tif","IMG_0110_5.tif"]';
idx = contains(filelist,["_2.tif","_3.tif","_4.tif"]);
filelist234 = filelist(idx)
末尾に 2,3,4 を含むファイル名だけが filelist234 に残ります。
filelist234 = 
  6×1 の string 配列
    "IMG_0100_2.tif"
    "IMG_0100_3.tif"
    "IMG_0100_4.tif"
    "IMG_0110_2.tif"
    "IMG_0110_3.tif"
    "IMG_0110_4.tif"
おおもとの filelist は以下で作れると思います。
listing = ls('*.tif');
filelist = string(listing);
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

