How to detect faces in photo in PHP
2 min readAug 1, 2019
Wouldn’t it be nice if there was a simple way to automatically detect people’s faces in images? Well, here it is.
Step 1, add our image recognition API to your library.
"require": {
"cloudmersive/cloudmersive_imagerecognition_api_client": "^1.4",
}
Step 2, call faceLocate, like so:
<?php
require_once(__DIR__ . '/vendor/autoload.php');// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');$apiInstance = new Swagger\Client\Api\FaceApi(
new GuzzleHttp\Client(),
$config
);
$image_file = "/path/to/file"; // \SplFileObject | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.try {
$result = $apiInstance->faceLocate($image_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling FaceApi->faceLocate: ', $e->getMessage(), PHP_EOL;
}
?>
And that’s all you need to do! Here is an example of what the output data looks like, in this case with 8 faces in the image.
{
"ErrorDetails": null,
"Successful": true,
"Faces": [
{
"LeftX": 227,
"TopY": 181,
"RightX": 330,
"BottomY": 284
},
{
"LeftX": 344,
"TopY": 194,
"RightX": 493,
"BottomY": 344
},
{
"LeftX": 410,
"TopY": 6,
"RightX": 496,
"BottomY": 93
},
{
"LeftX": 77,
"TopY": 77,
"RightX": 181,
"BottomY": 181
},
{
"LeftX": 245,
"TopY": 45,
"RightX": 317,
"BottomY": 117
},
{
"LeftX": 325,
"TopY": 45,
"RightX": 397,
"BottomY": 117
},
{
"LeftX": 526,
"TopY": 135,
"RightX": 630,
"BottomY": 238
},
{
"LeftX": 160,
"TopY": 150,
"RightX": 246,
"BottomY": 237
}
],
"FaceCount": 8
}
As you can see, we are provided with the number of faces and the location of each. Our image recognition API includes other functions that allow you to count entire people in photos as well as provide facial feature locations, such as eyes and nose.