百度API使用php实现人脸识别

作者 : 慕源网 本文共7495个字,预计阅读时间需要19分钟 发布时间: 2021-09-20 共252人阅读

百度API使用php实现人脸识别

 

1.注册百度开发者账号。

 

https://login.bce.baidu.com/?account= 注册登录成功后,进入控制台,在左边的导航栏找到产品-》人工智能-》人脸识别:

百度API使用php实现人脸识别

  创建应用。创建应用成功后拿到应用的API Key和Secret Key

 

2.接口调用-获取access token

 

调用人脸识别接口前需要获取access token,示例代码:

 

function execCurl($url, $param) {

 

if (empty($url) || empty($param)) {

 

return array(‘result’ => false, ‘err_msg’ => ‘url or param is null’);

 

}

 

$curl = curl_init();//初始化curl

 

curl_setopt($curl, CURLOPT_URL, $url);//抓取指定网页

 

curl_setopt($curl, CURLOPT_HEADER, 0);//设置header

 

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上

 

curl_setopt($curl, CURLOPT_POST, 1);//post提交方式

 

curl_setopt($curl, CURLOPT_POSTFIELDS, $param);

 

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

 

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

 

$data = curl_exec($curl);//运行curl

 

$curl_err_msg = curl_error($curl);

 

curl_close($curl);

 

if($data === false) {

 

return array(‘result’ => false, ‘err_msg’ => $curl_err_msg);

 

}else {

 

return array(‘result’ => true, ‘data’ => $data);

 

}

 

}

 

$url = ‘https://aip.baidubce.com/oauth/2.0/token’;

 

$param = array(

 

‘grant_type’ => ‘client_credentials’,

 

‘client_id’ => ‘你的API Key’,

 

‘client_secret’ => ‘你的Secret Key’

 

);

 

$result = execCurl($url, $param);

 

3.调用人脸检查接口

 

如果需要判断一张图片中的人脸,是否符合后续识别或者对比的条件,在请求时在face_field参数中请求quality。

 

下面示例是请求图文为base64转码字符串(转码不能包含头信息),也可以传图片网络地址,官方文档:https://ai.baidu.com/docs#/Face-Detect-V3/top

 

示例代码:

 

function checkPictureToCheckFace($image_path, $access_token) {

 

$url = ‘https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=’ . $access_token;

 

$param = array(

 

‘image’ => base64EncodeImage($image_path),

 

‘image_type’ => ‘BASE64’,

 

‘face_field’ => ‘quality’

 

);

 

$param = json_encode($param);

 

$result = execCurl($url, $param);

 

if($result[‘result’] == false) return $result;

 

$data = json_decode($result[‘data’], true);

 

if($data[‘error_code’] != 0) return array(‘result’ => false, ‘err_msg’ => ‘上传的人脸不符合要求,请重新上传五官清晰的真实头像’);

 

$err_result = array(‘result’ => false, ‘err_msg’ => ‘上传的人脸不符合要求,请重新上传五官清晰的真实头像!’);

 

$quality = $data[‘result’][‘face_list’][0][‘quality’];

 

if($quality[‘occlusion’][‘left_eye’] > 0.6) return $err_result; // 左眼被遮挡的阈值

 

if($quality[‘occlusion’][‘right_eye’] > 0.6) return $err_result; // 右眼被遮挡的阈值

 

if($quality[‘occlusion’][‘nose’] > 0.7) return $err_result; // 鼻子被遮挡的阈值

 

if($quality[‘occlusion’][‘mouth’] > 0.7) return $err_result; // 嘴巴被遮挡的阈值

 

if($quality[‘occlusion’][‘left_cheek’] > 0.8) return $err_result; // 左脸颊被遮挡的阈值

 

if($quality[‘occlusion’][‘right_cheek’] > 0.8) return $err_result; // 右脸颊被遮挡的阈值

 

if($quality[‘occlusion’][‘chin_contour’] > 0.6) return $err_result; // 下巴被遮挡阈值

 

if($quality[‘blur’] != 0 && $quality[‘blur’] > 0.7) return $err_result; // 模糊度范围 0是最清晰,1是最模糊

 

if($quality[‘illumination’] < 40) return $err_result; // 光照范围

 

if($quality[‘completeness’] == 0) return $err_result; // 人脸完整度 0为人脸溢出图像边界,1为人脸都在图像边界内

 

return array(‘result’ => true);

 

}

 

