使用BOF实现动物分类:matlab版本
1.训练集测试集划分(同上一篇)
2.代码部分
1)训练部分代码:training.m
%% 该函数是使用Bag of Features来提取test_images下图片的特征的,代码编写参考matlab官方文档 % 内部采用k-means训练,可能需要点时间 %% 1.获取图片以及相关的分类 currentPath = pwd; % 获得当前的工作目录 imds = imageDatastore(fullfile(pwd,\'train_images\'),... \'IncludeSubfolders\',true,... \'LabelSource\',\'foldernames\'); % 载入图片集合 tbl = countEachLabel(imds); % 2.预处理:每一类的图片要一样多 minSetCount = min(tbl{:,2}); imds = splitEachLabel(imds, minSetCount, \'randomize\'); % 提示信息 disp(\'开始训练数据...\'); %3. 划分测试集合和训练集合 [trainingSet, validationSet] = splitEachLabel(imds, 0.9, \'randomize\'); % 4.训练包 bag = bagOfFeatures(trainingSet); categoryClassifier = trainImageCategoryClassifier(trainingSet, bag); % 5.计算可能性 confMatrix = evaluate(categoryClassifier, trainingSet); mean(diag(confMatrix)); save categoryClassifier % 提示信息 disp(\'训练阶段结束!!!\');
2)测试部分代码:classify.m
%% 该函数用来对图片进项分类 BOF + SVM %% 1.读入待分类的图片集合 currentPath = pwd; imdsTest = imageDatastore(fullfile(pwd,\'test_image\')); %% 2.分类,预测并显示预测效果图 % 载入分类器 load categoryClassifier numTest = length(imdsTest.Files); % correctCount:正确图片张数 correctCount = 0; fprintf(\'开始分类......\n\'); for i = 1:numTest testImage = readimage(imdsTest,i); % imdsTest.readimage(1) [labelIdx, scores] = predict(categoryClassifier, testImage); figure;imshow(imresize(testImage,[256,256])); imgName = imdsTest.Files(i); tt = regexp(imgName,\'\\',\'split\'); cellLength = cellfun(\'length\',tt); tt2 = char(tt{1}(1,cellLength)); % 统计正确率 if strfind(tt2,char(categoryClassifier.Labels(labelIdx)))==1 correctCount = correctCount+1; end fprintf(\'%s == %s\n\',tt2,char(categoryClassifier.Labels(labelIdx))); title([\'分类结果: \',tt2,\'--\',char(categoryClassifier.Labels(labelIdx))]); end % 显示正确率 fprintf(\'分类结束,正确了为:%.1f%%\n\',correctCount * 100.0 / numTest);
版权声明:本文为xiangbin1207原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。