MATLAB | 圖片批量讀取並保存


批量讀取圖片

1。 指定路徑下 單個文件夾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

注,上述的代碼只能讀取data文件夾中的圖像,假設data中包含子文件夾,不能讀取子文件夾中的圖像。

  1. 指定路徑下 多個文件夾中所有圖像,該代碼可以讀取文件夾data中及data的所有子文件夾中的圖像。
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中。
  1. 下面是逐一文件夾中讀取圖像
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

保存窗圖為特定格式

%% Introduction
 % 按需求生成多張圖片並保存到指定文件夾下
 % 如生成64張480*600(w*h)的32級灰階png圖片並按順序保存在image文件夾下

width = 480;  % 圖片寬度
height = 600; % 圖片高度
dim = 3; % 圖片維度

% 按照圖片規格預分配內存
image = zeros(height, width, dim);

path = 'image/'; % 保存的文件夾位置
prefix = 'image_'; % 文件名前綴
format = 'png'; % (圖片)文件格式
suffix = strcat('.',format); % 文件后綴
gray_level = 32; % 灰階等級
gray_step = 256 / gray_level; % 灰階間隔

% 如果目錄不存在則新建,否則刪除文件夾並新建
if ~exist(path,'dir')
    mkdir(path);
else
    rmdir(path,'s');
    mkdir(path);
end

% 生成圖像並保存
%% !!! 使用`saveas`,具體的查看matlab幫助文檔的格式


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM