Saturday, July 28, 2012

SVM Tutorial, HOG based Face Detection using SVM-Light in Matlab



This tutorial will show you how to use SVM-Light [1] for Object detection (face, car, person or any other object recognition) in Matlab.  Particularly, it will implement a very basic Face Detector just to give you a bit of intuition about how these things work. I have uploaded the source code of this tutorial here, which is well commented and quite self explanatory. It shouldn’t be hard to understand and modify it for any other object detection. All you have to do is to follow the step in Section 2 to and make it work on your system. Section 1 is the detailed explanation of the algorithm.

Section 1
Algorithm Overview

There are two key factors involved in object detection: (1) to choose an efficient feature descriptor, (2) selection of proper classifier. I choose HOG [3] and off course SVM for this tutorial. The approach is quite straightforward; to train a support vector machine you need some positive (face) and some negative (non face) labeled examples. For each training example, extract features from each image and train a SVM to differentiate between the two classes. For detection, scan the test image in sliding window fashion. For each window extract features and run the classifier to determine whether or not there is a face at that location.

Training:

There are 322 images originally and their flipped version, so total of 644 positive (face) examples and the same way 2572 negative (non face) examples in the training dataset. To train the SVM you will need to extract feature from both positive and negative examples and label them as 1 for positive and -1 for negative examples in case of SVM-Light, and if you want binary classification then labels should be 1 and 0 respectively. Below is the example code.

if exist('model.mat','file')
    load model;
else
    [fpos, fneg] = features(pathPos, pathNeg);  % extract features
    [ model ] = trainSVM( fpos,fneg );          % train SVM
    save model model;
end

function [fpos, fneg] = features(pathPos,pathNeg)
% extract features for positive examples
imlist = dir([pathPos '*.png']);
for i = 1:length(imlist)
    im = imread([pathPos imlist(i).name]);
    fpos{i} = HOG(double(im));
end
% extract features for negative examples
imlist = dir([pathNeg '*.png']);
for i = 1:length(imlist)
    im = imread([pathNeg imlist(i).name]);
    fneg{i} = HOG(double(im));
end

end

