slide window(滑窗)MATLAB代碼

  上一篇博客,我講了如何利用BOW(bag of words)詞袋模型進行圖片或者物體的歸類,並給出了MATLAB的代碼。但是代碼只能識別整張圖片,無法識別圖片裏面的特定區域,所以今天我準備分享一種直觀實用的方法——滑窗(slide window)法。

  滑窗法的思路就是用不同尺寸(scale)的窗口歷遍整張圖片,再將滑窗內的圖片進行處理。下面我將給出該方法的MATLAB代碼,跟註釋。

以下爲滑窗代碼:

function BoundingBox = SlideWindowDetector( I ,Template) 

%輸入: I                 -待處理圖片
%       Template          -模板圖片
%
%輸出: BoundingBox       -滑窗座標矩陣,爲 N x 4 的矩陣,每行儲存滑框四個頂點的座標, N 代表有N個滑窗。

[n, m] = size(I);

left = 0;
right = 0;
upper = 0;
bottom = 0;

% wid_step = 100;
% ht_step = n/;

BoundingBox = [];

ratio = numel(I)/(Template(2)*Template(1));

for scale = .35 :.15 : .65  % 滑窗尺寸在這裏設置
%     winWidth = round(Template(2)*scale); % 滑窗尺寸可以根據自身尺寸調整,也可以根據樣本尺寸調整。
%     winHeight = round(Template(1)*scale);
    winWidth = round(m*scale); % 滑窗的寬度(整數)
    winHeight = round(n*scale); % 滑窗的高度(整數)
    disp(['scanning windows of scale ' num2str(scale)])

    if n>m  % 判斷圖片I的長寬比,以調整橫向與縱向滑窗步進步長,當然你可以直接設置步長爲一個定值。
        wid_step = round(winWidth/4);
        ht_step = round(winHeight/6);
    else
        wid_step = round(winWidth/6);
        ht_step = round(winHeight/4);
    end
    
    for i = 1 : ht_step : (n-winHeight),
%         if ( (i + winHeight - 1) > n ), 
%             continue;
%         end
        
        for j = 1 : wid_step : (m-winWidth),
%             if ( (j + winWidth - 1) > m ),
%                 continue;
%             end
            
            tmp_img = I(i:i+winHeight-1, j:j+winWidth-1, :); % 獲得當前滑框內的圖像
            
            
            if (tmp_img ==  Template), %判斷滑框跟模板是否相等,相等則錄入滑框信息;
                left = j;
                right = j+winWidth-1;
                upper = i;
                bottom = i+winHeight-1;
                BoundingBox_tmp = [left, right, upper, bottom];
                BoundingBox = [BoundingBox;BoundingBox_tmp];
            end
        end
    end
end
end
以下爲顯示滑窗的代碼:

function VisualizeBox( I, Box )
%VisualizeBox Visualize detection results by overlaying the bounding box on
%the image.
%   I: the original image
%   Box: the bounding box, [left, right, upper, bottom]
%   left/right: the leftmost/rightmost index
%   upper/bottom: the upper/bottom index
%
%
if size(Box,1)~=0
    figure,
    imshow(I);
    hold on;
    for i=1:size(Box,1)
        line([Box(i,1), Box(i,1), Box(i,2), Box(i,2), Box(i,1)], [Box(i,3), Box(i,4), Box(i,4), Box(i,3), Box(i,3)], 'linewidth', 3, 'color', 'r');
    end
    hold off;
else
    disp('沒有檢測到人臉! ');
end
end
以下爲一些實例:


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