选用的人脸检测器:NPD Face Detector
单人脸的简单跟踪MATLAB代码。
close all; clear; clc;
mov = VideoReader('test.mov');
modelFile = 'model_frontal.mat'
load(modelFile, 'npdModel')
%原图中检测到的人脸位置
cddBoxX=0;
cddBoxY=0;
cddBoxW=0;
cddBoxH=0;
%在检测人脸时,为下一次检测产生的候选框。
rectX=0;
rectY=0;
rectW=0;
rectH=0;
%检测到的人脸总数
numFaces=0;
%总的检测时间
timeSum=0;
%总共检测的帧数
frameN=0;
for i=1:mov.NumberOfFrames
img = read(mov, i);
img = imresize(img,[640, 480]);
imgCpy = img;
if(i~=1 && numFaces>0)
%候选框的生成
rectX = cddBoxX*0.6;
rectY = cddBoxY*0.6;
rectW = cddBoxW*2.5;
rectH = cddBoxH*2.5;
%在原图中抠出候选框
img = imcrop(imgCpy, [rectX ,rectY ,rectW ,rectH]);
end
if(numFaces == 0)
img = imgCpy;
end
t1 = clock;
%人脸检测
rects = DetectFace(npdModel,img);
t2 = clock;
timeDet = etime(t2,t1);
timeSum = timeSum + timeDet;
frameN = frameN+1;
fprintf('detect time is: %f\n', timeDet);
numFaces = length(rects);
fprintf('%d faces detected.\n', numFaces);
%判断是在原图上检测的人脸,还是在候选框中检测的人脸,两者的显示是不同的。
if numFaces > 0
border = round(size(img,2) / 300);
if border < 2, border = 2; end
%注意这是一个单人脸检测的版本。
maxBox=0;
for j=1:numFaces
areas = rects[j].width * rects[j].height;
if(areas>maxBox)
index = j;
end
end
cddBoxX = rects(index).col;
cddBoxY = rects(index).row;
cddBoxW = rects(index).width;
cddBoxH = rects(index).height;
imgCpy = DrawRectangle(imgCpy, int16(rectX+cddBoxX), int16(rectY+cddBoxY), cddBoxW , cddBoxH , [0 255 0], border);
cddBoxX = rectX+cddBoxX;
cddBoxY = rectY+cddBoxY;
cddBoxW = cddBoxW;
cddBoxH = cddBoxH;
end
if numFaces > 0
border = round(size(img,2) / 300);
if border < 2, border = 2; end
maxBox=0;
for j=1:numFaces
areas = rects[j].width * rects[j].height;
if(areas>maxBox)
index = j;
end
end
cddBoxX = rects(index).col;
cddBoxY = rects(index).row;
cddBoxW = rects(index).width;
cddBoxH = rects(index).height;
imgCpy = DrawRectangle(imgCpy, cddBoxX, cddBoxY, cddBoxW , cddBoxH , [0 255 0], border);
end
imshow(imgCpy)
end
timeAvg = timeSum/frameN;
fprintf('average time: %f.\n', timeAvg);