Matlab圖像識別/檢索系列(3)—10行代碼完成caltech圖象集分類和識別

Caltech是常用的圖像識別數據庫之一,加州理工有一個在Caltech上的圖像檢索工具包image-search ,提供了很多圖像檢索需要的功能,其中包括基於BOW的圖像檢索。該工具包的使用有一定難度,並且涉及函數很多。在Matlab2016中也有Caltech101的圖像分類和識別程序,代碼數量很少。

    % 數據庫下載地址,第一次執行需要聯網下載
    url ='http://www.vision.caltech.edu/Image_Datasets/Caltech101/101_ObjectCategories.tar.gz';
    outputFolder = fullfile(tempdir, 'caltech101'); 
    if ~exist(outputFolder, 'dir') % download only once
        disp('Downloading 126MB Caltech101 data set...');
        untar(url, outputFolder);
    end
    rootFolder = fullfile(outputFolder, '101_ObjectCategories');
    %爲加快速度只取三類圖像
    imgSets = [ imageSet(fullfile(rootFolder, 'airplanes')), ...
                            imageSet(fullfile(rootFolder, 'ferry')), ...
                            imageSet(fullfile(rootFolder, 'laptop')) ];
    %取各類圖像數目最小值
    minSetCount = min([imgSets.Count]); 
    %圖像集分割
    [trainingSets, validationSets] = partition(imgSets, 0.3, 'randomize');

    bag = bagOfFeatures(trainingSets);
    img = read(imgSets(1), 1);
    %使用圖像詞包(bag)對每幅圖像進行編碼,得出一個定長的向量
    featureVector = encode(bag, img);

    figure;
    %圖像向量分佈圖
    bar(featureVector);
    title('Visual word occurrences');
    xlabel('Visual word index');
    ylabel('Frequency of occurrence');
    %訓練圖像類別分類器
    categoryClassifier = trainImageCategoryClassifier(trainingSets, bag);
    %計算訓練集上的混淆矩陣
    confMatrix = evaluate(categoryClassifier, trainingSets);
    confMatrix = evaluate(categoryClassifier, validationSets);

    % 計算平均準確度
    mean(diag(confMatrix));
    img = imread(fullfile(rootFolder, 'airplanes', 'image_0690.jpg'));
    %對指定圖像進行識別
    [labelIdx, scores] = predict(categoryClassifier, img);

該示例關鍵代碼也只有幾行,除了計算圖象集詞包,還利用encode函數對圖像編碼,生成了特徵向量,也有人叫做視覺向量。該示例中,僅畫出了視覺向量的分佈圖,沒有它用。事實上,該向量可作爲圖像特徵進一步完成圖像檢索、分類、識別等任務,相比直接使用提取詞袋的局部特徵,可大大減少計算複雜度和內存消耗。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章