Friday, July 27, 2012

FACE DETECTION USING MATLAB


Image Showing Labelled Faces
Face Detection:


In this tutorial, I present a face recognition system that attempts to recognize faces using the Skin Segmentation Technique. This tutorial is intended to provide an insight into developing a face recognition system using Skin Detection and hopefully gives a good starting point for those who are interested in developing a face recognition system.


There are other methods of face detection in an image, but i structured my own format and it works very well.


My Method:


1. Histogram Equalization
2. Skin Detection and Segmentation
3. Filling The Holes
4. Eliminating Pixels Below a Threshold
5. Putting Bounding Boxes Around Detected Faces And Counting

Step 1:


Brightness Preserving Dynamic Histogram Equalization:


Code:

close all;
clear all;
clc;
rgbInputImage = imread('Your File Here');
%rgbInputImage=getsnapshot(rgbInputImage);
labInputImage = applycform(rgbInputImage,makecform('srgb2lab'));
Lbpdfhe = fcnBPDFHE(labInputImage(:,:,1));
labOutputImage = cat(3,Lbpdfhe,labInputImage(:,:,2),labInputImage(:,:,3));
rgbOutputImage = applycform(labOutputImage,makecform('lab2srgb'));
figure, imshow(rgbInputImage);
figure, imshow(rgbOutputImage);
img=rgbOutputImage;
final_image = zeros(size(img,1), size(img,2));

This routine calls a function fcnBPDHE.(Function Brightness Preserving Dynamic Histogram Equalization.)

You Need To Have The Function saved in your MATLAB directory.


An Image Before Histogram Equalization:


Original Input Image

An Image After Histogram Equalization:



Notice The Increase In Brightness


Step 2:

Detect Skin Regions:

The next step is to detect the skin regions in an image. Photos in which people are fully covered give the best results as the complexity of the code reduces and complex procedures such as neural networks or template matching are not required. But this code does a good job of identifying faces even with some skin shown in the image. 


Code For Skin Detection & Segmentation:

if(size(img, 3) > 1)
for i = 1:size(img,1)
for j = 1:size(img,2)
R = img(i,j,1);
G = img(i,j,2);
B = img(i,j,3);
if(R > 92 && G > 40 && B > 20)
v = [R,G,B];
if((max(v) - min(v)) > 15)
if(abs(R-G) > 15 && R > G && R > B)
%it is a skin
final_image(i,j) = 1;
end
end
end
end
end

Image After Skin Detection And Segmentation:

Some Parts Are Falsely Detected



Step 3:

Fill In The Holes:

So far so good. The idea is to let MATLAB identify white blobs in an image but because of certain broken blobs they are identified as separate blobs and this makes it difficult to detect faces with accuracy. In the above picture, the chinese women's face has a big black cut running between the two eyes. and the same with the chinese man.

What we would do is we would fill the gaps with white spaces so as to make it a solid white blob.
MATLAB has an inbuilt function for the same known as 'imfill'. Type imfill in MATLAB help to find out more about the function.

Before performing 'imfill' we need to convert our grayscale image into a binary image.

'BW=im2bw(I,level);' converts the grayscale image I to a binary image. The output image BW replaces all pixels in the input image with luminance greater than level with the value 1 (white) and replaces all other pixels with the value 0 (black). You specify level in the range [0,1], regardless of the class of the input image. The function 'greythresh' can be used to compute the level argument automatically. If you do not specify levelim2bw uses the value 0.5.

%Grayscale To Binary.
binaryImage=im2bw(final_image,0.6);
figure, imshow(binaryImage);

%Filling The Holes.
binaryImage = imfill(binaryImage, 'holes');
figure, imshow(binaryImage);


Image After Performing 'imfill' function:

The Face Now Looks Like A Big White Blob

Step 4:

Putting Bounding Boxes Around Detected Blobs and Counting Them

Well in this routine we eliminate those white pixels that fall under a threshold.
For eg: if the face pixel density is lets say 2000 then anything below that is not a face. And such pixels would be discarded and a new binary image would be present with the remaining face pixels.

The Basic Steps Are As Follows:

1. Determine the Connected Components.
2. Computer the Area of Each Component.
3. Remove Small Objects.

