File Exchange

image thumbnail

Viola Jones Object Detection

version 1.1 (224 KB) by

Viola Jones Object detection using OpenCV trained classifiers

4.68421
20 Ratings

65 Downloads

Updated

View License

This function ObjectDetection is an implementation of the Detection in the Viola-Jones framework. In this framework Haar-like features are used for rapid object detection. It supports the trained classifiers in the XML files of OpenCV which can be download as part of the OPENCV software on opencv.willowgarage.com


Objects=ObjectDetection(I,FilenameHaarcasade,Options)

inputs,
I : 2D image, or Filename of an image
FilenameHaarcasade : The filename of a Matlab file with a Haarcasade which is created from an OpenCV xml file
Options : A struct with options
Options.ScaleUpdate : The scale update, default 1/1.2
Options.Resize : If boolean is true (default), the function will
resize the image to maximum size 384 for less cpu-time
Options.Verbose : Display process information

outputs,
Objects : An array n x 4 with [x y width height] of the detected
objects

Literature :
- Rainer Linehart and Jochend Maydt, "An Extended Set of Haar-like
Features for Rapid Object Detection"
- Paul viola and Michael J. Jones, "Rapid Object Detection using
a Boosted Cascade of Simple Features", 2001

Example 1,
% % Convert an OpenCV classifier XML file to a Matlab file
% ConvertHaarcasadeXMLOpenCV('HaarCascades/haarcascade_frontalface_alt.xml');
% % Detect Faces
% Options.Resize=false;
% ObjectDetection('Images/1.jpg','HaarCascades/haarcascade_frontalface_alt.mat',Options);

Comments and Ratings (55)

Olfa Mechi

hi , can anybody tell me about how to run this code? : olfamechi@yahoo.fr

pawan gupta

Hi,can anybody tell me about the algorithm which is used in the following code? like viola jones,template matching etc.

it would be greatly appericiated if u could help me.
thank you!!!

clc
clear all;
close all;

% initialize webcam (read instructions if required 'README_TO_SET_YOUR_CAMERA.m')

vobj=videoinput('winvideo',1,'YUY2_640x480','ReturnedColorSpace','rgb');
figure('Name','My Custom Preview Window');
uicontrol('string','close','callback','close(gcf)');

% create an image object for previewing

vidRes=get(vobj,'VideoResolution');
nBands=get(vobj,'NumberOfBands');
hImage=image(zeros(vidRes(2),vidRes(1),nBands));
preview(vobj,hImage);

%pause
% coordinates to draw lines

rs=vidRes(2);
cs=vidRes(1);
C1=floor(cs/6);
C2=floor(267*cs/320);

C3=floor(0);
C4=floor(cs);

R1=floor(rs/4);
R2=floor(rs/2);
R3=floor(3*rs/4);
R4=floor(rs);

x1=[C1 C1];
x2=[C2 C2];
x3=[C3 C3];
x4=[C4 C4];

x5=[C3 C4];

y1=[0 rs];
y2=[R1 R1];
y3=[R2 R2];
y4=[R3 R3];
y5=[R4 R4];

%draw lines

line(x1,y1,'color','r','LineWidth',2)
line(x2,y1,'color','r','LineWidth',2)

%line(x3,y1,'color','g','LineWidth',2)
%line(x4,y1,'color','g','LineWidth',2)

line(x5,y2,'color','g','LineWidth',2)
line(x5,y3,'color','g','LineWidth',2)
line(x5,y4,'color','g','LineWidth',2)

%line(x5,y5,'color','w','LineWidth',2)

% write text

text1=text(19*cs/96,rs/8,'FOREHEAD REGION','color','r');
text2=text(19*cs/96,3*rs/8,'EYE REGION','color','r');
text3=text(19*cs/96,5*rs/8,'NOSE REGION','color','r');
text4=text(19*cs/96,7*rs/8,'MOUTH REGION','color','r');
% initialize flags

FlagForHead=0;
FlagEyes=0;
FlagNose=0;
FlagMouth=0;

cnt=0;

% initialize vision toolbox

