该方法提取图像集的词袋(bag-of-features),然后根据词袋对各图像编码得出图像特征,再对测试图像在训练图像集上进行检索,最后根据检索出的图像类别判断测试图像所属类别。该方法直接对图像进行处理,不需要先提取特征,再将特征文件导入。不过该方法消耗内存很大,适用于小规模图像集。代码如下:

clear;
% 设置图象集路径
imgSetFolder = fullfile(pwd, 'image');
imgqueryFolder = fullfile(pwd, 'query');
%构造图像集变量
qImageSets = imageSet(imgSetFolder,   'recursive'); 
qImages   = imageSet(imgqueryFolder);             
%获取查询图像数量
setNum = numel(qImageSets);
for i=1:setNum
    qImageSetsOut(i) = select(qImageSets(i), 1:2:qImageSets(i).Count);
end
%图象集划分
%[trainingSets, validationSets] = partition(qImageSetsOut, 0.8, 'randomized');

if ~exist('ColorBagOfFeatures.mat','file')
%提取图象集词袋
%     colorBag = bagOfFeatures(qImageSetsOut, ...
%         'CustomExtractor', @exampleBagOfFeaturesColorExtractor, ...
%         'VocabularySize', 1000);
%     extractor = @exampleBagOfFeaturesExtractor;
%     colorBag = bagOfFeatures(qImageSetsOut,'CustomExtractor',extractor,'VocabularySize', 1000);
    Bag = bagOfFeatures(qImageSetsOut,'VocabularySize', 1000);
%存储得出的词袋
    save('BagOfFeatures.mat','Bag');
else
    % 加载词袋
    load('BagOfFeatures.mat','Bag');
end

if ~exist('imagesIndex.mat','file')    
    featureVector = [];
    for i = 1:setNum        
%根据词袋对各图像进行编码得出图像特征
        for j =1:qImageSets(i).Count
            queryImage = read(qImageSetsOut(i),j);
            tempcode   = encode(Bag, queryImage);
            featureVector =[featureVector tempcode];            
        end
    end    
    save('imagesWord.mat','featureVector');
else
    % 加载图像特征
    load('imagesWord.mat', 'featureVector');
end

figure
imshow(queryImage)
% 检索出相似的图像
[imageIDs, scores] = retrieveImages(queryImage, ImageIndex);
scores;
figure
plot(sort(ImageIndex.WordFrequency))
%设置词频范围
ImageIndex.WordFrequencyRange = [0.01 0.2];
% 重新检索
[imageIDs, scores] = retrieveImages(queryImage, ImageIndex);
% 显示检索结果
helperDisplayImageMontage(queredImageSet.ImageLocation(imageIDs));