PHP人脸识别小程序接口(阿里云OpenAPI)

越信鸥
2023-12-01

这两天接的小程序用了阿里云的openapi--人脸识别接口,讲下大体流程和代码

  • 先进入人脸识别文档,开通该服务  
  • 然后建立RAM子账号,并设置accessKey,并记下两个参数
  • 使用阿里云新版php-sdk GitHub - aliyun/openapi-sdk-php: Alibaba Cloud SDK for PHP,用composer安装
  • composer require alibabacloud/sdk

    我用的框架tp5 获取调用该接口的权限

  • <?php
    AlibabaCloud::accessKeyClient('foo', 'bar')
                // ->regionId('cn-hangzhou')
                ->asDefaultClient();

添加人脸#

参考地址: 阿里云OpenAPI开发者门户

/**          * AddFace, 向人脸库中添加人脸
     * 
     * @param string $Group 添加人脸的分组
     * @param string $Person 添加人脸的姓名
     * @param string $Image 添加人脸的编号
     * @param string $Content 添加人脸图片的base64编码     * Content参数也可以换成图片url,二者选一个即可    
     */
    public function AddFace($Group, $Person, $Image, $Content){

        try {
            $result = AlibabaCloud::rpc()
            ->product('FaceAPI')
            ->version('2018-12-03')
            ->action('AddFace')
            ->method('POST')
            ->host('face.cn-shanghai.aliyuncs.com')
            ->regionId('cn-shanghai')
            ->setAcceptFormat('json')
            ->setQueryParameters('Group', $Group)
            ->setQueryParameters('Person', $Person)
            ->setQueryParameters('Image', $Image)
            // ->setQueryParameters('ImageUrl', $ImageUrl)
            ->setQueryParameters('Content', $Content)
            ->request();
            /**
             *  ["RequestId"] => string(36) "E4C1CE50-5123-48A1-BEB7-CFBA4C2A7D5D"
             *  ["Data"] => string(2) "ok"
             *  ["Success"] => bool(true)
             *  ["RequestId"] => string(36) "1588E5F8-6642-49D6-BB48-BDBD012589E0"
             *  ["HostId"] => string(29) "face.cn-shanghai.aliyuncs.com"
             *  ["Code"] => string(13) "AddImageError"
             *  ["Message"] => string(67) "Error 1062: Duplicate entry 'test-testone12-test' for key 'img_idx'"
             */
            $message = [
                'status'=>'failed',
                'message'=>$result['Message']        
            ];  
            if(!empty($result['Success']) && $result['Success'] === true){
                $message = [
                    'status'=>'success',
                    'message'=>'添加人物肖像图成功.'
                ];
            }else if(!empty($result['Code'])){
                if((strstr($result['Message'], 'Duplicate entry'))){
                    $message = [
                        'status'=>'failed',
                        'message'=>'请勿重复添加人物肖像图.'
                    ];
                }else if((strstr($result['Message'], 'Image Decode Failed'))){
                    $message = [
                        'status'=>'failed',
                        'message'=>'图片解码失败, 请检查上传图片的编码.'
                    ];
                }else if((strstr($result['Message'], 'NO_FACE_DETECTED'))){
                    $message = [
                        'status'=>'failed',
                        'message'=>'请上传正确的人脸图片.'
                    ];
                }else if((strstr($result['Message'], 'expect 1'))){
                    $message = [
                        'status'=>'failed',
                        'message'=>'请上传只有一张人脸的图片.'
                    ];
                }
            }

           return $this->response->create(['message'=>$message], 'json')->code('200');
        } catch (ClientException $exception) {
            print_r($exception->getErrorMessage());
        } catch (ServerException $exception) {
            print_r($exception->getErrorMessage());
        }
    }

删除人脸#

参考地址: 阿里云OpenAPI开发者门户

