View License

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

» Watch video

Highlights from
Viola Jones Object Detection

4.7 | 20 ratings Rate this file 130 Downloads (last 30 days) File Size: 224 KB File ID: #29437 Version: 1.1
image thumbnail

Viola Jones Object Detection


Dirk-Jan Kroon (view profile)


17 Nov 2010 (Updated )

Viola Jones Object detection using OpenCV trained classifiers

| Watch this File

File Information

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

    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
    Objects : An array n x 4 with [x y width height] of the detected
  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);

Required Products Image Processing Toolbox
MATLAB release MATLAB 7.11 (R2010b)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (54)
08 Apr 2016 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!!!

clear all;
close all;

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

figure('Name','My Custom Preview Window');

% create an image object for previewing


% coordinates to draw lines




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





% 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



% initialize vision toolbox

shape=vision.ShapeInserter('BorderColor','Custom','CustomBorderColor',[255 255 0]);

%% press any key while you are ready

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

[Matl Nr]=bwlabel(BW2);
if Nr~=0
SecondSegment=imcrop(I2,[C1 R1 C2-C1 R2-R1]);
if isempty(bbox_eye1)~=1
subplot(3,2,1),imshow(I_Eye),title('EYE INPUT');
subplot(1,2,2),imshow(EyeRegion),title('EYE REGION');
ThirdSegment=imcrop(I2,[C1 R2 C2-C1 R3-R2]);
% figure(4),subplot(1,2,1),imshow(ThirdSegment);
if isempty(bbox_Nose1)~=1
%subplot(3,2,5),imshow(I_Nose),title('Nose INPUT');
%subplot(1,2,2),imshow(NoseRegion),title('Nose REGION');
FourthSegment=imcrop(I2,[C1 R3 C2-C1 R4-R3]);
if isempty(bbox_Mouth1)~=1
% subplot(3,2,3),imshow(I_Mouth),title('MOUTH INPUT');
% subplot(1,2,2),imshow(MouthRegion),title('MOUTH REGION');
if ((FlagForHead==1)&&(FlagEyes==1)&&(FlagNose==1)&&(FlagMouth==1))
disp('Normal Condition')
disp('possible drowsiness detection')
if cnt>5
disp('drowsiness confirmed')

Comment only
11 Feb 2016 Mohamad

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

Comment only
11 Feb 2016 Mohamad

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

Comment only
08 Nov 2015 usman khan

how to run this code?

Comment only
31 Mar 2015 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 ???

30 Mar 2015 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

Comment only
30 Mar 2015 lin nan

Please tell me how to use this code!thanks!

Comment only
25 Mar 2015 Erina

Erina (view profile)

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

Comment only
19 Mar 2015 Ean Yee Khor

sir,pls tell me how to run this email address is Thanks in advance

11 Mar 2015 khushi patel


Comment only
15 Dec 2014 amani Aljefri

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

Comment only
11 Nov 2014 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

Comment only
29 Aug 2014 Anshuman

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

Comment only
24 Aug 2014 Imam

Imam (view profile)

how to know how many people in picutre?

Comment only
26 Jul 2014 Duc Manh

20 Apr 2014 nhatmusic nhatmusic

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: i have nothing just a song played by myself as a gift ( have a nice day.

Comment only
19 Apr 2014 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
% 3 - ObjectDetection func.

Comment only
18 Apr 2014 nhatmusic nhatmusic

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.

28 Mar 2014 lourdes ramirez

I need the trainning algorithm would you mind upload?

Comment only
14 Mar 2014 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?

Comment only
14 Mar 2014 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.

Comment only
13 Mar 2014 Huri Zuhan

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

plz help out

Comment only
10 Feb 2014 jaknap32

01 Jan 2014 Tojo

Tojo (view profile)

13 Dec 2013 Akshay Gore

Akshay Gore (view profile)

03 Oct 2013 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!!

17 Jul 2013 carlos

carlos (view profile)

I need to put to run the algorithm
it works but not how to make it work
help please!!!

Comment only
18 Apr 2013 rana

rana (view profile)

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

Comment only
08 Apr 2013 Junxuan

Nice code. Could you tell me how I can modify it to detect vehicles?

Comment only
03 Apr 2013 KaMu

KaMu (view profile)

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

Comment only
14 Mar 2013 godspeed

I rewrite it into C++

26 Jan 2013 karan dev

sir i also wanted to know how to run this code. can anybody tell me at

Comment only
18 Jan 2013 sachin

sachin (view profile)

sir,pls tell me how to run this mail id

Comment only
13 Jan 2013 ali

ali (view profile)

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

05 Dec 2012 Nagesh

Nagesh (view profile)

Can any body explain this part form"haarcascade_frontalface_alt.xml"
- <rects>
<_>3 7 14 4 -1.</_>
<_>3 9 14 2 2.</_>

Comment only
01 Dec 2012 arusha imtiaz

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

Comment only
01 Oct 2012 Auon Kazmi

please tell me how to run this code specifying each instruction

Comment only
19 Sep 2012 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.

17 Sep 2012 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?

Comment only
17 Sep 2012 Binh Physel

10 Jul 2012 Liou

Liou (view profile)

15 Apr 2012 vaibhav

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

Comment only
01 Apr 2012 Nick

Nick (view profile)

29 Feb 2012 Arun

Arun (view profile)

21 Jan 2012 Daksha

Daksha (view profile)

Can you please tell how to run ur code ?

Comment only
16 Jan 2012 xu huabin

16 Jan 2012 xu huabin

Thank for you code!

Comment only
11 Dec 2011 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.

15 Sep 2011 Antony

Antony (view profile)

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

Comment only
27 Jun 2011 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

16 Feb 2011 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!

21 Jan 2011 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.

Comment only
30 Dec 2010 sara bilal

good work and thanks for sharing with all

Comment only
21 Dec 2010 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.

18 Nov 2010 1.1

Fixed Comment, and added xml file

Contact us