WalkerDi的技术专栏 PHP and SQL Coder

百度人脸识别

2018-07-03

阅读:


本文讲解如何使用百度提供的人脸识别技术进行简单的应用,这里以CI 框架为例进行说明。

在百度AI开放平台使用百度的人脸识别能力,只需要三个核心步骤即可操作完成:

1.获取接口权限

2.准备接口调用工具

3.进行接口调用

步骤

1.开通百度开发者账号

地址:https://console.bce.baidu.com/ai/?_=1528192333418&fromai=1#/ai/face/overview/index

2.创建人脸识别应用

账号登录成功,您需要创建应用才可正式调用AI能力。应用是您调用API服务的基本操作单元,您可以基于应用创建成功后获取的API Key及Secret Key,进行接口调用操作,及相关配置。

创建应用,填写【应用名称】和【应用描述】,即可创建应用(其他选项可以不做操作,使用默认值即可)

3.获取秘钥

在您创建完毕应用后,平台将会分配给您此应用的相关凭证:API Key、Secret Key。使用秘钥将可以在下一步中获取调用接口所需的Access Token。

接口开发及应用

在拿到秘钥及应用的相关凭证API Key、Secret Key后,就可以开发接口调用了,这里已CI 框架为例进行说明。

必要参数说明

access_token 百度鉴权凭证 ,以redis缓存形式保存;

grant_type: 必须参数,固定为client_credentials;

client_id: 必须参数,应用的API Key;

client_secret: 必须参数,应用的Secret Key;

需要注意的是 Header Content-Type 参数设置为 application/x-www-form-urlencoded


<?php
/**
 * 百度人脸识别 api
 * Created by PhpStorm.
 * author: dichuanjun
 * Date: 2018/5/7
 * Time: 15:29
 */

class Baiduface
{
    protected $CI;
    protected $grand_type;
    protected $client_id;
    protected $client_secret;
    protected $url;
    protected $header;
    public static $baidu_access_token_key = "ibearcar_baidu_access_token_key";
    public function __construct()
    {
        $this->CI = & get_instance();
        $this->CI->load->driver('cache', array('adapter' => 'redis'));
        $this->grand_type='client_credentials';
        $this->client_id='OyF3BFkK2T7LbqWgQYIsPtIm';
        $this->client_secret='wH2umjZ8YapP0jatX7H1xT7uyfHQwGBq';
        $this->url='https://aip.baidubce.com/oauth/2.0/token';
        $this->header=array('Content-type:application/x-www-form-urlencoded');

    }

    /**
     * 获取 Access Token
     */
    public function get_access_token(){

        $post_data['grant_type']       = $this->grand_type;
        $post_data['client_id']      = $this->client_id;
        $post_data['client_secret'] = $this->client_secret;

        $access_token = $this->CI->cache->get(self::$baidu_access_token_key); //这里是access_token以redis缓存形式保存
        if(empty($access_token)){
            $data_json=$this->_http_post($this->url,$post_data,'');
            $data=json_decode($data_json,true);
            if(isset($data['error'])){
                return false;
            }
            $access_token=$data['access_token'];
            $this->CI->cache->save(self::$baidu_access_token_key, $access_token, 28 * 24 * 3600);
            $file="./logs/baidu_access_token_log.txt";
            $str=date('Y-m-d H:i:s')." access_token:{$access_token}\r\n";
            file_put_contents($file,$str,FILE_APPEND);
        }

        return $access_token;

    }

    /**
     * 人脸识别--公安验证v3版
     * @param $data
     * @return bool
     */
    public function face_verify($data){
        $access_token = $this->get_access_token();
        $url="https://aip.baidubce.com/rest/2.0/face/v3/person/verify?access_token={$access_token}";
        $post_data['image']=$data['image'];
        $post_data['id_card_number']=$data['id_card_number'];
        $post_data['name']=$data['name'];
        $post_data['image_type']='BASE64';

        $data_json=$this->_http_post($url,$post_data,$this->header);
        $data = json_decode($data_json,true);
        if($data['error_code']==0){
            if($data['result']['score']>=80){
                return true;
            }

        }else{
            return false;
        }


    }