function execCurl($url, $param) {

 

if (empty($url) || empty($param)) {

 

return array(‘result’ => false, ‘err_msg’ => ‘url or param is null’);

 

}

 

$curl = curl_init();//初始化curl

 

curl_setopt($curl, CURLOPT_URL, $url);//抓取指定网页

 

curl_setopt($curl, CURLOPT_HEADER, 0);//设置header

 

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上

 

curl_setopt($curl, CURLOPT_POST, 1);//post提交方式

 

curl_setopt($curl, CURLOPT_POSTFIELDS, $param);

 

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

 

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

 

$data = curl_exec($curl);//运行curl

 

$curl_err_msg = curl_error($curl);

 

curl_close($curl);

 

if($data === false) {

 

return array(‘result’ => false, ‘err_msg’ => $curl_err_msg);

 

}else {

 

return array(‘result’ => true, ‘data’ => $data);

 

}

 

}

 

function base64EncodeImage($image_path) {

 

$base64_image = ”;

 

$image_info = getimagesize($image_path);

 

$image_data = fread(fopen($image_path, ‘r’), filesize($image_path));

 

$base64_image = chunk_split(base64_encode($image_data));

 

return $base64_image;

 

}

 

$image_path = ‘image/1.jpg’;

 

$access_token = ‘上一步的获取access token’;

 

$result = checkPictureToCheckFace($image_path, $access_token);

 

判断是否符合人脸识别检查的字段说明:

百度API使用php实现人脸识别

 

阿里云人脸识别PHP调用示例

 

Code Sample

 

1、环境依赖

 

composer.json

 

{

 

“require”: {

 

“guzzlehttp/guzzle”: “~6.0”

 

}

 

}

 

2、使用网络图片

 

<?php

 

use GuzzleHttp\Psr7\Request;

 

use GuzzleHttp\Client;

 

require_once ‘vendor\autoload.php’;

 

// 参数设置

 

$akId = “********”;

 

$akSecret = “********”;

 

