Matlab批量JPG图像导入提速方法咨询
加快Matlab批量导入JPG图像速度的优化方案
我需要从指定文件夹中导入平均约500张JPG格式图像,为此编写了两种Matlab实现函数,第二种方法速度略有提升,但整体导入耗时仍过长,请问是否有可进一步加快图像导入速度的方法?
第一种实现方法
function Seq = ImageImport(imgPath, imgType,Amount) images = dir([imgPath imgType]); N = length(images); % 检查图像目录与文件 if( ~exist(imgPath, 'dir') || N<1 ) disp('Directory not found or no matching images found.'); end % 预分配元胞数组 Seq{N,1} = []; if Amount == "all" for i = 1:N Seq{i} = imread([imgPath images(i).name]); end elseif Amount == "first" Seq{1} = rgb2gray(imread([imgPath images(1).name])); end end
第二种实现方法
function Seq = ImageImport(imgPath, imgType,Amount) images = dir([imgPath imgType]); N = length(images); % 检查图像目录与文件 if( ~exist(imgPath, 'dir') || N<1 ) disp('Directory not found or no matching images found.'); end % 预分配元胞数组 Seq{N,1} = []; % 预分配文件路径元胞 filepath{N,1} = []; for i = 1:N filepath{i} = sprintf('%s%s',imgPath,images(i).name); end if Amount == "all" for i = 1:N Seq{i} = imread(filepath{i}); end elseif Amount == "first" Seq{1} = imread(filepath{1}); end end
提速优化方案
1. 用统一尺寸数组替代元胞数组
如果所有图像尺寸一致,直接预分配三维/四维数值数组(而非元胞数组),能避免元胞的内存管理开销,大幅提升速度:
function Seq = ImageImport(imgPath, imgType,Amount) images = dir([imgPath imgType]); N = length(images); if( ~exist(imgPath, 'dir') || N<1 ) disp('Directory not found or no matching images found.'); Seq = []; return; end if Amount == "all" % 读取第一张图获取尺寸与数据类型 firstImg = imread([imgPath images(1).name]); [h,w,c] = size(firstImg); % 预分配四维数组:高度×宽度×通道数×图像数 Seq = zeros(h,w,c,N,'like',firstImg); for i = 1:N Seq(:,:,:,i) = imread([imgPath images(i).name]); end elseif Amount == "first" Seq = imread([imgPath images(1).name], 'ColorSpace', 'Gray'); end end
2. 使用imageDatastore批量读取
Matlab内置的imageDatastore是专门为批量图像设计的工具,内部做了I/O优化,支持自动并行读取,比手动循环更高效:
function Seq = ImageImport(imgPath, imgType,Amount) % 创建图像数据存储对象 ds = imageDatastore(fullfile(imgPath, imgType)); if Amount == "all" % 一次性读取所有图像,若尺寸一致返回数组,否则返回元胞 Seq = readall(ds); elseif Amount == "first" % 读取单张并转灰度 ds.ColorSpace = 'Gray'; Seq = read(ds); end end
3. 启用并行循环(parfor)
如果电脑有多核心CPU,用parfor替代普通for循环,利用并行计算加速文件读取:
function Seq = ImageImport(imgPath, imgType,Amount) images = dir([imgPath imgType]); N = length(images); if( ~exist(imgPath, 'dir') || N<1 ) disp('Directory not found or no matching images found.'); Seq = []; return; end Seq = cell(N,1); if Amount == "all" % 初始化并行池(首次运行会自动启动,后续可跳过) if isempty(gcp('nocreate')) parpool; end parfor i = 1:N Seq{i} = imread([imgPath images(i).name]); end % 可选:关闭并行池 delete(gcp); elseif Amount == "first" Seq{1} = imread([imgPath images(1).name], 'ColorSpace', 'Gray'); end end
4. 预打包成Mat文件减少I/O
如果需要反复读取这批图像,可一次性读取后保存为Mat文件,后续直接加载Mat文件(比反复解码JPG快数倍):
% 首次读取并保存 Seq = ImageImport('your/path/', '*.jpg', "all"); save('images_batch.mat', 'Seq'); % 后续直接加载 load('images_batch.mat');
5. 直接读取灰度图减少运算
如果最终需要灰度图,在读的时候指定ColorSpace参数,避免先读RGB再转灰度的额外运算:
% 替代 rgb2gray(imread(...)) imread(filePath, 'ColorSpace', 'Gray');
内容的提问来源于stack exchange,提问作者Raúl Santamaría
相关产品推荐
相关产品推荐

