Face detection in images using PHP

In a previous post we saw how to detect human faces in images using JavaScript. In the current post we will look into a PHP port of a JavaScript face detection algorithm without using openCV. Since the code is completed written in PHP it cannot attain the raw speed that C,C++ provides, but for many trivial application a PHP version can do.

Installing

Before reading further you can download the code below. The original JavaScript port is located here, the following includes the complete code with a crop method added along with a few example files. As the code relies on the GD library, make sure that it is installed and activated on your system.

Download Source
Downloads : 18098 / File size : 499.3 kB

Running our sample code

The sample code to show the detected face is show below. Note that in images having multiple faces only the first one is detected. Although this might seem like a limitation, this can be useful in web applications that need to create a user profile picture from a raw image. So that if a user uploads a full length picture of him/her, the given code can detect the face and automatically create a profile picture for the user.

<?php
 
include "FaceDetector.php";
 
$face_detect = new Face_Detector('detection.dat');
$face_detect->face_detect('sample-image3.jpg');
$face_detect->toJpeg();
 
?>


Flickr :By modelxing

The above code displays a border around the detected face, instead we can directly crop the resulting face area and output the resulting image.

<?php
 
include "FaceDetector.php";
 
$face_detect = new Face_Detector('detection.dat');
$face_detect->face_detect('sample-image3.jpg');
$face_detect->cropFace();
 
?>

Face coordinates

If you need the coordinates of the detected face for further processing, you can use the following.

// Return coordinates in JSON
// {'x':56.375, 'y':45.1, 'w':227.55}
$face_detect->toJson();
 
// OR
 
// Return coordinates as an Array
$face_detect->getFace();

Extending the class

You can extend the Face_Detector class using your own methods. For example I’ve added three methods – Rotate(), resizeFace() and toGrayScale() to the class, which lets you modify the final face area further.

<?php
 
include "FaceDetector.php";
 
/* We now extend the above class so we can add our own methods */
class FaceModify extends Face_Detector {
 
  public function Rotate() {
    $canvas = imagecreatetruecolor($this->face['w'], $this->face['w']);
    imagecopy($canvas, $this->canvas, 0, 0, $this->face['x'], 
              $this->face['x'], $this->face['w'], $this->face['w']);
    $canvas = imagerotate($canvas, 180, 0);
    $this->_outImage($canvas);
  }
 
  public function toGrayScale() {
    $canvas = imagecreatetruecolor($this->face['w'], $this->face['w']);
    imagecopy($canvas, $this->canvas, 0, 0, $this->face['x'], 
              $this->face['x'], $this->face['w'], $this->face['w']);
    imagefilter ($canvas, IMG_FILTER_GRAYSCALE);
    $this->_outImage($canvas);
  }
 
  public function resizeFace($width, $height) {
    $canvas = imagecreatetruecolor($width, $width);
    imagecopyresized($canvas, $this->canvas, 0, 0, $this->face['x'], 
                     $this->face['y'], $width, $height, 
                     $this->face['w'], $this->face['w']);
    $this->_outImage($canvas);
  }
 
  private function _outImage($canvas) {
    header('Content-type: image/jpeg');
    imagejpeg($canvas);
  }
}
 
 
/* Using the extended class */
$face_detect = new FaceModify('detection.dat');
$face_detect->face_detect('sample-image3.jpg');
$face_detect->resizeFace(100,100);
 
?>

NB: If for some reason the code returns a error, turn off error reporting in php.ini

Further Links

1. Automatic Face Detection in Photos with PHP
2. http://www.facedetection.com/

20 Responses

  1. Juan C. Monestel says:

    Great article… better if was multiple detection hehe

  2. m a r c o says:

    Hi,
    Nice idea, but it doesn’t seem to find any face on the image from your previous javascript demo :-/ …any idea?
    I modified your code to get multiple faces, and it gives very uncertain results…
    Regards,
    m a r c o

  3. Fred says:

    Hello, thank you for this tutorial. We successfully added this code in our application for android to handle remote images. Can you update this code to get multiple faces detection? Please.
    Best regards

  4. Mostafa says:

    Hi,
    it’s very googd script. but…

    how i can save the face witch detect?

  5. Stef157 says:

    Do it like this :

    public function cropFace($path) {
    $canvas = imagecreatetruecolor($this->face[‘w’], $this->face[‘w’]);
    imagecopy($canvas, $this->canvas, 0, 0, $this->face[‘x’], $this->face[‘x’], $this->face[‘w’], $this->face[‘w’]);
    //header(‘Content-type: image/jpeg’);
    imagejpeg($canvas, $path);
    }

  6. Closca says:

    HI, i am using this to know how to resize and image and don;t lose the face, but if the face is undetectable stays alot of time to analyze, over 30 seconds for one image,
    how could it make it faster, or somehow to decide faster if the face exists?

  7. Sharavana Kumar says:

    It work for only some images correctly for the face detection.For some type image it didnt work well.Any size need to change in the “facedector.php”
    Please help to get the good result

  8. closa says:

    the code showing error like “http://localhost/sample/face-detect/example.php(because it contains error)”can you slove us

  9. Renan Fenrich says:

    Better quality could be obtained using imagecopyresampled() in resizeFace().

  10. Widyo Rio says:

    Great !! Next step could be detect gender from a photograph.

  11. Sandy Lee says:

    Great script. I am looking this kind script for multiple detection, do you know how to modify it for my need? Thanks!!

  12. Tuymurod says:

    error_reporting(0);
    include “FaceDetector.php”;
    $face_detect = new Face_Detector(‘detection.dat’);
    $face_detect->face_detect(‘sample-image3.jpg’);

    $face_detect->cropFace(‘new.jpg’);

    public function cropFace($path) {
    $canvas = imagecreatetruecolor($this->face[‘w’], $this->face[‘w’]);
    imagecopy($canvas, $this->canvas, 0, 0, $this->face[‘x’], $this->face[‘x’], $this->face[‘w’], $this->face[‘w’]);
    //header(‘Content-type: image/jpeg’);
    imagejpeg($canvas, $path);
    }

    Dosn`t save. How can I save it?

  13. Surath Wije says:

    Need help to get this code working for a website on paid help basis. If somebody can help me to get this working to extend this code to cover other images type as well I am willing to pay a reasonable amount.

  14. surath wije says:

    Need help to get this code working for a website on paid help basis. If somebody can help me to get this working to extend this code to cover other images type (png etc) as well I am willing to pay a reasonable amount (up to $500/= ) . Please contact surathwije@yahoo.com

  15. Peter says:

    Hi
    Works wonderful for me.. the only thing I can’t get is how to get the result picture with the square and below that with the:
    $face_detect->getFace();
    or
    $face_detect->toJson();
    with the coordinates of the square?
    With other words: I can’t validate if picture has face..
    How to?

  1. July 8, 2011

    […] beruht (und daher ohne jegliche Hilfsbibliotheken wie OpenCV, etc. auskommt).Die Klasse von Sameer Borate bietet eine Reihe nützlicher Features wobei die gleiche Einschränkung wie schon damals gilt: die […]

  2. July 23, 2011

    […] Source :: Codediesel […]

  3. August 24, 2011

    […] Face detection in images using PHP. Wykrywanie twarzy w PHP. […]

  4. March 11, 2013

    […] képeket, vagy az arcot. A codediesel.com oldalon éppen egy ilyen cikkre akadtam (Face detection in images using PHP), amiben PHP használatával, JPG képből egy osztály és némi adat […]

  5. February 21, 2015