shape=vision.ShapeInserter('BorderColor','Custom','CustomBorderColor',[255 255 0]);
EyeDetector1=vision.CascadeObjectDetector('EyePairSmall');
NoseDetector=vision.CascadeObjectDetector('Nose');
MouthDetector1=vision.CascadeObjectDetector('Mouth');

%% press any key while you are ready

for i=1:50 % for 200 frames, increse/decrese if required
I2=getsnapshot(vobj);
pause(0.5)
FirstSeg=imcrop(I2,[C1 0 C2-C1 R1]);
% figure(2),subplt(1,2,1);imshow(FirstSeg);

BlackDetect=(FirstSeg(:,:,1)<70)&(FirstSeg(:,:,2)<70)&(FirstSeg(:,:,3)<70);
BW1=imfill(BlackDetect,'holes');
BW2=bwareaopen(BW1,2000);
%subplot(1,2,2),imshow(BW2);
[Matl Nr]=bwlabel(BW2);
if Nr~=0
FlagForHead=1;
else
FlagForHead=0;
end
SecondSegment=imcrop(I2,[C1 R1 C2-C1 R2-R1]);
figure(3),subplot(1,2,1),imshow(SecondSegment);
bbox_eye1=step(EyeDetector1,SecondSegment);
I_Eye=step(shape,SecondSegment,int32(bbox_eye1));
if isempty(bbox_eye1)~=1
FlagEyes=1;
EyeRegion=imcrop(SecondSegment,[bbox_eye1(1,1),bbox_eye1(1,2),bbox_eye1(1,3),bbox_eye1(1,4)]);
subplot(3,2,1),imshow(I_Eye),title('EYE INPUT');
subplot(1,2,2),imshow(EyeRegion),title('EYE REGION');
else
FlagEyes=0;
end;
ThirdSegment=imcrop(I2,[C1 R2 C2-C1 R3-R2]);
% figure(4),subplot(1,2,1),imshow(ThirdSegment);
bbox_Nose1=step(NoseDetector,ThirdSegment);
I_Nose=step(shape,ThirdSegment,int32(bbox_Nose1));
if isempty(bbox_Nose1)~=1
FlagNose=1;
%
NoseRegion=imcrop(ThirdSegment,[bbox_Nose1(1,1),bbox_Nose1(1,2),bbox_Nose1(1,3),bbox_Nose1(1,4)]);
%subplot(3,2,5),imshow(I_Nose),title('Nose INPUT');
%subplot(1,2,2),imshow(NoseRegion),title('Nose REGION');
else
FlagNose=0;
end;
FourthSegment=imcrop(I2,[C1 R3 C2-C1 R4-R3]);
%figure(5),subplot(1,2,1),imshow(FourthSegment);
bbox_Mouth1=step(MouthDetector1,FourthSegment);
I_Mouth=step(shape,FourthSegment,int32(bbox_Mouth1));
if isempty(bbox_Mouth1)~=1
FlagMouth=1;
%
MouthRegion=imcrop(FourthSegment,[bbox_Mouth1(1,1),bbox_Mouth1(1,2),bbox_Mouth1(1,3),bbox_Mouth1(1,4)]);
% subplot(3,2,3),imshow(I_Mouth),title('MOUTH INPUT');
% subplot(1,2,2),imshow(MouthRegion),title('MOUTH REGION');
else
FlagMouth=0;
end;
if ((FlagForHead==1)&&(FlagEyes==1)&&(FlagNose==1)&&(FlagMouth==1))
disp('Normal Condition')
cnt=0;
else
disp('possible drowsiness detection')
cnt=cnt+1;
end
if cnt>5
cnt=0;
disp('drowsiness confirmed')
end
end

Mohamad

