With the rapid development of artificial intelligence, face recognition technology has been widely used in areas such as security monitoring, identity verification, and smart access control. Baidu provides a powerful face recognition API that supports face detection, face comparison, and face search. This tutorial demonstrates how to use PHP to connect to Baidu’s Face Recognition API and implement basic face detection functionality.
Before writing the code, you need to complete the following steps:
The following PHP example demonstrates how to call Baidu’s Face Recognition API to detect the number of faces in an image.
Create a file named face_detection.php and define a request function:
<?php
function request($url, $data){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
?>Next, write a detection function to call Baidu’s face detection API:
<?php
function detect(){
$url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect';
$data = array(
'api_key' => 'your_api_key',
'api_secret' => 'your_api_secret',
'image' => 'your_image',
'image_type' => 'URL',
'max_face_num' => 1
);
$response = request($url, $data);
return $response;
}
?>Finally, call the detection function and output the result:
<?php
require_once 'face_detection.php';
$response = detect();
$result = json_decode($response, true);
if($result['error_code'] == 0){
$face_num = $result['result']['face_num'];
echo "Detected {$face_num} face(s)";
} else {
echo "Face detection failed: {$result['error_msg']}";
}
?>In this example, replace your_api_key, your_api_secret, and your_image with your actual application credentials and image URL. The image can be provided as a web URL or Base64-encoded data.
With the example above, you can see how to integrate Baidu’s Face Recognition API using PHP to implement face detection. The same principle applies to other features such as face comparison, search, and registration. Baidu’s API provides rich functionality and supports multiple programming languages, making it easy for developers to build AI-driven applications that enhance user experience and system intelligence.