最近学习了人脸识别,就是判断某个图片是否存在人脸,此次实现功能是,如果此图片存在一张人脸,则存入数据,多张人脸或无人脸均返回人脸过多或人脸不存在。
首先使用百度云,并在小程序中关联上百度云账号,在百度云中找到人脸识别功能,通过API Key 和Secret Key 来初始化人脸识别,代码如下
private function init_face(){
$app_id = '';
$app_key = '';
$secret_key = '';
$dir = APP_PATH .'/face_sdk/';
require_once $dir .'AipFace.php';
return new \AipFace($app_id,$app_key,$secret_key);
}
检查图片是否存在,代码如下
$file='';
if(!file_exists($file)){
die('文件不存在');
}
下面是识别人脸的代码
$image= base64_encode(file_get_contents($file));
$options=array();
$options['max_face_num']=2;
$client=$this->init_face();
$ret=$client->detect($image,'BASE64',$options);
// echo $ret;
// exit;
if($ret['error_code']==0){
// echo $ret['error_code'];
//有人脸
$result=$ret['result'];
$face_num=$result['face_num'];
if(1==$face_num){
//人脸数为1
$face_probability=$result['face_list'][0]['face_probability'];
if(1==$face_probability){
//可靠性为1
$guid=myguid();
$group=$this->face_group();
$client->addUser($image,'BASE64',$group,$guid);
echo '人脸检测完成,并已入库';
}else{
die('人脸为'.$face_probability);
}
}else{
die('人脸数量大于1');
}
}else{
die('没有人脸');
}
guid和myguid需要定义在function中代码如下
//生成guid
function guid(){
if(function_exists('com_create_guid')){
return com_create_guid();
}else{
mt_srand((double)microtime()*10000);
$charid=strtoupper(md5(uniqid(rand(),true)));
$hyphen=chr(45);
$uuid=chr(123)
.substr($charid,0,8).$hyphen
.substr($charid,8,4).$hyphen
.substr($charid,12,4).$hyphen
.substr($charid,16,4).$hyphen
.substr($charid,20,12)
.chr(125);
return $uuid;
}
}
//生成变种guid
function myguid(){
$guid=guid();
$guid=trim($guid,'{}');
$guid=str_replace('-', '_',$guid);
return $guid;
}