1. 程式人生 > >微信小程式 上傳圖片,人臉識別

微信小程式 上傳圖片,人臉識別

今天我們來說一下人臉識別怎麼實現,首先你要有一個可以就行人臉識別的伺服器,阿里雲百度雲都可以,這裡推薦使用百度雲,因為百度雲人臉識別的API介面全面升級到V3版本,並進行開放測試,意思就是說現在是免費的   ^_^。

先來看一下人臉識別頁面


我們來看一下wxml程式碼

<camera device-position="{{sxt}}" flash="off" binderror="error" style="width: 100%; height: 300px;"></camera>
<view class="weui-cells weui-cells_after-title">
                <view class="weui-cell weui-cell_switch">
                    <view class="weui-cell__bd"></view>
                    <!-- <view class="weui-cell__ft"> -->
                        <input name='sex' value='{{sxt}}'>{{sxt}}</input>
                        <switch checked bindchange='switch1Change'/>
                    <!-- </view> -->
                </view>
            </view> 
<button type="primary" bindtap="takePhoto">拍照</button>

然後是js程式碼

data: {
    sxt: '前置'
  },
  switch1Change: function (e) {
    console.log(e)
    var front = '前置'
    var back = '後置'
    if (this.data.sxt == '前置') {
      this.setData({ sxt: back })
    } else if (this.data.sxt == '後置') {
      this.setData({ sxt: front })
    }
  },
  takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        // console.log(res);
        this.setData({
          src: res.tempImagePath
        })
        wx.showLoading({
        	title:'正在核驗身份...',
        })
        this.setData({logindisabled:true});

        wx.uploadFile({
          url: 'http://www.swinder.top/server/index.php/home/index/login',
        	filePath:res.tempImagePath,
        	name:'file',

        	success:(res)=>{
        		wx.hideLoading();
        		this.setData({logindisabled:false});

        		var data = res.data
        		console.log(data);
        		wx.showModal({
        			title:'提示',
        			content:data,
        			showCancel:false
        		})
        	}
        })
      }
    })
  }

然後我們來看一下url呼叫的PHP程式碼 

 private function init_face(){
      $APP_ID=''; //在百度雲上檢視自己的資訊
      $API_KEY='';
      $SECRET_KEY='';
      $dir = APP_PATH . '/face-sdk/';
      require_once $dir . 'AipFace.php';
      return new \AipFace($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;//設定附件上傳大小2m
        $upload->exts=array('jpg','gif','png','jpeg');//設定上傳型別
        $upload->rootPath=$dir;//設定附件上傳根目錄
        $upload->savePath='';//設定附件上傳(子)目錄
        $upload->autoSub=false;

        //上傳檔案
        $info = $upload->uploadOne($_FILES['file']);
        if(!$info){
        	//上傳錯誤提示資訊
        	echo 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_user_num']='1';
        	$ret = $client->search($image,'BASE64',$this->face_group(),$options);

        	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;
        				echo json_encode($data,JSON_UNESCAPED_UNICODE);
        			}else{
        				//本地庫不存在此學號
        				echo "本地資料庫沒有該學生,百度雲庫資訊:個人資訊:{$no},分值:{$score}";
        			}

        		}

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

我們需要下載百度雲的sdk檔案



然後我們將下載的檔案解壓新增到ThinPHP框架中  我起了一個檔名叫 face-sdk 的資料夾,在裡面放了SDK檔案解壓出來的東西,這裡我們主要呼叫了AipFace.php檔案,這個檔案就是已經封裝好的人臉識別所需要呼叫的介面


如果這些都弄好了我們就可以在百度雲人臉庫中新增自己的一張照片


在這按照步驟新增  人臉庫名稱,使用者組,使用者然後編輯使用者資訊即可,

然後我們就可以在小程式上進行拍照了,他會和百度雲人臉庫中的圖片進行對比,然後返回一個分數最高的人的資訊。

好了到這裡 人臉識別的基本功能已經介紹完畢了,謝謝觀看。