在Matlab2016/2017中進行圖像分類變得非常容易,下面是幾個例子。
- exam1:統計學習工具箱內置SVM函數
%exam1.m
load fisheriris
xdata = meas(51:end,3:4);
group = species(51:end);
figure;
svmStruct = svmtrain(xdata,group,'ShowPlot',true);
Xnew = [5 2; 4 1.5];
species = svmclassify(svmStruct,Xnew,'ShowPlot',true);
hold on;
plot(Xnew(:,1),Xnew(:,2),'ro','MarkerSize',12);
hold off
該示例使用Matlab內置的SVM函數進行分類,
SVMStruct = svmtrain(Training,Group,Name,Value)
Training和Group表示訓練數據和類別標籤,每行表示一個樣本,行數應相同。得出SVM模型後,用它進行分類。
Group = svmclassify(SVMStruct,Sample)
Sample表示測試數據,每一列表示一個樣本。結果返回測試樣本所屬類別。
- exam2:利用圖像BOW進行識別
%exam2.m setDir = fullfile(toolboxdir('vision'),'visiondata','imageSets'); imgSets = imageSet(setDir, 'recursive'); %將30%的數據用作訓練集,其餘的用作測試集 [trainingSets, testSets] = partition(imgSets, 0.3, 'randomize'); bag = bagOfFeatures(trainingSets); %訓練得出圖像類別分類器 categoryClassifier = trainImageCategoryClassifier(trainingSets, bag); %預測測試集中第一幅圖像的類別 [labelIdx, score] = predict(categoryClassifier, testSets(1));
該示例直接使用Computer Vision工具箱的函數
classifier = trainImageCategoryClassifier(imds,bag,Name,Value)
輸入參數的imds由partition對imageSets分割得來,返回值是imageCategoryClassifier類型的類,predict函數用它對測試圖像進行預測,完成圖像識別功能。