您的位置:首页 > 编程语言 > MATLAB

Matlab基于Viola-Jones算法的人脸检测(2)

2016-05-26 16:02 471 查看
VJ算法的目的是检测人脸,但是其思想同样可以用于检测其他物体,只需进行训练即可。

VJ算法在Matlab里面实现的时候,已经训练好了正脸、侧脸、上半身、眼睛、嘴、鼻子,这些都是可以直接检测,不需训练,直接调用CascadeObjectDetector函数即可

% Example 1:  Face detection
% ----------------------------
faceDetector = vision.CascadeObjectDetector; % Default: finds faces

I = imread('visionteam.jpg');
bboxes = step(faceDetector, I); % Detect faces

% Annotate detected faces
IFaces = insertObjectAnnotation(I, 'rectangle', bboxes, 'Face');
figure, imshow(IFaces), title('Detected faces');

% Example 2: Upper body detection
% --------------------------------------
bodyDetector = vision.CascadeObjectDetector('UpperBody');
bodyDetector.MinSize = [60 60];
bodyDetector.MergeThreshold = 10;

I2 = imread('visionteam.jpg');
bboxBody = step(bodyDetector, I2); % Detect upper bodies

% Annotate detected upper bodies
IBody = insertObjectAnnotation(I2, 'rectangle', ...
bboxBody, 'Upper Body');
figure, imshow(IBody), title('Detected upper bodies');


这是Matlab里面的两个例子

下面说一下训练的过程,Matlab里面也提供给了用户自己进行训练的函数trainingImageLabeler,调用这个函数会打开一个app,如下:



新建Session之后,Add Images,然后就可以标记ROI,如下:



然后保存Session,还有重要的一步是Export ROIs,将ROIs导出,然后会提示你保存变量名,写好变量名之后ok,命令行会出现下面的文字



工作区里会出现你命名的变量



下面就是训练

positiveInstances=evalin('base','positiveInstances');
% Add the image directory to the MATLAB path
imDir = fullfile('train\positive');
addpath(imDir);
% Specify folder with negative images
negativeFolder = fullfile('train\negative');
% Train a cascade object detector called 'stopSignDetector.xml'
% using HOG features.
% NOTE: The command below can take several minutes to run
trainCascadeObjectDetector('new.xml',positiveInstances,...
negativeFolder, 'FalseAlarmRate', 0.1, 'NumCascadeStages', 5);


我这段代码是写在函数里的,所以要先用evalin函数将工作区里的变量导进来,然后添加正样本和负样本的路径,最后调用trainCascadeObjectDetector进行训练,这个函数的参数可以设置很多,具体参数可以看函数内部代码。函数默认采用HOG特征,可以选择Haar和LBP特征。选择Haar特征时训练的时间可能会很长,占用的资源比较大。

有了训练好的xml文件之后就可以直接调用CascadeObjectDetector函数来检测

detector = vision.CascadeObjectDetector('new.xml');

% detector.MinSize = [60 90];
% detector.MaxSize = [50 80];
detector.MergeThreshold =10;

img = imread(pathfile); % read the test image

bbox = step(detector, img);
% Insert bounding box rectangles and return marked image
detectedImg = insertObjectAnnotation(img, 'rectangle', bbox,'Result');
imshow(detectedImg);


以上就是Viola-Jones算法在Matlab里面的实现

参考资料:

http://cn.mathworks.com/help/vision/ref/vision.cascadeobjectdetector-class.html#bs_hhwg-4

http://cn.mathworks.com/help/vision/ug/train-a-cascade-object-detector.html

http://cn.mathworks.com/help/vision/ug/label-images-for-classification-model-training.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  matlab