I have always wondered how to detect faces automatically with php script. I have seen in many photo sharing and social network sites automatically detect a face and tag a name after being uploaded.
In this article, i will explain how possible this task can be achieved with simplicity with OpenCV and PHP Facedetect extension. Both are free to download and opensource.
Goal
To auto detect faces in a photo and draw pink box around the faces with a php script running a linux centos server. Please note that face detection and face recognition are two different things. To recognize a face you have to first detect a face and then do the required processing.
Requirements
- Linux server running Centos with SSH access
- PHP/Apache
- GD Library
- OpenCV [Download]
- PHP Facedetect extension [Download]
PHP facedetect extension is very simple. All you have to do is call a function face_detect(p) and it will give all the x,y coordinates in a photo where we draw a square. face_count() will output how many total faces in the given photo. For documentation see here
Installation
We install opencv and then we compile the php facedetect extension with php.
How to Install OpenCV
If you are running centos then one single line will install opencv.
yum install opencv
OpenCV may also need the following depencies to work properly and you will need to install them as well.
yum install ibpng libpng-dev zlib libjpeg libjpeg-dev libtiff libjasper swig python pkgconfig gtk gtk-dev
For more installation instructions on linux see here
The opencv will be installed in/usr/local/share/opencv and all the important facedetection training files known as “haar training” can be found in haarcascades folder in xml format (like haarcascade_frontalface_alt.xml)
How to test run OpenCV
Inorder to test run opencv you have to compile the samples folder. Go to /usr/local/share/opencv/samples/c/
Run this command to compile to binary.
./build_all.sh
If you find large number of errors and variables not declared like shown below..
Package opencv was not found in the pkg-config search path.
Perhaps you should add the directory containing `opencv.pc’
to the PKG_CONFIG_PATH environment variable
No package ‘opencv’ found
….
run
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
./build_all.sh
and then it will compile.
To test run the opencv run the following command in the c folder for a test.jpg photo.
./facedetect –cascade=”../haarcascades/haarcascade_frontalface_alt.xml” test.jpg
Since your server does not have Xwindow installed, you probably do not see the output just the processing time.
If you see error “error while loading shared libraries: libcxcore.so.2: cannot open shared object file: No such file or directory” then see this solution
Install PHP Facedetect Extension
Installing the PHP facedetect extension is very easy. Just download the package and compile it for PHP.
wget [download_file_path]
tar zxf facedetect-1.0.0
then
phpize && configure && make && make install
If you see phpize command not found error, install php developer libraries
yum install php-devel
OR
yum install php5-devel
then
open php.ini and make sure you add this line.
extension=facedetect.so
If facedetect has been successful, you will see this enabled in test.php.
Thats it! all the installation part is over!
Writing a PHP Script
Before you start writing php script make sure you copy all xml files in /usr/local/share/opencv/haarcascades folder to the web folder.
and this simple two lines to from php to call the function
<?php
//face_count() outputs total faces detected
// face_detect() outputs assoc array of x,y,width,height of each face recognized
$total= face_count('test.jpg','haarcascade_frontalface_alt.xml');
$coord= face_detect('test.jpg','haarcascade_frontalface_alt.xml');
print_r($coord);
?>
Make sure the path of xml files are correct else you would see a blank face or bool(false) output. Once you get this co-ordinates all we have to do is use php gd library to draw square around the face with the above coordinates.
This script will do that and you have call the script with photo file like this http://domain/face.php?file=test.jpg and the test.jpg file should be in the same folder
<?php
//face.php -> detects faces and draws a pink square on faces
function LoadJpeg($imgname)
{
$im = @imagecreatefromjpeg($imgname); /* Attempt to open */
if (!$im) { /* See if it failed */
$im = imagecreate(150, 30); /* Create a blank image */
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
/* Output an errmsg */
imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
}
return $im;
}
$total= face_count($_GET['file'],'haarcascade_frontalface_alt.xml');
$ord= face_detect($_GET['file'],'haarcascade_frontalface_alt.xml');
$im = LoadJpeg($_GET['file']);
$pink = imagecolorallocate($im, 255, 105, 180);
if(count($ord) > 0) {
foreach ($ord as $arr) {
imagerectangle($im,$arr['x'] ,$arr['y'] , $arr['x']+$arr['w'],
$arr['y']+$arr['h'], $pink);
}
}
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
?>
Just remember haarcascade_frontalface_alt.xml are haar training files used for face detection. You can play around with other training files like to detect various body parts, not just faces.
haarcascade_frontalface_alt.xml
haarcascade_frontalface_alt_tree.xml
haarcascade_fullbody.xml
haarcascade_profileface.xml
haarcascade_lowerbody.xml
haarcascade_upperbody.xml
Conclusion and the Results

(standard test image used for image processing)
I have given multiple frontal detection photos to the script and the script performed well, despite few false face detections. One sample output file is shown below with the pink boxes detected by the script as faces. Unfortunately i can only show the blurred faces because of personal reasons.

I should say i am pretty surprised the way the multiple faces are detected and the results are good with haarcascade_frontalface_alt.xml as training file . To get more accurate results, you need to do haar training to xml files to produce more accurate results.
Other Useful Links
Facedetection with pure PHP without OpenCV [visit site]
Facedetection with javascript [visit site]
OpenCV Face Detection Page [visit site]
Enjoy!
Download up to date 650-177 questions and 650-251 answers for guarantee success in 650-393 exam.
Similar Posts:
- [Fix] Ziplib compile error with zziptest.c
- Easy Install FFmpeg in Linux
- How to unzip ZIP files with PHP
- Implementing Secure File Upload in PHP
- Uploading Files using Unzip in Linux
- how to change default homepage with htaccess?
- Implementing Secure File Upload in PHP
- Install ClamAV in Centos with Cpanel
- Facebook like button not working!
- Custom Layouts with CakePHP Framework





October 15, 2009
Well, it took me a little over an hour to get everything running on Debian but man, it’s incredible!
I tried the pure PHP technique (without OpenCV) first and it was very slow. Took between 4 and 30 seconds to find a face in an image. Then I came back to this page, installed OpenCV, facedetect, and the PHP wrapper and it found faces in those same images in .1 to .3 seconds. That’s 1/10th to 1/3 of a second!
GREAT tutorial! Thanks.
November 4, 2009
Hello,
I installed the facedetect module as described, but i mean that is not working. A symple phpinfo() doesn´t give me the facedetection details.
November 5, 2009
In the above lines for some of them the command
“phpize && configure && make && make install” will not work , then please try
“phpize && ./configure && make && make install”
December 5, 2009
You can create valid passport photos with http://idphoto4you.com website.
It uses face detection to set size and position of head.
It is free.
It knows numerous standards.
January 3, 2010
Thanks for the info, the one that does it without OpenCV was very useful(php one).
January 6, 2010
Perfectly work for me. great thanks. I’ll try to adapt your code to use it with rubyOnRails
February 17, 2010
Great Thanks
Miley
February 24, 2010
Great ! This is a good example for php face detection.
March 22, 2010
I was searching for this type of thing and i have arrived on this page..
Kindly tell me how wheni upload multiple photos,how i will use it with them..
Explain abit please.it s so urgent..
Thanks
May 20, 2010
Thanks for your blog.
But I had a problem that I got different results when I ran it on 2 different linux machine with the same picture.
Why??
June 2, 2010
Great, thanks for realease.
Miley.
August 26, 2010
Can i use it to black(babo) face?
October 30, 2010
Is this module working in windows or not ?
December 17, 2010
can you do any other recognition, like hand recognition or some car type recognition or something?
December 18, 2010
anything is possible with opencv. all you have to do is have the training data. consult youtube for more videos on opencv.
February 19, 2011
GREAT tutorial! Thanks.
Angel.
March 14, 2011
Great ! Very thanks.
Angel.
March 29, 2011
Its great resource. i was finding that type inf and now i get it.thanks for this.
May 8, 2011
Dear all,
was there a change in rpm package? I suspect ‘yum install opencv’ does not do expected thing. It does not install facedetect, in fact it does not install almost anything. Did anyone meet this behavior?
August 1, 2011
Great, thanks for realease.
Angel.
August 26, 2011
great, thanks for sharing.
December 30, 2011
Hey!
few days back i started a research on image detection,for building a web application in php,…after googled for an hour i landed on this page..i found this tutorial is super awesome….i had some queries that…..
/*************************************/
Requirements
- Linux server running Centos with SSH access
- PHP/Apache
- GD Library
- OpenCV [Download]
- PHP Facedetect extension [Download]”
/*************************************/
i have downloaded everything in list OpenCV in windows version….but instead of Linux server can i run the development process on windows platform…That is How to install OpenCV or Install PHP Facedetect Extension…plz help….
January 6, 2012
I am trying to use php-facedetect.
But when I run ./confugure I take:
checking for cvLoad in -lopencv_objdetect… no
configure: error: wrong OpenCV version or OpenCV not found
What is it? And how do I overcome this?
October 9, 2012
me too. any solution?
February 22, 2012
Installed on Centos 6. Works fine. thanks a lot!
February 25, 2012
WIll need to implement this on windows running PHP on IIS.
April 8, 2012
great tutorial !! great post…
May 19, 2012
Hello
I have tried with the example picture but picture is not displayed and I don’t find where it comes from.
It displays as if link to image was broken. Could you help?
October 11, 2012
That’s cool. I didn’t know you could do that with PHP. Thanks for sharing.
March 11, 2013
I was seeking this particular info for a long time. Thank you and best of luck.
March 28, 2013
I am working on a php based academic project where user (students) have to upload their photos (or you can say ID photo). Before saving the image into the database after uploading by user I want to validate whether a photo contains face or not ? How could I do this? How to restrict user from uploading an irrelevant photo say animals, bike ? Any help would be really grateful. Thanks in advance.
April 7, 2013
Sorry~ it`s too hard for me! Who can help me