Checkout MATLAB Help For More information on these functions...Click On Read More To See The Complete Post.


FINAL IMAGE WITH BOUNDING BOXES AROUND DETECTED FACES:
Original Image With Bounding Boxes Around Faces
Code:

binaryImage = bwareaopen(binaryImage,1890);   
figure,imshow(binaryImage);
labeledImage = bwlabel(binaryImage, 8);
blobMeasurements = regionprops(labeledImage, final_image, 'all');
numberOfPeople = size(blobMeasurements, 1)
imagesc(rgbInputImage); title('Outlines, from bwboundaries()'); 
%axis square;
hold on;
boundaries = bwboundaries(binaryImage);
for k = 1 : numberOfPeople
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), 'g', 'LineWidth', 2);
end
% hold off;


imagesc(rgbInputImage);
hold on;
title('Original with bounding boxes');
%fprintf(1,'Blob # x1 x2 y1 y2\n');
for k = 1 : numberOfPeople % Loop through all blobs.
% Find the mean of each blob. (R2008a has a better way where you can pass the original image
% directly into regionprops. The way below works for all versionsincluding earlier versions.)
thisBlobsBox = blobMeasurements(k).BoundingBox; % Get list of pixels in current blob.
x1 = thisBlobsBox(1);
y1 = thisBlobsBox(2);
x2 = x1 + thisBlobsBox(3);
y2 = y1 + thisBlobsBox(4);


   % fprintf(1,'#%d %.1f %.1f %.1f %.1f\n', k, x1, x2, y1, y2);
x = [x1 x2 x2 x1 x1];
y = [y1 y1 y2 y2 y1];
%subplot(3,4,2);
plot(x, y, 'LineWidth', 2);
end


%figure, imshow(labeledImage);
%B = bwboundaries(binaryImage);
%imshow(B);
%text(10,10,strcat('\color{green}Objects Found:',num2str(length(B))))
%hold on
%for k = 1:length(B)
%boundary = B{k};
%plot(boundary(:,2), boundary(:,1), 'g', 'LineWidth', 0.2)
%end
end


Checkout Some More Test:

This Photo Is Used To Judge The Face Detect Algorithms

Particularly In this photo the short Asian girl's neck is exposed to the camera and it appears as if her face and neck and lower part of chest is connected as is a face in whole but that appeared to MATLAB as if there were two faces.. Adding two more functions to the code solved it.

Here is a photo of Aishwarya Rai Bachhan With Bounding Box Around Her Face

Notice How Face is Detected In spite of Skin Exposure


