上一篇博客,我讲了如何利用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以下为一些实例: