1. 程式人生 > >微信小程式之人臉識別

微信小程式之人臉識別

人臉識別,是基於人的臉部特徵資訊進行身份識別的一種生物識別技術。用攝像機或攝像頭採集含有人臉的影象或視訊流,並自動在影象中檢測和跟蹤人臉,進而對檢測到的人臉進行臉部的一系列相關技術,通常也叫做人像識別、面部識別。

下面是前臺頁面,用到了camera元件,進行拍照

<camera device-position="{{position}}" flash="off" binderror="error" style="width: 100%; height: 300px;"></camera>
<switch checked bindchange= 'switchChange' />
<button type="primary" bindtap="takePhoto">拍照</button>

後臺程式碼如下(其中init_face方法是獲取APP_ID,API_KEY,SECRET_KEY):

//刷臉登入
    public function login(){
    	//上傳路徑
    	$dir = "./Uploads/temp/";
    	if(!file_exists($dir)){
            mkdir($dir, 0777, true);
        }
        $upload = new \Think\Upload();// 例項化上傳類
        $upload->maxSize = 2048000 ;// 設定附件上傳大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 設定附件上傳型別
        $upload->rootPath = $dir; // 設定附件上傳根目錄
        $upload->savePath = ''; // 設定附件上傳(子)目錄
        $upload->saveName = $no;
        $upload->autoSub = false;
        // 上傳檔案
        $info = $upload->uploadOne($_FILES['file']);
        if(!$info) {// 上傳錯誤提示錯誤資訊

            return json_encode(array('error'=>true,'msg'=>$upload->getError()),JSON_UNESCAPED_UNICODE);
        }else{// 上傳成功 獲取上傳檔案資訊

            $file = $dir . $info['savepath'] . $info['savename'];
            $image = base64_encode(file_get_contents($file));
            // 呼叫人臉檢測
        	$client = $this->init_face();

        	$options['liveness_control'] = 'NORMAL';
        	$options["max_face_num"] = '1';
        	
        	$ret = $client->search($image,'BASE64','pingjiao',$options);

            // echo json_encode($ret,JSON_UNESCAPED_UNICODE);
            // exit;

            if($ret['error_code'] == 0){ //有人臉
	        	$user = $ret['result']['user_list'][0];
	        	$no = $user['user_id'];
	        	$score = $user['score'];

	        	if(!empty($no)){
	        		$data = M('student')->field('no,name,sex')->where("no='{$no}'")->find();
	        		if($data){
                        $data['score']=$score;
                        // if($score>95){
                        //     echo '姓名:'.$data['name'];
                        // }else{
                            echo json_encode($data,JSON_UNESCAPED_UNICODE);
                        // }
                    }else{
                        echo "本地資料庫沒有該學生,百度雲資訊:個人資訊:{$no}, 分值:{$score}";
                    }

	        	}
	        }else{
                echo "活體檢測失敗," . json_encode($ret,JSON_UNESCAPED_UNICODE);
             }

        }
    }

js程式碼如下,通過介面實現人臉識別:

Page({

  /**
   * 頁面的初始資料
   */
  data: {
    position: 'back',
  },
  switchChange: function(e){
    if (e.detail.value == true) {
      this.setData({ position: 'back' });
    } else {
      this.setData({ position: 'front' });
    }
  },
  takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        var tempImagePath = res.tempImagePath;
        // console.log(tempImagePath);
        wx.showLoading({
          title: '正在核驗身份。。。。。',
        })
        this.setData({ loindisables: true });

        wx.uploadFile({
          url: ....., //僅為示例,非真實的介面地址
          header: {
            Cookie: wx.getStorageSync('session_id')
          },
          filePath: tempImagePath,
          name: 'file',
          success: (res) => {
            wx.hideLoading();
            this.setData({ loindisables: false });
            var data = res.data
            console.log(data)
            //do something
            wx.showModal({
              title: '提示',
              content: data,
              showCancel: false
            })
          }
        })
      }
    })
  },