when I train my own classifier with MIT-CBCL dataset it doesnt detect any face in pictures. poor code. :(

Mohamad

when I train my own classifier with MIT-CBCL dataset it doesnt detect any face in pictures. poor code. :(

usman khan

how to run this code?

adam AHMED

Thank you for this helpful function .
I have a question . does Cas​cadeObject​Detector function give the same performance as Opencv "haartraing" function ???
if yes then way opencv take all that time to finish the trainning ???

lin nan

I don't know this sentanse,please help me!
FilenameHaarcasade : The filename of a Matlab file with a Haarcasade which is created from an OpenCV xml file
Options : A struct with options

lin nan

Please tell me how to use this code!thanks!734948550@qq.com

Erina

Erina (view profile)

Is this code accurate? I have downloaded and tried it. It only detect 45 cropped face images out of 100.

Ean Yee Khor

sir,pls tell me how to run this code.my email address is yiyijanice@gmail.com. Thanks in advance

khushi patel

123456789

amani Aljefri

please I need help>>what is the input for options?..I am new to malab

Jia Zhen

Sir, when i try to run ConvertHaarcasadeXMLOpenCV(filename) i keep getting this error
Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N) to change the limit. Be aware
that exceeding your available stack space can crash MATLAB and/or your computer.

Error in ConvertHaarcasadeXMLOpenCV

what should i do to solve the problem? thanks

Anshuman

What should be the input like for the "options" structure?

Imam

Imam (view profile)

how to know how many people in picutre?

Duc Manh

Rafaee,sr for disturbing u again. i have trouble with my final project,"People counting system using camera(in Matlab)". Can u give me some advice about how can we apply Viola-jones algorithm to counting people? my email: nhatmusic@gmail.com. i have nothing just a song played by myself as a gift (https://www.youtube.com/watch?v=c2ima-xlzro).relaxing. have a nice day.

Rafaee

Rafaee (view profile)

@nahatmusic, Example 1,
% 1- Need to Convert an OpenCV classifier XML file on a Matlab. There should be XML in HaarCascades folder / .xml
% 2 - Detect Faces
Options.Resize=false;
% 3 - ObjectDetection func.
ObjectDetection('Images/1.jpg','HaarCascades/haarcascade_frontalface_alt.mat',Options);

Rafaee, I try to run the example 1. no error. I wait for 20 minutes but it gives no result. The ObjectDetection function is still running. What can i do? plz help me. thank for your help.

I need the trainning algorithm would you mind upload?

Huri Zuhan

okay thanks Rafaee its solved but, then what is the purpose of rest of the uncommented code?

i mean what is use of uncommented code in objectdetection.m file?

Rafaee

Rafaee (view profile)

Huri Zuhan, On top of the m file there is the full description with 2 Examples.You can RUN those examples to get idea.

Huri Zuhan

can anyone please help me with objectdetection.m file, i dont know where to give which argument

plz help out

jaknap32

Tojo

Tojo (view profile)

Akshay Gore

Akshay Gore (view profile)

ISRAA

ISRAA (view profile)

Please, I am getting Error :
Warning: Function C:\Users\loona\det.m has the same name as a MATLAB builtin. We suggest you rename the function to avoid a potential name conflict.
> In path at 110
In addpath at 87
In ObjectDetection at 55
Error using ObjectDetection (line 58)
Not enough input arguments.
How can I upload my image to this detector? Help!!

carlos

carlos (view profile)

I need to put to run the algorithm
it works but not how to make it work
help please!!!
mail: zion50000@hotmail.com

rana

rana (view profile)

hi, this code worked fine for me.. could i use it for a real time detection .. in a video sequence ?

Junxuan

Hi,
Nice code. Could you tell me how I can modify it to detect vehicles?
manumavs@hotmail.com

KaMu

KaMu (view profile)

Is it only usable for face detection? how can I implement it for detecting other objects?

godspeed

karan dev

sir i also wanted to know how to run this code. can anybody tell me at coolkaran2005@gmail.com?

sachin

sachin (view profile)

sir,pls tell me how to run this code.my mail id sachhi111@rediffmail.com

ali

ali (view profile)

Hi. I want to Detection Eyes For Drowsy Driver. Please, say to me that, How do I? Thanks.
noorian1363@yahoo.com

Nagesh

Nagesh (view profile)

Can any body explain this part form"haarcascade_frontalface_alt.xml"
<feature>
- <rects>
<_>3 7 14 4 -1.</_>
<_>3 9 14 2 2.</_>
</rects>
<tilted>0</tilted>
</feature>
<threshold>4.0141958743333817e-003</threshold>
<left_val>0.0337941907346249</left_val>
<right_val>0.8378106951713562</right_val>
</_>

this code doesnt work when i convert the xml file for eye detection.

Auon Kazmi

PLEASE PLEASE PLEASE
please tell me how to run this code specifying each instruction

Binh Physel

Dear Mr.Kroon,
Thank you for sharing. I have a problem when I try to convert openCV XML to mat file. >>ConvertHaarcasadeXMLOpenCV('HaarCascades/haarcascade_frontalface_alt.xml')
??? Undefined function or method 'ConvertHaarcasadeXMLOpenCV' for input arguments of type 'char'.
Could you please tell me the reason why? Thanks in advance.

Raul

Raul (view profile)

I have the same problem of Chun-Yi. When I try to run your code with another trained classifier, I have the error :"Warning: Tilted features are not supported "
And there is no results.
How I can solve the problem?

Binh Physel

Liou

Liou (view profile)

vaibhav

we dont need to train the classifiers..is it like that??it means we can save weeks of time??am i right???

Nick

Nick (view profile)

Arun

Arun (view profile)

Daksha

Daksha (view profile)

Can you please tell how to run ur code ?

xu huabin

xu huabin

Thank for you code!

Yue WU

Yue WU (view profile)

I had a similar problem with Chun-Yi. After modifying the code base on Antony's comment, I could run eye detection.

Antony

Antony (view profile)

I found a bug.
In OneScaleObjectDetection.m line number 12.
Variance(Variance<1)=1; < incorccect
Variance(Variance<0)=1; < correct

Nikolay S.

Nikolay S. (view profile)

Good morning Dirk-Jan Kroon.
I've downloaded the code, and applied it to different images (after reading the Viola Jones paper). Worked like magic, without any adaptation (I've used the example parameters you've suggested).
However, I've noticed massive False Negatives (non detections) and a few False Positives (false alarms) (I can send you the images I've used). What makes things odd is the fact that cropping image to smaller sub images, without any resolution change improves the True Positive detection rate (that is some faces missed at original image were detected at the sub image). I assume that this is due to the fact that scaling in smaller image results in a higher resolution, but that's my guess only. I need to improve the current results. Assuming you have applied your code to many different images I'd like to ask you how can the False negative rate be improved:
1) Additional classifier training?
2) Scale smaller than 1.25 proposed by viola Jones?
3) Any other parameters to be changed?
Thanks in advance
Nikoaly.