/**
     * DeleteFace, 从人脸库中删除人脸
     * 
     * @param string $Group 删除人脸所在的分组
     * @param string $Person 删除人脸的姓名
     * @param string $Image 删除的人脸编号
     */
    public function DeleteFace($Group, $Person, $Image){
        try {
            $result = AlibabaCloud::rpc()
            ->product('FaceAPI')
            ->version('2018-12-03')
            ->action('DeleteFace')
            ->method('POST')
            ->host('face.cn-shanghai.aliyuncs.com')
            ->regionId('cn-shanghai')
            ->setAcceptFormat('json')
            ->setQueryParameters('Group', $Group)
            ->setQueryParameters('Person', $Person)
            ->setQueryParameters('Image', $Image)
            ->request();
            /**
             * {"RequestId":"8C1F5719-DDD6-433D-A9D0-20B91C0BF048","Data":"ok","Success":true}             
             */
            $result = $result->toArray();
            if(!empty($result['Success']) && $result['Success'] === true){
                $message = [
                    'status'=>'success',
                    'message'=>'删除人物肖像图成功.'
                ];
            }else{
                $message = $result;
            }
           return $this->response->create($message, 'json')->code('200');
       } catch (ClientException $exception) {
            print_r($exception->getErrorMessage());
        } catch (ServerException $exception) {
            print_r($exception->getErrorMessage());
        }
    }

列出人脸数据#

参考地址: 阿里云OpenAPI开发者门户

/**
    * ListGroup,列举人脸组
    */
    function ListGroup(){
        try {
            $result = AlibabaCloud::rpc()
            ->product('FaceAPI')
            ->version('2018-12-03')
            ->action('ListGroup')
            ->method('POST')
            ->host('face.cn-shanghai.aliyuncs.com')
            ->regionId('cn-shanghai')
            ->setAcceptFormat('json')
            ->request();
            /**
             * {"RequestId":"D410F1BB-9B45-4B8D-ABC0-3EF4E3A6F0B5","Data":["test"],"Success":true}
             */
            $result = $result->toArray();
            if(!empty($result['Success']) && $result['Success'] === true){
                $message = [
                    'status'=>'success',
                    'message'=>'获取分组成功.',
                    'data'=>$result['Data'],                    
                ];
            }else{
                $message = $result;
            }
           return $this->response->create($message, 'json')->code('200');
        } catch (ClientException $exception) {
            print_r($exception->getErrorMessage());
        } catch (ServerException $exception) {
            print_r($exception->getErrorMessage());
        }
    }

人脸检索,返回的是一个score,我判断小于0.5即不是一个人#

参考地址: 阿里云OpenAPI开发者门户

/**
     * RecognizeFace, 查找注册库中的人脸
     * 
     * @param string $Group 识别的组
     * @param string $Content 图像base64编码
     */
    function RecognizeFace($Group, $Content){
        try {
            $result = AlibabaCloud::rpc()
            ->product('FaceAPI')
            ->version('2018-12-03')
            ->action('RecognizeFace')
            ->method('POST')
            ->host('face.cn-shanghai.aliyuncs.com')
            ->regionId('cn-shanghai')
            ->setAcceptFormat('json')
            ->setQueryParameters('Group', $Group)
            // ->setQueryParameters('ImageUrl', $ImageUrl)
            ->setQueryParameters('Content', $Content)
            ->request();
            /**
             * {"status":"success","message":"获取分组成功.","data":[{"image":"test","rect":[227,80,160,215],"score":0.049100418,"person":"testonelb"}]}
             */
            $result = $result->toArray();
            if(!empty($result['Success']) && $result['Success'] === true){
                if($result['Data'][0]['score'] > 0.5){
                    $message = [
                        'status'=>'success',
                        'message'=>'验证成功.',
                        'data'=>$result['Data'],                    
                    ];
                }else{
                    $message = [
                        'status'=>'failed',
                        'message'=>'验证失败.',
                        'data'=>$result['Data'],                    
                    ];
                }       
            }else{
                $message = $result;
            }
            return $message;
        } catch (ClientException $exception) {
            print_r($exception->getErrorMessage());
        } catch (ServerException $exception) {
            print_r($exception->getErrorMessage());
        }
    }

 类似资料: