matlab生成图像路径列表和标签,打乱顺序

以101_ObjectCategories数据库为例,将9144张图像的存储路径保存在两个文本文件中,一个为训练集,一个为测试集,并在每张图像后添加对应类别标签。最后打乱顺序。
1. 准备好101_ObjectCategories数据库
matlab生成图像路径列表和标签,打乱顺序_第1张图片
2. 打开MATLAB,添加extract.m脚本,运行。extract.m代码如下

%trian test
clc;
ParentFolder='J:\Dataset\101_ObjectCategories\'; %matlab在本地数据库生成list所以路径是反斜杠
ParentPath = dir(ParentFolder);
NumFolders = length(ParentPath);


train= fopen('train.txt','wt');
test = fopen('test.txt','wt');


for i = 3:NumFolders
    label=num2str(i-3);
    FolderPath = [ParentFolder ParentPath(i).name];
    imageName=dir(FolderPath);
    numPic=length(imageName);
    count=1;
    index = randperm(length(imageName)-2);
    for k = 1:4
        index = randperm(size(index,2));
    end 
    for j=3:numPic
        src=['/' ParentPath(i).name '/' imageName(index(count)+2).name]; %Ubuntu系统下读取list,路径是斜杠
        if count<=15
            fprintf(train,'%s %s\n',src,label);
        else
            fprintf(test,'%s %s\n',src,label);
        end
        count=count+1;
     end
end
fclose(train);
fclose(test);

3.对生成的list进行打乱,代码:

fidin_train=fopen('train.txt');
fidout_train = fopen('train_rand.txt','wt');
fidin_test = fopen('test.txt');
fidout_test = fopen('test_rand.txt','wt');
index =0;
str_train = cell(1);
while ~feof(fidin_train)                                          
   tline=fgetl(fidin_train);
   index =index+1;
   str_train{index} = tline;
end


rand_index = randperm(index);


for i=1:index
    fprintf(fidout_train, '%s\n',str_train{rand_index(i)});
end

index = 0;
str_test = cell(1);
while ~feof(fidin_test)                                                 
   tline=fgetl(fidin_test);
   index =index+1;
   str_test{index} = tline;
end


rand_index = randperm(index);


for i=1:index
    fprintf(fidout_test, '%s\n',str_test{rand_index(i)});  
end

你可能感兴趣的:(Matlab)