89 comments:

  1. Where do I get the function fcnBPDHE.(Function Brightness Preserving Dynamic Histogram Equalization.)?

    ReplyDelete
    Replies
    1. You will find the function on this link.

      http://www.mathworks.co.uk/matlabcentral/fileexchange/34172-brightness-preserving-dynamic-fuzzy-histogram-equalization/content/fcnBPDFHE.m

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

    ReplyDelete
  3. This code is amazing! It works flawlessly!:) Thank you so much! :)

    ReplyDelete
    Replies
    1. pls send me the code which u have executed to my mail id punithpes@gmail.com
      pls

      Delete
    2. hello my self punith kumar M B presently i am working on the human face detection but i am getting the output for the image which contain only single face bes of that i am not able to continue continue my work so pls mail me the code which u have executed and tel me the procedure to execute it pls my mail id is punithpes@gmail.com

      Delete
    3. Hi every one can any one pls send me the code u ececuted to me on my ID its onesh.agrawal.1991@gmail.com



      Delete
    4. hey pls send me the file that u executed to my mail id. m getting errors of misplaced ) ;..... so pls it would be helpful if u send me the file.
      mail id is : tejabhai2@gmail.com
      thanks in advance

      Delete
    5. hi mam please help me how to execute it.please send the hints of executing the code to my mail id kaminepallinaveen@gmail.com thank you

      Delete
    6. hey, I am struggling on trying the codes that you post, may I get the code you did? Can you send to evelynchook@gmail.com. Thanks a lot :)

      Delete
    7. can u mail me the working code plzzz its urgent.its my email id pawan_1111@ymail.com

      Delete
    8. As everyone i woul like to see the code oyu executed plz... my e-mail is yayahuita@gmail.com Thanks so much

      Delete
  4. how can the face blob be differentiated from the other skin area??? which are two functions dat ur'll used??

    ReplyDelete
  5. hey.. thank u for such a simplified code... but i just tried it in matlab 7.10 and it shows error in "if(size(img, 3) > 1)" this part of skin detection and segmentaltion. can you plz suggest an alternative for this expression

    ReplyDelete
    Replies
    1. Can you please specify the error??

      Delete
    2. if(size(img, 3) > 1)
      |
      Error: Unbalanced or unexpected parenthesis or bracket.

      I AM getting this error so pls tel me how to debug it my mail id is punithpes@gmail.com

      Delete
    3. yes the error specified by punit.. it is solved..
      can you plz tell those two functions to be added to make code efficient (so that it differentiates between the face and other body parts ). This code only works for the images with people wearing dark clothes and fully covered skin... or atleast plz tell what algorithm should i apply. if you have the efficient code you can send me on my email- electronicstelecom999@gmail.com

      Delete
  6. my self punith i am finding problem in executing this code so pls can anyone will help me to get the ways how to execute

    Where do I get the function fcnBPDHE.(Function Brightness Preserving Dynamic Histogram Equalization.)?

    ReplyDelete
  7. i am getting
    Error using ==> nargin
    Not a valid M-file.
    while executing function fcnBPDHE so pls help me how to solve it

    ReplyDelete
    Replies
    1. I have mailed you the code already

      Delete
    2. can u please mail me the code..ggosh405@gmail.com pls i need ds badly

      Delete
    3. pls any one send me the code and procedure of executing of it pls its needed urgent to my mail id punithpes@gmail.com

      Delete
    4. hey plz send me code which is runing properly.. at rohit_kmr109@yahoo.in

      Delete
    5. plz send me your code to email: duongLhbk@gmail.com
      Thank you very much!

      Delete
    6. Hi, if possible i would like to check out de code too... matheuzss@hotmail.com
      Thank you

      Delete
    7. Please Mail Me Now this final Code that u executed.
      pcdhaka@gmail.com is my mail address

      Delete
  8. my self punith i am finding problem in executing this code so pls can anyone will help me to get the ways how to execute

    Where do I get the function fcnBPDHE.(Function Brightness Preserving Dynamic Histogram Equalization.)?

    ReplyDelete
  9. Can you send me the code for this program.... I am getting error while executing the above...

    ReplyDelete
    Replies
    1. please send this from very begining to toatal step to my mail
      soumyaranjan6193@gmail.com
      thanks

      Delete
  10. i'm getting error in Skin Detection & Segmentation

    if(size(img, 3) & gt; 1)
    |
    Error: Unbalanced or unexpected parenthesis or bracket.

    how to resolve this??

    ReplyDelete
    Replies
    1. use it in this way >> if(size(img, 3)> 1 )

      Delete
    2. I am new to matlab and getting many problems and errors while executing this program. Can you please send me the code to iabhinav72@gmail.com

      Delete
  11. The code executed pretty well without any error but something is wrong as it detects my clothes and my neck too. Plus it gets affected by light.

    ReplyDelete
    Replies
    1. pls send me the code what u have executed to my mail id punithpes@gmail.com i am facing so much of problem in ececuting it pls

      Delete
  12. Hello !! Can you please tell me what are the other two functions that I need to add to get only the face ?

    ReplyDelete
  13. this code will not work for all the images if any body will not agreefor this send me u r code i will check it out with my images or else i will send the images u just work it out on it

    ReplyDelete
    Replies
    1. Send me the images. Also, please note that i used this code to automatically detect face region and extract the face out for face recognition for "office going people" and for detecting area of skin exposure for curbing "pornography". In case of office-goers, who normally wear a formal outfit, only some part of the neck or other skin region other than the face is exposed to the camera, regions like hands and some part of the neck have already been eliminated in the code above. Also, without adding the "TWO FUNCTIONS" you wouldn't be able to eliminate too much skin exposure from the image. These "TWO FUNCTIONS" are not available within matlab, they are developed by some members who have filed for patent so i cannot disclose how its been used..I guess its up to the readers to figure out to make their own version of the code and modify it to suit their needs.

      Delete
    2. give me u r mail id i will send the images

      Delete
  14. I will be updating the blog very soon regarding how to recognize a person in the image using only the face with automatic face detection and PCA based face recognition .Also, on how to censor images on web with adult content or nudity automatically using MATLAB.

    ReplyDelete
    Replies
    1. can u please send me the code on dhaparis13@gmail.com i try to excute above code and i am getting too many errors even function not working properly

      Delete
    2. hey Mustafa.. can u pls send me the code that u executed... i m facing difficulties in running this code...
      anshul0390@yahoo.in
      abhi92g@gmail.com

      thanxxx

      Delete
    3. can u plz mail me working code ani07tha@gmail.com

      Delete
  15. I m getting error in function(fcnBPDFHE)....
    ??? Undefined command/function 'iptcheckinput'.

    Error in ==> fcnBPDFHE at 100
    iptcheckinput(inputImage,{'uint8','uint16','int16','single','double'}, {'nonsparse','2d'}, mfilename,'I',1);

    ReplyDelete
  16. can you plz help me to resolve this error...or mail me ur error free code on this id...plzz reply itz vry urgent ...
    sweetvandana.28@gmail.com or kaveri.naughty@gmail.com
    thanx in advance.. :)
    ??? Error using ==> regionprops>ParseInputs
    This measurement is not a string: "0"..This measurement is not a string: "0".
    Error in ==> regionprops at 109
    [L, requestedStats] = ParseInputs(officialStats, varargin{:});

    Error in ==> histogramDemo at 90
    blobMeasurements = regionprops(labeledImage, final_image, 'all');

    ReplyDelete
  17. Hey !! This seems really nice. But i get error while executing it . Can you please send me the error free code to this mail mirapadmapriya@gmail.com It will be very helpful for me to learn. Thanks in advance

    ReplyDelete
  18. would you please send me the MATLAB code for face detection using multi scale local image structure.

    ReplyDelete
  19. can u plz send me d code on my email id
    i.e kanwalkhan.pk786@gmail.com

    ReplyDelete
  20. Can u plz send me the code on my email id : lotlikar.sahil@gmail.com
    since i am getting many errors while executing the code.
    thank you

    ReplyDelete
  21. Can u pls mail me the code to barathvee@gmail.com ?
    Thank You

    ReplyDelete
  22. can any 1 pls mail me the code on omesh.agrawal.1991@gmail.com

    ReplyDelete
  23. plz send the code at ovi.jkt@gmail.com.....i need this code badly:(

    ReplyDelete
  24. please send the executable code and the decumentation to my mail and my mail id is kaminepallinaveen@gmail.com thank you

    ReplyDelete
  25. please send the code at mevlutkorukmez@gmail.com i need this code thank you

    ReplyDelete
  26. sorry sir the error at
    Lbpdfhe = fcnBPDFHE(labInputImage(:,:,1)); is making me mad please help me how to rectify that sir thank you sir

    ReplyDelete
  27. Hello,
    I try this code and its working perfectly...
    but i have a doubt and is just for better understanding..
    how do you obtain the calculation below??
    if there any references please help me know,,
    if(R > 92 && G > 40 && B > 20)
    v = [R,G,B];
    if((max(v) - min(v)) > 15)
    if(abs(R-G) > 15 && R > G && R > B)
    another question is why i cannot get the same bounding box like yours??
    even i follow each code but i still could not
    get the picture with bounding box surround face..
    this is my email address shukri.hassan87@gmail.com
    looking forward for your reply..

    ReplyDelete
    Replies
    1. can u pls send me the code that u executed
      my email id is anshul0390@yahoo.in
      thanx

      Delete
  28. cn u plz mail me the working code.my mail id pawan_1111@ymail.com

    ReplyDelete
  29. if(size(img, 3) > 1)
    i gotta a problem in d above line(step 2) saying
    "Error: Unbalanced or unexpected parenthesis or bracket."

    how to rectify it?

    ReplyDelete
    Replies
    1. i have this problem too, if you find out let me know bro ;)
      thanks in advanced
      meysamrasouli67@gmail.com

      Delete
  30. Hi,
    May some one provide me the working code for face detection using matlab. I need this for my major project. Please mail me the code or project on aman_5286@yahoo.co.in

    ReplyDelete
  31. hey can u send me the code at abhishek.v91@gmail.com

    ReplyDelete
  32. sir ,
    I try this code and its working perfectly...
    but i have a doubt and is just for better understanding..
    how do you obtain the calculation below??
    %imshow(B);

    ReplyDelete
    Replies
    1. can u plz mail me working code ani07tha@gmail.com

      Delete
    2. Could you please send me the code?
      Thanks.
      carrieta13@hotmail.com

      Delete
  33. Can u please mail me the code. Robobrob@gmail.com

    ReplyDelete
  34. can u plz mail me working code ani07tha@gmail.com

    ReplyDelete
  35. im working on face detection project... but its works only for single image..
    can u plz send me the working code ani07tha@gmail.com

    ReplyDelete
  36. hey can any1 plzz provide me the working code... m getting lots of errors.. ma id- snehal.gupta@rocketmail.com

    ReplyDelete
  37. Hey! please help me. I am getting trouble wid th cde. can anybody send me complete wrking code at magrawal6055@gmail.com

    ReplyDelete
  38. Hello Dear, Please send me complete MATLAB.m code in a single file.thanks
    engr.adeelkamran@yahoo.com

    I am very thankful to you.

    ReplyDelete
  39. hello dear send me matlab m file code please plzzzz
    nn_0819@yahoo.com please

    ReplyDelete
  40. pls any one send me the code and procedure of executing of it pls its needed urgent to my mail id dhim.imen@gmail.com

    ReplyDelete
  41. could you possibly send me the code, i really need it, meysamrasouli67@gmail.com
    thanks in advanced :)

    ReplyDelete
  42. sir, could you please mail the working code @chikkalingaiah.shwe@gmail.com..thanks in advance

    ReplyDelete
  43. sir please mail me final working code at ravikumar.1532@gmail.com Thanx in advance.

    ReplyDelete
  44. when apply step2(Detect Skin Regions) I getting this error
    ??? if(size(img, 3) >1)
    |
    Error: Unbalanced or unexpected parenthesis or bracket.

    can you correct to me this is my email(engineer.soft8@gmail.com)
    thanks alot

    ReplyDelete
  45. Can u please mail me the code i try it but i have some errors too well u mail me the correct code thanks. bbs.khll@gmail.com

    ReplyDelete
  46. pleas can any one send the code for me final working code ...thanks
    my mail bbs.khll@gmail.com

    ReplyDelete
  47. can anyone send me the working code and explain that how can i run that program thanks so much my email : jackbecham@gmail.com

    ReplyDelete
  48. please send it to me too , thank you very much for your great work
    My mail : nasibah.k@gmail.com

    ReplyDelete
  49. I am doing step 5 but I could not run it.What does 'binaryImage' and 'labelledImage'?

    ReplyDelete
  50. hi, this is awesome... how can i modify this code so that instead of detecting face it detects dress ( T shirt or Shirt) in an image...
    Please help me out

    ReplyDelete
  51. hello dear can send me matlab m file code please please~
    pets_suying@hotmail.com

    ReplyDelete
  52. This is great! Can you send me the .m code?
    adenes.eletronica@gmail.com
    Thanks!

    ReplyDelete
  53. could u mail me the .m file of this code ? vikasparihar1990@gmail.com

    ReplyDelete
  54. I am doing step 2 but I could not run it. Error - ??? if(size(img, 3) > 1)
    |
    Error: Unbalanced or unexpected parenthesis or bracket.
    Error is occurring.

    ReplyDelete
  55. Please Send me the final code in my mail address. Please
    pcdhaka@gmail.com

    ReplyDelete
  56. The support is made simpler by Gmail. Gmail is an ideal assistance to the educators also Using Gmail’s

    ReplyDelete
  57. Wonderful illustrated information. I thank you about that. No doubt it will be very useful for my future projects. Would like to see some other posts on the same subject! Concrete balcony crack repair

    ReplyDelete