您的位置:首页 > 编程语言 > MATLAB

Matlab 关于如何读取文件夹中的所有图片(3种方法)

2014-04-09 09:22 627 查看
Matlab读取图片的方法有很多种, 我给出的方法思想和他们的差不多一样,但是代码的风格可能有点区别, 可以学习。

方法1:

首先定义文件夹的名称:

[cpp] view plaincopy

imgDir='.\coimg\';

imgDir2='.\\coimg\\%s'; 用于读取图片

具体代码:

[cpp] view plaincopy

oldPwd = pwd;

cd(imgDir);

x = dir;

listOfImages = [];

for i = 1:length(x),

if x(i).isdir == 0,

listOfImages = [listOfImages; x(i)];

end;

end;

cd(oldPwd);

fid=imgDir2;

for j = 1:length(listOfImages)

fileName = listOfImages(j).name;

rfid=sprintf(fid,fileName);

Irgb=imread(rfid);

Iset{j}=Irgb;

end

文中 x(i).isdir==0 其实意思是跳过i=1,2时,那是isdir==1,其实是为了跳过'.','..',这个应该是操作系统的知识吧。。

最后将读取的图片放在Iset里面。

代码很简单。自己手写,测试成功



两幅图片在Iset里面啦 。。

小技巧值得注意。。。

方法2:

适合文件夹里面的图片批量处理,非常好的算法,应该值得学习。。

[cpp] view plaincopy

function database = build_database(rt_data_dir,suffix)

% This function is to build a database for the image sets

% Input: rt_data_dir -- direction of image sets

% suffix -- image format like 'jpg'

% Output: database -- database that contains all the information of

% images

% Written by Wei Q

% July. 16, 2013

fprintf('dir the database...');

subfolders = dir(rt_data_dir);

database = [];

database.imnum = 0; % total image number of the database

database.cname = {}; % name of each class

database.label = []; % label of each class

database.path = {}; % contain the pathes for each image of each class

database.nclass = 0;

for ii = 1:length(subfolders),

subname = subfolders(ii).name;

if ~strcmp(subname, '.') & ~strcmp(subname, '..'),

database.nclass = database.nclass + 1;

database.cname{database.nclass} = subname;

frames = dir(fullfile(rt_data_dir, subname, suffix));

c_num = length(frames);

database.imnum = database.imnum + c_num;

database.label = [database.label; ones(c_num, 1)*database.nclass];

for jj = 1:c_num,

c_path = fullfile(rt_data_dir, subname, frames(jj).name);

database.path = [database.path, c_path];

end;

end;

end;

disp('done!');

应该试着自己写写。

方法3:(这种方法有点特别)

[cpp] view plaincopy

ext = {'*.jpeg','*.jpg','*.png','*.pgm'};

images = [];

for i = 1:length(ext)

images = [images dir([path ext{i}])];

end

% images are returned with absolute path

for i = 1:length(images)

images(i).name = [path images(i).name];

end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: