在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表示测试数据,每一列表示一个样本。结果返回测试样本所属类别。 2. 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函数用它对测试图像进行预测,完成图像识别功能。