My blog has moved!

You will be automatically redirected to the new address. If that does not occur, visit
http://ashokbasnet.com.np
and update your bookmarks.

Monday, May 7, 2012

Detect face area using Matlab

Image processing can be used to process various objects in various ways and one for them is the face detection. The face detection system has got many applications and developing such a system is even easier by use of the Image Processing ToolBox available in MATLAB.

The detection of face involves various tasks. They can be summarized in three steps as:-

  1. reading of a RGB image
  2. minimisation of background portion
  3. detection of face object

Here is the code for the detection of the face area. Save it as filename.m file and execute the code in matlab.

%%%%% Reading of a RGB image
i=imread('imagepath');  % for eg. C:\P1140119.jpg
I=rgb2gray(i);
BW=im2bw(I);
figure,imshow(BW)
 
%%%%% minimisation of background portion
 
[n1 n2]=size(BW);
r=floor(n1/10);
c=floor(n2/10);
x1=1;x2=r;
s=r*c;
 
for i=1:10
    y1=1;y2=c;
    for j=1:10
        if (y2<=c | y2>=9*c) | (x1==1 | x2==r*10)
            loc=find(BW(x1:x2, y1:y2)==0);
            [o p]=size(loc);
            pr=o*100/s;
            if pr<=100
                BW(x1:x2, y1:y2)=0;
                r1=x1;r2=x2;s1=y1;s2=y2;
                pr1=0;
            end
            imshow(BW);
        end
            y1=y1+c;
            y2=y2+c;
    end
    
 x1=x1+r;
 x2=x2+r;
end
 figure,imshow(BW)
 
 %%%%% detection of face object
 
L = bwlabel(BW,8);
BB  = regionprops(L, 'BoundingBox');
BB1=struct2cell(BB);
BB2=cell2mat(BB1);
 
[s1 s2]=size(BB2);
mx=0;
for k=3:4:s2-1
    p=BB2(1,k)*BB2(1,k+1);
    if p>mx & (BB2(1,k)/BB2(1,k+1))<1.8
        mx=p;
        j=k;
    end
end
figure,imshow(I);
hold on;
rectangle('Position',[BB2(1,j-2),BB2(1,j-1),BB2(1,j),BB2(1,j+1)],'EdgeColor','r' )



 


The sample output for the image read from my computer is shown below:-


fig1


fig2


fig3


The final output is the one with detected area of the face.
The algorithm can be extended to detect even more precisely the area of the face.

5 comments :

  1. thanks ashok sir...
    i am doing my project face identification and verification using gabor.... can you tell me how to extract the face point (fudicial point)like nose,eye,mouth... and how to get that value as arithmatic value...please sir....my mail id is vickyneversayno@gmail.com

    ReplyDelete
  2. how to modify the same code for multiple faces

    ReplyDelete
  3. Hello, How to detect eyes nose and lips from detected face ??

    ReplyDelete
  4. I want to Detect ROI of face as well as eyes, nose and mouth . sent me to sameersoft6@gmail.com

    ReplyDelete