不败君

前端萌新&初级后端攻城狮

PHP人脸识别为你的颜值打分

PHP人脸识别为你的颜值打分

2020-04-23 18:20:00

围观(2304)

这两天一个朋友在写 Python 玩抖音的小姐姐识别, 如:

1.jpg

得知是用了百度的接口, 突然想起博主上个月有写一篇文章也用到了百度的接口: PHP开发图像内容识别

好奇心驱使下, 又玩起了百度的人脸识别接口. 最后做出来的效果:

2.png

在线体验: www.bubaijun.com/demo/face

直接上代码, 先创建一个 index.html 并写入以下代码:

<!DOCTYPE html>
<html>
<head>
    <title>人脸识别 - 不败君</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="viewport" content="initial-scale=1, width=device-width, maximum-scale=1, user-scalable=no">
    <link rel="stylesheet" href="https://www.bubaijun.com/layui/css/layui.css">
    <style>
        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;
        }
    </style>
</head>
<body>
  
    <div id="img_show">
        <img id="img_view" />
    </div>
  
    <div id="info"></div>

    <button class="layui-btn" id="upload">图片上传</button>

    <script src="https://www.bubaijun.com/layui/layui.js"></script>
  
    <script type="text/javascript">
        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 = '<p>识别人脸数量:' + res.data.face_num + '</p><p>年龄:' + res.data.age + '</p><p>评分:' + res.data.beauty + '</p>';
                    layer.closeAll('loading');
              },
              error: function(){
                    layer.msg('图片上传失败');
                    layer.closeAll('loading');
              }
            });
          });
    </script>

</body>
</html>

注意的是, 上面代码使用了 layui , 引用的都是现在这个博客的链接, 但是博客开了防盗链, 所以如果要使用, 请自行到 layui 官方下载并引用.


接下来就是 face.php 的代码:

<?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

本文地址 : bubaijun.com/page.php?id=175

版权声明 : 未经允许禁止转载!

评论:我要评论
发布评论:
Copyright © 不败君 粤ICP备18102917号-1

不败君

首 页 作 品 微 语