$body1 = ‘{“type”:”0″,”image_url”:”https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1553926699&di=3e4484731c8897c57e67b3f632801f9a&src=http://b-ssl.duitang.com/uploads/item/201603/28/20160328121906_ErzAB.jpeg”}’;

 

$url = “https://dtplus-cn-shanghai.data.aliyuncs.com/face/attribute”;

 

$date1 = gmdate(“D, d M Y H:i:s \G\M\T”);

 

// 参数构造

 

$options = array(

 

‘http’ => array(

 

‘header’ => array(

 

‘accept’=> “application/json”,

 

‘content-type’=> “application/json”,

 

‘date’=> $date1,

 

‘authorization’ => ”

 

),

 

‘method’ => “POST”, //可以是 GET, POST, DELETE, PUT

 

‘content’ => $body1

 

//         ‘content’ => json_encode($body1)

 

)

 

);

 

$http = $options[‘http’];

 

$header = $http[‘header’];

 

$urlObj = parse_url($url);

 

if(empty($urlObj[“query”]))

 

$path = $urlObj[“path”];

 

else

 

$path = $urlObj[“path”].”?”.$urlObj[“query”];

 

$body = $http[‘content’];

 

if(empty($body))

 

$bodymd5 = $body;

 

else

 

$bodymd5 = base64_encode(md5($body,true));

 

$stringToSign = $http[‘method’].”\n”.$header[‘accept’].”\n”.$bodymd5.”\n”.$header[‘content-type’].”\n”.$header[‘date’].”\n”.$path;

 

$signature = base64_encode(

 

hash_hmac(

 

“sha1”,

 

$stringToSign,

 

$akSecret, true));

 

$authHeader = “Dataplus “.”$akId”.”:”.”$signature”;

 

$options[‘http’][‘header’][‘authorization’] = $authHeader;

 

#  构造Rest API Client请求

 

$client = new Client();

 

$headers = [‘Content-type’ => ‘application/json’, ‘Accept’ => ‘application/json’, ‘Authorization’ => $options[‘http’][‘header’][‘authorization’], ‘Date’ => $date1];

 

$request = new Request(‘POST’,’https://dtplus-cn-shanghai.data.aliyuncs.com/face/attribute’,$headers,$body1);

 

$response = $client->send($request);

 

echo $response->getBody();

 

?>

 

3、使用本地图片

 

<?php

 

use GuzzleHttp\Psr7\Request;

 

use GuzzleHttp\Client;

 

require_once ‘vendor\autoload.php’;

 

// 参数设置

 

$akId = “********”;

 

$akSecret = “********”;

 

# 读取本地图片

 

$image_file = ‘C:\Users\Administrator\Desktop\time.jpeg’;

 

$image_info = getimagesize($image_file);

 

$base64_image_content = “data:{$image_info[‘mime’]};base64,” . chunk_split(base64_encode(file_get_contents($image_file)));

 

function trimall($str)//删除所有的空格

 

{

 

$qian=array(” “,” ”,”\t”,”\n”,”\r”);

 

$hou=array(“”,””,””,””,””);

 

return str_replace($qian,$hou,$str);

 

}

 

$base64_image_content = substr($base64_image_content, 23);

 

$base64_image_content = trimall($base64_image_content);

 

// echo $base64_image_content;

 

$body1 = ‘{“type”:”1″,”content”:”‘.$base64_image_content.'”}’;

 

$url = “https://dtplus-cn-shanghai.data.aliyuncs.com/face/attribute”;

 

$date1 = gmdate(“D, d M Y H:i:s \G\M\T”);

 

// 参数构造

 

$options = array(

 

‘http’ => array(

 

‘header’ => array(

 

‘accept’=> “application/json”,

 

‘content-type’=> “application/json”,

 

‘date’=> $date1,

 

‘authorization’ => ”

 

),

 

‘method’ => “POST”, //可以是 GET, POST, DELETE, PUT

 

‘content’ => $body1

 

)

 

);

 

$http = $options[‘http’];

 

$header = $http[‘header’];

 

$urlObj = parse_url($url);

 

if(empty($urlObj[“query”]))

 

$path = $urlObj[“path”];

 

else

 

$path = $urlObj[“path”].”?”.$urlObj[“query”];

 

$body = $http[‘content’];

 

if(empty($body))

 

$bodymd5 = $body;

 

else

 

$bodymd5 = base64_encode(md5($body,true));

 

$stringToSign = $http[‘method’].”\n”.$header[‘accept’].”\n”.$bodymd5.”\n”.$header[‘content-type’].”\n”.$header[‘date’].”\n”.$path;

 

$signature = base64_encode(

 

hash_hmac(

 

“sha1”,

 

$stringToSign,

 

$akSecret, true));

 

$authHeader = “Dataplus “.”$akId”.”:”.”$signature”;

 

$options[‘http’][‘header’][‘authorization’] = $authHeader;

 

#  构造Rest API Client请求

 

$client = new Client();

 

$headers = [‘Content-type’ => ‘application/json’, ‘Accept’ => ‘application/json’, ‘Authorization’ => $options[‘http’][‘header’][‘authorization’], ‘Date’ => $date1];

 

$request = new Request(‘POST’,’https://dtplus-cn-shanghai.data.aliyuncs.com/face/attribute’,$headers,$body);

 

$response = $client->send($request);

 

echo $response->getBody();

 

?>


慕源网 » 百度API使用php实现人脸识别

常见问题FAQ

程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!

发表评论

开通VIP 享更多特权,建议使用QQ登录