    /**
     * 验证身份信息
     * @param $data
     * @return array
     */
    public function verify($data){
        $idcard_info=$this->idcard($data);
        $driving_license_info=$this->driving_license($data);
        $code=6000;
        $res_data='';
        if(isset($idcard_info[0]['error_code'])){
            $code = 6002;
            $result=[
                'code'=>$code,
                'data'=>$res_data,
            ];
            return $result;
        }
        if(isset($idcard_info[1]['error_code'])){
            $code = 6003;
            $result=[
                'code'=>$code,
                'data'=>$res_data,
            ];
            return $result;
        }
        if(isset($driving_license_info['error_code'])){
            $code = 6005;
            $result=[
                'code'=>$code,
                'data'=>$res_data,
            ];
            return $result;
        }

        if(empty($idcard_info[0]['words_result']['公民身份号码']['words'])){
            $code = 6003;
        }


        $this->CI->load->model('M_user_certificate');
        $idcard=$this->CI->M_user_certificate->get_certificate_by_idcard($idcard_info[0]['words_result']['公民身份号码']['words']);
        if(!empty($idcard)){
            $code=6012;
        }


        if(strtotime($idcard_info[1]['words_result']['失效日期']['words'])<time()){
            $code = 6007;
        }

        if(strtotime($driving_license_info['words_result']['至']['words'])<time()){
            $code = 6008;
        }
        if($idcard_info[0]['words_result']['公民身份号码']['words']!=$driving_license_info['words_result']['证号']['words']){
            $code = 6006;
        }
        if($code==6000){
            $verify_data=[
                'image'=>$data['personal_image'],
                'id_card_number'=>$idcard_info[0]['words_result']['公民身份号码']['words'],
                'name'=>$driving_license_info['words_result']['姓名']['words'],
            ];

            //身份验证
            if(!$this->face_verify($verify_data)){
                $code = 6009;
            }
        }

        if($driving_license_info['words_result']['性别']['words']=='男'){
            $sex=0;
        }else{
            $sex=1;
        }

        //验证成功
        if($code==6000){
            $certificate_data=[
                'name'=>$driving_license_info['words_result']['姓名']['words'],
                'sex'=>$sex,
                'id_card_number'=>$driving_license_info['words_result']['证号']['words'],
                'birth_date'=>date('Y-m-d',strtotime($driving_license_info['words_result']['出生日期']['words'])),
                'card_date'=>date('Y-m-d',strtotime($idcard_info[1]['words_result']['失效日期']['words'])),
                'driving_type'=>$driving_license_info['words_result']['准驾车型']['words'],
                'driving_first_date'=>date('Y-m-d',strtotime($driving_license_info['words_result']['初次领证日期']['words'])),
                'driving_num'=>$driving_license_info['words_result']['证号']['words'],
                'driving_date'=>date('Y-m-d',strtotime($driving_license_info['words_result']['至']['words'])),

            ];
            $res_data=$certificate_data;
        }

        $result=[
            'code'=>$code,
            'data'=>$res_data,
        ];
        return $result;


    }

    /**
     * ocr 身份证识别
     * @param $data
     * @return array
     */
    public function idcard($data){
        $access_token = $this->get_access_token();
        $res_data=[];
        $data=[
            'front'=>$data['idcard_front'],
            'back'=>$data['idcard_back']

        ];
        $url="https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={$access_token}";
        foreach ($data as $key=>$value){
            $post['image']=$value;
            $post['id_card_side']=$key;
            $post['detect_risk']=true;
            $res_data[]=json_decode($this->_http_post($url,$post,$this->header),true);
        }

        return $res_data;

    }

    /**
     * ocr 驾驶证识别
     * @param $data
     * @return array
     */
    public function driving_license($data){
        $post_data['image']=$data['driving_image'];
        $access_token = $this->get_access_token();
        $url="https://aip.baidubce.com/rest/2.0/ocr/v1/driving_license?access_token={$access_token}";
        $res_data=json_decode($this->_http_post($url,$post_data,$this->header),true);
        return $res_data;

    }

    private function _http_post($url, $data,$header) {

        $o = "";
        foreach ( $data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $data = substr($o,0,-1);

        $handle = curl_init();
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($handle, CURLOPT_POST, 1);
        if(!empty($header)){
            curl_setopt($handle,CURLOPT_HTTPHEADER,$header); //设置header
        }
        // curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
        curl_setopt($handle, CURLOPT_TIMEOUT, 10);
        curl_setopt($handle, CURLOPT_URL, $url);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($handle);
        curl_close($handle);

        return $response;
    }

}

接口应用

 /**
     * 百度人脸识别
     */
    public function baidu_face_verify(){

        $this->load->model('M_user_certificate');
        $this->load->model('M_user');
        $user_info = $this->session->userdata(KEY_USER_INFO);
        $this->load->library('baiduface');
        if(empty($user_info)){
            $this->api_response_result(11);
        }


        $driving_image=$this->input->post('driving_image',true);//驾驶证
        $personal_image=$this->input->post('personal_image',true);//个人照片
        $idcard_front=$this->input->post('idcard_front',true); //身份证正面
        $idcard_back=$this->input->post('idcard_back',true); //身份证背面

        if(empty($driving_image)){
            $this->api_response_result(6011);
        }
        if(empty($personal_image)){
            $this->api_response_result(6010);
        }
        if(empty($idcard_front)){
            $this->api_response_result(6004);
        }

        if(empty($idcard_back)){
            $this->api_response_result(6006);
        }


        $verify_data['driving_image']=$driving_image;
        $verify_data['personal_image']=$personal_image;
        $verify_data['idcard_front']=$idcard_front;
        $verify_data['idcard_back']=$idcard_back;

        $res = $this->baiduface->verify($verify_data);
        $user_data=[
            'id'=>$user_info['id'],
            'is_identification'=>0,
        ];
        if($res['code']==6000){
            $certificate_data=$res['data'];
            $certificate_data['user_id']=$user_info['id'];
            $this->M_user_certificate->save_entry($certificate_data);
            $user_data['is_identification']=1;//已认证
            $this->M_user->save_entry($user_data);
            $user = $this->M_user->get_by_phone($user_info['mobile_phone']);
            $this->_login($user);//更新session
        }else{
            $this->M_user->save_entry($user_data);
        }

        $this->api_response_result($res['code']);
    }

参考地址:

百度人脸识别api https://cloud.baidu.com/doc/OCR/OCR-API.html#.E8.BA.AB.E4.BB.BD.E8.AF.81.E8.AF.86.E5.88.AB

百度应用接入 http://ai.baidu.com/docs#/Begin/top


上一篇 Linux 磁盘挂载

Comments

Content