本文为大家分享了微信小程序实现人脸检测的具体代码,供大家参考,具体内容如下
因为本文章的人脸检测技术运用的是百度云人工智能,首先要有百度云的账号。
近期,人脸识别已经升级到了V3,开启了测试,所以也依照v3文档进行了更新;
1、人脸识别的每个接口,都需要用到百度云的access_token,首先获取 access-token ,一个月之后access_token过期;可以将获取的存入文件,再次引用时可以判断其是否过期,然后引用或者重新获取:
//获取access_token function request_post($url = '', $param = '') { if (empty($url) || empty($param)) { return false; } $postUrl = $url; $curlPost = $param; $curl = curl_init();//初始化curl curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页 curl_setopt($curl, CURLOPT_HEADER, 0);//设置header curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求
2、创建初始化方法,需要用到 Secret_Key、API_Key、App_ID,为用户基本资料;
private function init_face(){ $App_ID = '用户appid'; $API_Key = '用户api_key'; $Secret_Key = '用户secret_key'; $dir = APP_PATH.'/face-sdk/'; require_once $dir."AipFace.php"; return new \AipFace($App_ID, $API_Key, $Secret_Key); }
(thinkPHP框架)
将所需检测图片放入文件;具体参数可依照百度云人脸识别v3文档查看。
// 人脸检测 public function facevalid(){ $file = './Upload/2018-05-17/1.png'; if (!file_exists($file)) { die('文件不存在!'); } $image = base_encode(file_get_contents($file)); $imageType = 'BASE'; //如果有可选参数 $options = array(); $options['max_face_num'] = 2; $client = $this->init_face(); $ret = $client->detect($image,$imageType,$options); // print_r($ret); if ($ret['error_code'] == 0) {//有人脸 $result = $ret['result']; $face_num = $result['face_num']; if ($face_num==1) { //人脸数量为1 $face_probability = $result['face_list'][0]['face_probability']; if ($face_probability==1) { //可靠性为1 $user_id = myguid(); $group_id = $this->face_group(); $res = $client->addUser($image,'BASE',$group_id,$user_id); // print_r($res); if ($res['error_code']==0) { echo "人脸检测完成,并入库"; } }else{ die('可靠性为:'.$face_probability); } }else{ die('人脸数大于1'); } }else{ die('没有人脸'); } } // 获取组 private function face_group(){ $groupname = '10001'; $client = $this->init_face(); $ret = $client->getGroupList(); if ($ret['error_code'] == 0) { $grouplist = $ret['result']['group_id_list']; if (in_array($groupname, $grouplist)) { return $groupname; }else{ $ret = $client->groupAdd($groupname); if ($ret['error_code'] == 0) { return $groupname; }else{ return false; } } }else{ return false; } }