function [ model ] = trainSVM( fpos,fneg )
SV = loadingV(fpos,fneg);   % loading and labeling each training example
fprintf('Training SVM..\n');
T = cell2mat(SV(2,:));
tP = SV(3,:)';
P = cell2mat(tP); % each row of P correspond to a training example
model = svmlearn(P, T', '-t -g 0.3 -c 0.5');
fprintf('done. \n');
end


Testing:

Here is the example code for detection.

function detect(im,model,wSize)
%{
this function will take three parameters
    1.  im      --> Test Image
    2.  model   --> trained model
    3.  wStize  --> Size of the window, i.e. [24,32]
and draw rectangle on best estimated window
%}

topLeftRow = 1;
topLeftCol = 1;
[bottomRightCol bottomRightRow d] = size(im);

fcount = 1;

% this for loop scan the entire image and extract features for each sliding window
for y = topLeftCol:bottomRightCol-wSize(2)   
    for x = topLeftRow:bottomRightRow-wSize(1)
        p1 = [x,y];
        p2 = [x+(wSize(1)-1), y+(wSize(2)-1)];
        po = [p1; p2];
        img = imcut(po,im);     
        featureVector{fcount} = HOG(double(img));
        boxPoint{fcount} = [x,y];
        fcount = fcount+1;
        x = x+1;
    end
end

lebel = ones(length(featureVector),1);
P = cell2mat(featureVector);
% each row of P' correspond to a window
[~, predictions] = svmclassify(P',lebel,model); % classifying each window

[a, indx]= max(predictions);
bBox = cell2mat(boxPoint(indx));
rectangle('Position',[bBox(1),bBox(2),24,32],'LineWidth',1, 'EdgeColor','r');
end


Section 2

To compile this library in Matlab you will need a C compiler and Mex function. So, let’s start with setting up Mex.

1.      Setting up Mex

If you have done this already, skip this part. Setting up Mex is very easy; all you have to do is to
  • Get and install a Matlab supported compiler.
  • Type mex -setup in Matlab’s command window press enter and then to locate compiler enter ‘y’, to select Compiler enter its number. Similar as in the figure below.



Note: The list of compilers shown on your system might be different from the list shown in this example. The path names to your compilers might also be different.  To read more about Mex click here and here 

2.      Download and extract the source code of this tutorial from here, set it to current working directory in matlab.
3.      Download SVM-Light from here
4.      Extract it into current working directory


5.      Add following paths to main file, demo.m in our case.

addpath './svm_mex601/matlab';
addpath './svm_mex601/bin';

6.      The library is precompiled; all binary files can be found in the ‘bin’ folder. Sometimes they work just fine but sometimes they cause problems, maybe due to compatibility and architectural issues. To compile them run compilemex()after adding the above paths.  compilemex.m  is located in the directory ‘matlab’ and resulting binary files should be stored in ‘bin’ directory. If compilemex fails then you would need to edit compilemex.m  as follows.

At line number 4 replace ‘cd bin’ to ‘cd svm_mex601/bin’ and add one more ‘cd ..’ after line 18 to point back to current working directory. As shown in the figure below



To run the compilemex insert break point after addpath lines as shown in the figure below, press F5 or click on the run button and when debugger stops at the break point run compilemex() through command window.





This might show some warning but don’t worry everything will work fine, if it is compiled successfully.

7.      Run mex HoG.cpp [2] through command window to compile the HoG.cpp file.


That’s it, everything is now ready to run this face detection code. To do so run the demo.m, this will read an image and determine whether or not there is a face in that image.


Results:











References
[3] N. Dalal, and B. Triggs. Histograms of Oriented Gradients for Human Detection. In Proc. CVPR, 2005.

61 comments:

  1. hi, first of all thank you so much your tutorial. It is great! very easy to follow. I hope you generate more tutorials like that.
    Could you give any idea so that I apply any size of window for face detection? Thank you very much in advance!

    ReplyDelete
  2. Hi,

    how to use this Algorithm in Traffic sign Detection,
    could you give any idea so that i can use it in javacv.

    Thanks very much in advance

    ReplyDelete
  3. Thank you very much for your post. I tried your way but keep getting an error message like this:

    K>> compilemex
    Compiling mexsvmlearn
    Error: Could not find the compiler "cl" on the DOS path.
    Use mex -setup to configure your environment properly.


    C:\PROGRA~1\MATLAB\R2011A\BIN\MEX.PL: Error: Unable to locate compiler.

    compile failed

    If you have any idea what went wrong, please help me. Thank you in advance

    ReplyDelete
    Replies
    1. it's a compilation error you probably haven't configured your environment properly. As i stated above in the tutorial, to compile c/c++ files in Matlab you need to setup c compiler with mex function, which actually is the first setup of the tutorial. please follow it to setup your Matlab environment.

      Delete
    2. hi, I used Microsoft Visual C++ 2010 Express Complier. I did perform the setup, the setup went through but the error that i mentioned previously still happened. While setting up the complier, matlab gave me 2 warnings:
      Warning: MEX-files generated using Microsoft Visual C++ 2010 require
      that Microsoft Visual Studio 2010 run-time libraries be
      available on the computer they are run on.
      If you plan to redistribute your MEX-files to other MATLAB
      users, be sure that they have the run-time libraries.

      Warning: The MATLAB C and Fortran API has changed to support MATLAB
      variables with more than 2^32-1 elements. In the near future
      you will be required to update your code to utilize the new
      API. You can find more information about this at:
      http://www.mathworks.com/support/solutions/en/data/1-5C27B9/?solution=1-5C27B9
      Building with the -largeArrayDims option enables the new API.

      Was it because it was an express version not standard one? - Thank you so much for your help

      Delete
  4. Hey! Thanx for this one! :D
    but I'm getting an error when I run this.

    It says..

    ??? ERR-002 - samples must be an mxn matrix, lables must be an mx1, The m dimensions don't match.

    Error in ==> trainSVM at 8
    model = svmlearn(P, T', '-t -g 0.3 -c 0.5');

    Error in ==> demo at 29
    [ model ] = trainSVM( fpos,fneg ); % train SVM


    What do I do?

    ReplyDelete
  5. Hi~thx for the code.
    But there might be some problem, could you please provide the loadingV.m?

    ReplyDelete
  6. Thanks.. you can download the complete code by clicking on "here" in the first paragraph, line 4.

    ReplyDelete
    Replies
    1. Yes, it works very well, thank you very much. This is the 1st time I play with feature extraction+classification, wonderful experience!

      Delete
    2. hi 虞ē«‹ęˆ
      could you plez tell me how u run it, because I have this error when run this code:

      Cannot find an exact (case-sensitive) match for 'HoG'

      The closest match is: HOG in C:\Users\Samora\Desktop\New
      folder\face_detection_SVMlight\face detection\HOG.m


      Error in HOG (line 9)
      HOGv = HoG(I,[orientation_bins, cell_size, block_size, oriented_gradients,
      clipping_L2norm]);

      Error in detect (line 23)
      featureVector{fcount} = HOG(double(img));

      Error in demo (line 39)
      detect(img,model,tSize);

      Delete
    3. I have the same error. Did you resolved it ?? Please help.

      Delete
  7. Thanks for your great code.
    How can we detect multiple people using your code from RGB image from Microsoft Kinect?

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. hello!
    first of all thank you so much your tutorial.
    It is great!.
    I hope you generate more tutorials like that.
    I run the program, the program recognizes the faces very well.
    But, I have a small question to ask you. I hope you help me?
    If the image has no face, it was mistaken identity programs.
    You can fix this. I hope you help me.
    have a great day!

    ReplyDelete
    Replies
    1. Thanks, you can just set a threshold for that. If an image have no face then the classifier score will be very low. My intentions for this tutorial was not face detection, so didn't implement the complete face detector. It's currently picking the max score region in the image, set a threshold there if the max score is say less than 0.3 then the image do not contain a face.

      Delete
    2. C:\PROGRA~1\MATLAB\R2013A\BIN\MEX.PL: Error: 'HoG.cpp' not found.
      plzz help

      Delete
    3. mail id swatinagori60@gmail.com

      Delete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Hello Ali,
    Thanks for the code, please how did you manage to get feature vectors of the same size ? when I am extracting features from a different set of images, then my feature vectors are of different sizes, so the CELL2MAT functions will not work
    Best
    Yara

    ReplyDelete
  14. HI Ali
    Thanks for what u thought taught...i have 2 questions that i will be appreciated if help...
    1) what your database address( i am working on face detection and your database is very good! )
    2) i want to use SVM Struct ( introduced by Dr Vedaldi ). i want to use its output ( like output of svmtrain() ) for a new data. actually i want to use svmclassify() but with the output of SVMStruct's output as its "model"( as you used i your code)

    please help me...
    ALI

    ReplyDelete
  15. Hi Ali,,

    I am doing a research on people detection in a crowd and I am planning to use HOG method. I found your code is so working on face detection and I tried to edit your code and change the datasets image also to be used on people detection, but why did take so long on processing and even the result cant be displayed? Can you help me how to use your code on people detection?

    Thank you,
    Best regards,

    Indra

    ReplyDelete
  16. Firstly thanks for sharing your knowledge to us,
    in your code , if we want to use different datasets you provided the code:
    %% if you want to use your own dataset then following functions could be
    % used for cropping the faces, non-face or positive and negative examples
    % respectively
    % pathN = './INRIA/';
    % grab_neg(pathN,pathNeg); % cut image into 4 equal sub images
    % flip_all( pathPos, pathNeg ); % Flip and write images to their corresponding directories

    This just cuts a negative samples into four. and does some flipping for both positive and negative samples. Say i want to detect "guns", I assume i would need to provide positive samples of guns and also the flipped images?, Why do i need the "grab_neg"

    ReplyDelete
  17. Hello, your tutorial is very easy and nice.
    I try to run your code. But I have a code problem. The error same as below.

    ??? Error using ==> HOG
    Too many input arguments.

    Error in ==> HOG at 9
    HOGv = HoG(I,[orientation_bins, cell_size, block_size, oriented_gradients, clipping_L2norm]);

    Error in ==> detect at 23
    featureVector{fcount} = HOG(double(img));

    Error in ==> demo at 39
    detect(img,model,tSize);

    If the problem is about complier, Please give me a solution.

    ??? Error using ==> mex at 208
    Unable to complete successfully.

    Thanks Ali.

    ReplyDelete
    Replies
    1. I can not download code.
      Can you please help.
      thank.

      Delete
    2. you can download the complete code by clicking on "here" in the first paragraph, line 4.

      Delete
  18. This comment has been removed by the author.

    ReplyDelete
  19. Thanks for code i cannot runing error is cannot file HoGmexw64 plz help

    ReplyDelete
  20. i am getting error : Undefined function 'mexsvmclassify' for input arguments of type 'struct'.
    Error in svmclassify (line 19)
    [ err, predictions ] = mexsvmclassify(x,y,model);
    Error in detect (line 33)
    [~, predictions] = svmclassify(P',lebel,model); % classifying each window

    Error in demo (line 39)
    detect(img,model,tSize);

    please provide me solution for this.
    Thank you

    ReplyDelete
  21. Hi! Mr. Ali Hassan. Your tutorial is great. However, i ve got a small issue. After adding the paths and extracting files in the specified folder, I get the following errors while running the demo.m code

    undefined function 'mexsvmclassify' for input arguments of type 'struct'.

    Error in svmclassify (line 19)
    [ err, predictions ] = mexsvmclassify(x,y,model);

    Error in detect (line 33)
    [~, predictions] = svmclassify(P',lebel,model); % classifying each window

    Error in demo (line 41)
    detect(img,model,tSize);

    I am unable to get rid of these errors. Please help me out.
    Thanks

    ReplyDelete
  22. hello Ali Hasaan sir,
    Sir " To run the compilemex insert break point after addpath lines as shown in the figure below, press F5 or click on the run button and when debugger stops at the break point run compilemex() through command window. "

    I done this step but still i have faced one error

    12 pathPos = './dataset/faces/'; % positive example
    K>> compilemex
    compile failed
    K>> compilemex()
    compile failed
    K>>


    Please give me reply as soon as possible sir thank you so much sir

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. Dear Ali Hassan,
    I am working on SVM, I want ask you a help, I want compiling and invoking the algorithm of SVMlight in ( http://svmlight.joachims.org/ )as MEX function
    from within the MATLAB environment.

    cd('C:\Users\hp\Documents\MATLAB\svm_struct')
    addpath('C:\Users\hp\Documents\MATLAB\svm_mex601\matlab');
    addpath ('C:\Users\hp\Documents\MATLAB\svm_mex601\bin');
    compilemex();
    cmd=['-c 1 -w 3 -l 10 '];
    model=svm_learn(X,Y,cmd);
    it give me:

    compile failed
    Undefined function or method 'svm_learn'
    please provide me solution for this.
    Thank you
    Reply

    ReplyDelete
  25. your code is detecting face or non face region.can HOG be used for differentiating between different faces?

    ReplyDelete
  26. The following error comes when running demo.m

    Error using HOG
    Too many input arguments.

    Error in HOG (line 9)
    HOGv = HOG(I,[orientation_bins, cell_size, block_size, oriented_gradients, clipping_L2norm]);

    Error in detect (line 23)
    featureVector{fcount} = HOG(double(img));

    Error in demo (line 40)
    detect(img,model,tSize);

    ReplyDelete
  27. kindly help me to implement the same in visual studio using opencv libraries. i have downloaded the svmlight files but i am getting linking errors. Please help me out in rectifying this. Write me reply to this mail mbrraghu@gmail.com

    Thanks
    Raghunandan B

    ReplyDelete
  28. I am working on HOG descriptor for human detection i have a problem into Testing phase so kindly help me plz dear brother...

    ReplyDelete
  29. great code ! :) it works. have any code for vehicle detection using hog and svm?

    ReplyDelete
    Replies
    1. i am getting this error " c:/PROGRA~1\MATLAB\R2013A\BIN\MEX.PL: Error:'HoG.cpp' not found. kindly help and reply asap.

      Delete
  30. can we detect multiple faces in same image with this pogram

    ReplyDelete
  31. i did exactly as the tutorial but still give me compile failed any help??

    ReplyDelete
  32. hello~thanks for your guide.
    i try to run the code,it show no error but there were no image shown on output windows.
    i really need help.anyone?
    thank you

    ReplyDelete
  33. Hello,
    Thank you very much for the code and perfect and easy explanations.
    As I see this was the problem to couple of other people. It would be great if you help us to use this code for multiple face detection.
    Regards

    ReplyDelete
    Replies
    1. error c:/PROGRA~1\MATLAB\R2013A\BIN\MEX.PL: Error:'HoG.cpp' not found. kindly help and reply asap.

      Delete
  34. Hello,Thank you for the tutorial! it helped a lot
    There is one small problem which is the compilemex always failed even I changed according to your way. Cant figure out the problem.

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. i am getting error in line 206 . error is in mex function. please reply asap.

    ReplyDelete
  37. i am getting this error " c:/PROGRA~1\MATLAB\R2013A\BIN\MEX.PL: Error:'HoG.cpp' not found. kindly help and reply asap.

    ReplyDelete
  38. This implementation seems to be Windows platform specific...If you could provide the one that works for Ubuntu..it would be great..Thank you.

    ReplyDelete
  39. Hi, Code is great but errors are coming in compiling step even i tried above mention method. Please help me out. Waiting of your replies

    ReplyDelete

  40. For those who have trouble compiling in C in Matlab
    -
    para los que tenga problema para compilar en C en Matlab

    Windows 10

    - Desintalar los Mocrosos Visual c++ https://www.youtube.com/watch?v=4ZGJp9swZOk

    -Uninstall all Microsoft Visual c++ redistributable https://www.youtube.com/watch?v=4ZGJp9swZOk



    - para instalar el visual
    -install sdk 7.1 .net framework 4
    https://www.mathworks.com/matlabcentral/answers/233850-how-can-i-install-sdk-7-1-on-windows-10
    ______________________________________________-


    In my experience with SDK 7.1 and installing the required C compiler for Matlab on Windows 10, you can install SDK 7.1 from http://www.microsoft.com/en-us/download/details.aspx?id=8279

    However, it fails to detect .NET framework 4. As a result you cannot install the required C++ compilers. You can download these manually at the following link:

    -install c++ compiler
    http://www.microsoft.com/en-us/download/details.aspx?id=4422

    Now Matlab was able to set SDK 7.1 as C compiler. Hope it works for you as well.


    when you run the HoG.cpp file you get this: /sale un error falta:


    C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\intrin.h(26) : fatal error C1083: Cannot open include file:
    'ammintrin.h': No such file or directory

    soluciĆ³n/ solution

    https://www.mathworks.com/matlabcentral/answers/90383-fix-problem-when-mex-cpp-file

    ReplyDelete
  41. I have been very infomed on SVM Tutorial, HOG based Face Detection using SVM-Light in Matlab, a topic that i had no idea that i wold find. This is a very nice and interesting post, a page that i would really like to revisit. It may be very challenging when it comes to Translating a Novel Written in Kiswahili into English, but if you find yourself in such a situation always be sure that we have a reliable helper who is very ready to assist.

    ReplyDelete
  42. Can you give its source code
    rit2015012@iiita.ac.in

    ReplyDelete
  43. greetings mr ali,
    i have tried your code and when i run the demo.m file it only prints test images without detecting the faces.
    can you help me to fix this issue

    ReplyDelete
  44. Matlab is the best technology at Learning New things. Appreciable blog on Matlab Course

    ReplyDelete
  45. I a using matlab 2017a but it is showing this error
    "Error using mex
    No supported compiler or SDK was found. You can install the freely available MinGW-w64 C/C++ compiler; see Install
    MinGW-w64 Compiler. For more options, visit http://www.mathworks.com/support/compilers/R2017a/."

    ReplyDelete
  46. Thanks for the information.It is really nice .In this age of Technology advancement, computer and information technology have not only brought convenience to citizens in modern life but also for policemen & various Government officials of the nation to fight cybercrime through various modus operandi. Indian Cyber Army has been dedicated in fighting cyber crime, striving to maintain law and order in cyberspace so as to ensure that everyone remains digitally safe.Read more:- Information Security

    ReplyDelete
  47. Compiling mexsvmlearn
    Building with 'Microsoft Visual C++ 2017 (C)'.
    compile failed

    can you please help im using 2017b matlab and visual as seen

    ReplyDelete