• PC端操作阿里云人脸识别(vue+php)


    html参考:

    1.需要引入 tracking.js 第三方库

    2.检测到人脸自动 stop

    3.canvas 压缩图片体积   正在上传中...........  

    <video id="video" preload autoplay loop muted></video>
    <canvas id="canvas" width="500" height="500"  style="position:absolute;top:0;left:0;"></canvas>
    export default {
        name: 'componentName',
        data() {
            return {
                videoEle: null,
                trackerTask:null,
                first:null
            } 
        },
        created(){
            this.openCamera();
        },
        mounted(){
        },
        methods: {
            openCamera () {
     
              var video = document.getElementById('video');
              var canvas = document.getElementById('canvas');
              var context = canvas.getContext('2d');
     
              var tracker = new tracking.ObjectTracker('face');  // 引入第三方 库
              tracker.setInitialScale(1);          
              tracker.setStepSize(2);
              tracker.setEdgesDensity(0.1);
     
              this.trackerTask = tracking.track('#video', tracker, { camera: true });
              //-------  指定 canvas 的宽高 ,auto 自动播放
              let constraints = {
                    video: { 500, height: 500},
                    audio: true
                };
     
              let promise = navigator.mediaDevices.getUserMedia(constraints);   // h5 新的API
                 
                promise.then(function (MediaStream) {
                    video.srcObject = MediaStream;
                    video.play();
                }).catch(function (PermissionDeniedError) {
                    console.log(PermissionDeniedError);
                })
                //--------------
                let that = this;
                that.tracker_fun(tracker,video,context,canvas); //open 摄像头,执行tracker_fun( 传入参数 )
     
          },
          tracker_fun(tracker,video,context,canvas){
            let that = this;
            let set_clear;
            set_clear = setTimeout(function(){ // 每秒 检测人脸 结果
                  tracker.on('track', function(event) {     // 视频流
                    // context.clearRect(0, 0, canvas.width, canvas.height);
                  if(!that.first){     // if  --- > else  检测到人脸 success() =>{}
                  event.data.forEach(function(rect) {
                    if(rect.x){
                      that.first = rect.x;
                      video.pause();    // success  将暂停 video
                      console.log(rect)
                      console.log(video)
                      context.drawImage(video, 0, 0, 500, 500);   // 绘制到 canvas
                      context.font = '11px Helvetica';
                      context.fillText("",100,40);
                      context.strokeStyle = '#a64ceb';
                      context.strokeRect(rect.x, rect.y, rect.width, rect.height);
                      var data_url = canvas.toDataURL('image/png'); //base64 request
                      console.log(data_url)
     
                      // video.load();
                      // that.first = null;
                      // that.tracker_fun(tracker,video,context,canvas)
                      return;
                    }
                  });
                  }
                });
                  clearTimeout(set_clear)
                  console.log('-------')
            },5000)
             
          }
        },
        mounted() {
     
        },
        destroyed() {
            // 停止侦测
            this.trackerTask.stop()
            // 关闭摄像头
            window.tracking.closeCamera()
        }   
    }

    PHP操作阿里云介绍

    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();
    ?>

    SSL错误处理

    问题描述

    在使用 PHP 的 http 客户端工具(如 Guzzle)调用认知服务时出现证书认证问题,错误信息如下:

    Fatal error: Uncaught exception 'GuzzleHttp\Exception\RequestException' with message 'cURL error 60: SSL certificate problem: unable to get local issuer certificate
    

    解决方法

    该问题的出现是由于没有配置信任的服务器 HTTPS 验证。默认 cURL 是被设为不信任任何 CAs 的,因此这就是无法访问相关服务器的原因。解决该问题的最好方法是指定一组默认受信任的 CAs。

    • CA 证书

      数字证书认证机构(Certificate Authority, 缩写为 CA),是负责发放和管理数字证书的权威机构,它要制定政策和具体步骤来验证、识别用户身份,并对用户证书进行签名,以确保证书持有者的身份和公钥的拥有权。证书通常包括所有者的公钥、 证书的到期时间、所有者的名称和其他关于所有者的信息。

    所以可以通过下载证书的方式解决该问题,具体操作方法如下:

    1. 下载证书保存到本地,下载地址:https://curl.haxx.se/ca/cacert.pem
    2. 配置 php.ini 文件:curl.cainfo =<filepath>/cacert.pem
    3. 重启 Apache 服务器,问题即可解决。
    通往牛逼的路上,在意的只有远方!
  • 相关阅读:
    scrollTop
    ……
    放下
    值得纪念的一天
    php新手上路(六)
    image map
    文字多出用点代替
    js formatter
    感谢,今天刚申请了博客园,
    接口的作用
  • 原文地址:https://www.cnblogs.com/ccdr/p/15791792.html
Copyright © 2020-2023  润新知