这两天一个朋友在写 Python 玩抖音的小姐姐识别,
得知是用了百度的接口, 突然想起博主上个月有写一篇文章也用到了百度的接口: PHP开发图像内容识别
直接上代码, 先创建一个 index.html 并写入以下代码:
人脸识别 - 不败君body {
text-align: center;
}
#img_show{
margin-top: 20%;
margin-left: auto;
margin-right: auto;
width: 300px;
height: 200px;
background: #ddd;
}
#img_show img{
max-width: 100%;
}
#upload{
margin-top: 20px;
}
图片上传
layui.use('upload', function(){
var $ = layui.jquery;
var upload = layui.upload;
var uploadInst = upload.render({
elem: '#upload',
url: 'face.php',
accept: 'images',
before: function(obj){
layer.load();
obj.preview(function(index, file, result){
$('#img_view').attr('src', result);
document.getElementById('img_show').style.background = '#fff';
});
},
done: function(res){
if (res.code) {
layer.msg(res.msg);
return;
}
document.getElementById('info').innerHTML = '
识别人脸数量:' + res.data.face_num + '
年龄:' + res.data.age + '
评分:' + res.data.beauty + '
';layer.closeAll('loading');
},
error: function(){
layer.msg('图片上传失败');
layer.closeAll('loading');
}
});
});
注意的是, 上面代码使用了 layui , 引用的都是现在这个博客的链接, 但是博客开了防盗链, 所以如果要使用, 请自行到 layui 官方下载并引用.
接下来就是 face.php 的代码:
header('Content-type: application/json');
if ($_FILES["file"]["error"] > 0) {
exit(json_encode(['code' => 101, 'msg' => $_FILES["file"]["error"]]));
}
if ($_FILES["file"]["size"] / 1024 > 5120) {
exit(json_encode(['code' => 101, 'msg' => '图片不能大于5M']));
}
$allowed_exts = ["gif", "jpeg", "jpg", "png"];
$extension = end(explode(".", $_FILES["file"]["name"]));
if (!in_array($extension, $allowed_exts)) {
exit(json_encode(['code' => 101, 'msg' => '文件类型错误']));
}
$img_data = base64_encode(file_get_contents($_FILES["file"]["tmp_name"]));
$access_token = get_access_token();
$url = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token={$access_token}";
$bodys = "{"image":"{$img_data}","image_type":"BASE64","face_field":"age,beauty"}";
$res = json_decode(request_post($url, $bodys), true);
if ($res['error_code'] !== 0) {
exit(json_encode(['code' => 101, 'msg' => '图片上传失败, 或图片没有人脸']));
}
exit(json_encode([
'code' => 0,
'data' => [
'src' => 'xxx',
'face_num' => $res['result']['face_num'],
'age' => $res['result']['face_list'][0]['age'],
'beauty' => $res['result']['face_list'][0]['beauty'],
],
]));
function get_access_token()
{
$file_name = 'access_token.json';
if (!file_exists($file_name)) {
return request_access_token($file_name);
}
$lst_access_token = json_decode(file_get_contents($file_name), true);
if (empty($lst_access_token) || $lst_access_token['time'] < time() + 86400) {
return request_access_token($file_name);
}
return $lst_access_token['access_token'];
}
function request_access_token($file_name)
{
$api_key = 'xUGgcEQf1376ozjEkE'; // 填入百度应用的 API KEY
$client_secret = 'cLsMxElngpooS51cKhU2Bui'; // 填入百度应用的 client_secret
$url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={$api_key}&client_secret={$client_secret}";
$lst_access_token = json_decode(file_get_contents($url), true);
$file = fopen($file_name, 'w+');
fwrite($file, json_encode(['access_token' => $lst_access_token['access_token'], 'time' => time()]));
fclose($file);
return $lst_access_token['access_token'];
}
function request_post($url = '', $param = '')
{
if (empty($url) || empty($param)) {
return false;
}
$post_url = $url;
$curl_post = $param;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $post_url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
以上代码需要修改一下 request_access_token 函数的 API KEY 之类的信息, 这些信息都是从百度应用中获取的. 百度应用: https://console.bce.baidu.com/?fromai=1#/aip/overview