1. 程式人生 > >MATLAB:如何在指定路徑下,讀取單個(多個)資料夾中所有影象

MATLAB:如何在指定路徑下,讀取單個(多個)資料夾中所有影象

0. 選擇資料夾路徑:

[filename filepath]=uigetfile('*.*','請選擇檔案');%filename為檔名,filepath為檔案路徑
image =  imread(strcat(file_path,image_name));%讀取圖片檔案

1, 指定路徑下 單個資料夾data中所有影象

注,下述的程式碼只能讀取data資料夾中的影象,假設data中包含子資料夾,不能讀取子資料夾中的影象。

file_path =  '.\data\';% 影象資料夾路徑
img_path_list = dir(strcat(file_path,'*.jpg'));%獲取該資料夾中所有jpg格式的影象
img_num = length(img_path_list);%獲取影象總數量
if img_num > 0 %有滿足條件的影象
        for j = 1:img_num %逐一讀取影象
            image_name = img_path_list(j).name;% 影象名
            image =  imread(strcat(file_path,image_name));
            fprintf('%d %d %s\n',i,j,strcat(file_path,image_name));% 顯示正在處理的影象名
            %影象處理過程 省略
        end
end

2. 指定路徑下 多個資料夾中所有影象,該程式碼可以讀取資料夾data中及data的所有子資料夾中的影象。

p = genpath('.\data');% 獲得資料夾data下所有子檔案的路徑,這些路徑存在字串p中,以';'分割
length_p = size(p,2);%字串p的長度
path = {};%建立一個單元陣列,陣列的每個單元中包含一個目錄
temp = [];
for i = 1:length_p %尋找分割符';',一旦找到,則將路徑temp寫入path陣列中
    if p(i) ~= ';'
        temp = [temp p(i)];
    else 
        temp = [temp '\']; %在路徑的最後加入 '\'
        path = [path ; temp];
        temp = [];
    end
end  
clear p length_p temp;
%至此獲得data資料夾及其所有子資料夾(及子資料夾的子資料夾)的路徑,存於陣列path中。
%下面是逐一資料夾中讀取影象
file_num = size(path,1);% 子資料夾的個數
for i = 1:file_num
    file_path =  path{i}; % 影象資料夾路徑
    img_path_list = dir(strcat(file_path,'*.jpg'));
    img_num = length(img_path_list); %該資料夾中影象數量
    if img_num > 0
        for j = 1:img_num
            image_name = img_path_list(j).name;% 影象名
            image =  imread(strcat(file_path,image_name));
            fprintf('%d %d %s\n',i,j,strcat(file_path,image_name));% 顯示正在處理的路徑和影象名
            %影象處理過程 省略
        end
    end
end

3.逐一讀取某資料夾中的圖片:


img_path_list = dir(strcat(file_path,'*.bmp'));%獲取該資料夾中所有jpg格式的影象
img_num = length(img_path_list);%獲取影象總數量
if img_num > 0 %有滿足條件的影象
        for j = 1:img_num %逐一讀取影象
            image_name = img_path_list(j).name;% 影象名
            image =  imread(strcat(file_path,image_name));%讀取影象
 
            %對單幅影象進行操作
 
       end

 

(http://blog.163.com/yuyang_tech/blog/static/216050083201399103356795/)

https://blog.csdn.net/d5224/article/details/77074035/