BackendGuy
backend developer

[Machine learning] Face detection in PHP

Wow, i can’t just laugh enough, sincerely speaking, when i wrote the title of this post, it sparked off laughter within me because as you know machine learning is best done with python, so why PHP? over the years many people have under estimated the fact that php could be used for core projects relating to Ai and machine learning, but top PHP enthusiasts have come up with core researches that software engineers like me want to tap into.

Sincerely speaking, this post is for Mid-level and senior PHP developers who have an interest in machine learning, incase you experience difficulties feel free to comment.

So PHP which is a wide language for backend developers can be applied to machine learning, and also has a wide library of Ai modules, at least the little i know talking about the PHPML framework, and google ai and machine learning libraries which can be used.

So back to our main topic, we want to implement a face detection technique using PHP, and to do this i will be using the google cloud vision api to detect faces in an image.

Steps and requirements

Create the service object

To access Google APIs using the official client SDKs, you create a service object based on the API’s discovery document, which describes the API to the SDK. You’ll need to fetch it from the Vision API’s discovery service, using your credentials:

create a file facedetection.php

use Google\Cloud\Vision\V1\ImageAnnotatorClient;
$imageAnnotator = new ImageAnnotatorClient();

Send a face detection request

To construct a request to the Vision API, first consult the API documentation. In this case, you’ll be asking the images resource to annotate your image. A request to this API takes the form of an object with a requests list. Each item in this list contains two bits of information:

  • The base64-encoded image data
  • A list of features you’d like annotated about that image.

For this example, you’ll simply request FACE_DETECTION annotation on one image, and return the relevant portion of the response:

# annotate the image
// $path = 'path/to/your/image.jpg'
$image = file_get_contents($path);
$response = $imageAnnotator->faceDetection($image);
$faces = $response->getFaceAnnotations();

Process the response

Congratulations – you’ve detected the faces in your image! The response to our face annotation request includes a bunch of metadata about the detected faces, which include coordinates of a polygon encompassing the face. At this point, though, this is only a list of numbers. Let’s use them to confirm that you have, in fact, found the faces in your image. We’ll draw polygons onto a copy of the image, using the coordinates returned by the Vision API:

# draw box around faces
if ($faces && $outFile) {
    $imageCreateFunc = [
        'png' => 'imagecreatefrompng',
        'gd' => 'imagecreatefromgd',
        'gif' => 'imagecreatefromgif',
        'jpg' => 'imagecreatefromjpeg',
        'jpeg' => 'imagecreatefromjpeg',
    ];
    $imageWriteFunc = [
        'png' => 'imagepng',
        'gd' => 'imagegd',
        'gif' => 'imagegif',
        'jpg' => 'imagejpeg',
        'jpeg' => 'imagejpeg',
    ];

    copy($path, $outFile);
    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    if (!array_key_exists($ext, $imageCreateFunc)) {
        throw new \Exception('Unsupported image extension');
    }
    $outputImage = call_user_func($imageCreateFunc[$ext], $outFile);

    foreach ($faces as $face) {
        $vertices = $face->getBoundingPoly()->getVertices();
        if ($vertices) {
            $x1 = $vertices[0]->getX();
            $y1 = $vertices[0]->getY();
            $x2 = $vertices[2]->getX();
            $y2 = $vertices[2]->getY();
            imagerectangle($outputImage, $x1, $y1, $x2, $y2, 0x00ff00);
        }
    }

Put it all together

call_user_func($imageWriteFunc[$ext], $outputImage, $outFile);
printf('Output image written to %s' . PHP_EOL, $outFile);

To run the sample, run the following command from the sample code directory:

NB: Sincerely speaking, this post is for Mid-level and senior PHP developers who have an interest in machine learning, incase you experience difficulties feel free to comment.

composer install
php vision.php face images/face.png output-image.png  

BackendGuy

2 comments

Your Header Sidebar area is currently empty. Hurry up and add some widgets.