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帮助文档的格式
posted @ 2020-10-29 10:24  Cindy's  阅读(2521)  评论(0编辑  收藏  举报