Stefan Grandl

Very cool, thanks a lot!

But one has to put some subsequent effort in using the code. It gives you all the face candidates that are detected by the Viola-Jones algorithm. But to be able to use these candidates for further programming one has to think about how to group the candidates and just keep those rectangles that overlap each other.

And this is not an easy part... at least for me by now... :D

But nevertheless...thanks a lot for the code!

Thomas

Thomas (view profile)

Very nice code! I'm so glad I don't have to compile the entire OpenCV library.

However, I'm having the same problem Chun-Yi is having, any other cascade except the included "frontface_alt" gives no results.

Furthermore, detection rates drop very fast at lower resolutions. I actually have to *upsample* my images (to something like 2000x1000 pixels, for group portraits) to detect faces. The "Scale" parameter is supposed to scale images down to 384 pixels, but I can't imagine getting *any* detections at that scale.

sara bilal

good work and thanks for sharing with all

Chun-Yi

Hi, Kroon

Good codes. Thanks for your sharing.
It works well by applying the cascade transformed from haarcascade_frontalface_alt.xml.
But it would be failed to detect anything if applying the cascade transformed from haarcascade_frontalface_default.xml which is also provided by OpenCV.
Could you please figure out what the reason is? Thank you.

Updates

1.1

Fixed Comment, and added xml file

MATLAB Release
MATLAB 7.11 (R2010b)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video