It seems that the trend right now within image hosting sites (be it social networks like facebook & orkut or specialized sites like picporta), is the ability to detect faces within user uploaded images. While it once may have required a great deal of skill and understanding of image processing techniques, that is no longer the case. In this tutorial, I’ll show you how to easily detect faces within your PHP apps in just 5 steps.
Face Detection in a PHP app
Face Detection
Face detection is the ability to detect a presence of faces within an image. It is very different from face recognition where the focus is matching faces to a known database of faces. Face detection works best when the face is a frontal shot. However there are advanced algorithms which make detection in side shots also possible.
The Solution: We will write a php script, which will detect faces automatically, using OpenCV (a computer vision library) and PHP Facedetect(a php wrapper to opencv). Both are free to download and opensource.
Requirements
- Basic PHP scripting skills
- Linux server running Centos with SSH access
- PHP/Apache
- GD Library
Lets, Get Started..
Step 1: Install OpenCV and its dependencies
yum install opencvOpenCV needs the following dependencies to work properly:
yum install ibpng libpng-dev zlib libjpeg libjpeg-dev libtiff libjasper swig python pkgconfig gtk gtk-devSee here for troubleshooting and advanced installation instructions.
Step 2: Compile & Test Run OpenCV
OpenCV is installed in /usr/local/share/opencv
In the /usr/local/share/opencv/samples/c/ folder, Run the following commands:
1 2 | export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig ./build_all.sh |
Test run OpenCV
./facedetect --cascade="../haarcascades/haarcascade_frontalface_alt.xml" test.jpg
If all is fine, you should see the processing time. If you see errors, then see here
Step 3: Download and Install PHPFacedetect
1 2 3 4 | wget http://www.xarg.org/download/facedetect-1.0.0.tar.gz tar zxf facedetect-1.0.0 yum install php5-devel phpize && configure && make && make install |
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.
Step 4: Writing a PHP Script
Copy all xml files in /usr/local/share/opencv/haarcascades folder to the web folder.
Call the php code as shown below, and 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, you can draw a square or a circle using php gd library.
1 2 3 4 5 6 7 8 | <?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); ?> |



