PHP code example of aoding9 / laravel-baidu-aip
1. Go to this page and download the library: Download aoding9/laravel-baidu-aip library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
aoding9 / laravel-baidu-aip example snippets
return [
'app_id'=>env('BAIDU_AIP_APP_ID',null),
'api_key'=>env('BAIDU_AIP_API_KEY',null),
'secret_key'=>env('BAIDU_AIP_SECRET_KEY',null),
'group_id'=>env('BAIDU_AIP_GROUP_ID',null),
];
use Aoding9\BaiduAip\BaiduAipService;
function test() {
//$aipFace = app('baiduAip')->aipFace(); // 别名
$aipFace = app(BaiduAipService::class)->aipFace();
$score = $aipFace
->matchFacesByUrl(
$url1 = 'https://pix2.tvzhe.com/thumb/star/0/221/260x346.jpg',
$url2 = 'https://n.sinaimg.cn/sinacn10114/40/w2000h2840/20190226/7aa0-htptaqe7306666.jpg'
);
dd($url1, $url2, '吴京1和吴京2相似度' . $score);
}
use Illuminate\Database\Eloquent\Model;
use Aoding9\BaiduAip\BaiduAipService;
class Staff extends Model {
/**
* @Desc 根据人脸,匹配人员model,需要提前增加用户组,并且把用户的人脸注册进去,绑定userid
* @param string $face 上传的图片url
*/
public static function getStaffByFaceImage($face): Staff {
$aipFace = app(BaiduAipService::class)->aipFace();
try {
$staffId = $aipFace->searchApi($face); // 返回用户id或null,或抛异常
$staff = Staff::findOrFail($staffId); // 未找到也抛异常
} catch (\Exception $e) {
throw new \Exception('未匹配到人员信息',$e->getCode());
}
return $staff;
}
}
// 前端上传人脸图片,根据图片地址,检索用户模型
$face = request()->input('face');
$staff = Staff::getStaffByFaceImage($face);
use Aoding9\BaiduAip\BaiduAipService;
function test() {
$aipFace = app(BaiduAipService::class)->aipFace();
// 不传参则使用env的默认用户组id
dd($aipFace->groupAddApi()); // 新增用户组
dd($aipFace->groupDeleteApi()); // 删除用户组
dd($aipFace->getGroupListApi()); // 获取用户组列表
dd($aipFace->getGroupUsersApi()); // 获取用户组的用户id列表
dd($aipFace->getUserApi(1)); // 获取根据用户id获取user_info
}
namespace App\Observers;
use App\Models\Staff;
use Aoding9\BaiduAip\BaiduAipService;
use Log;
class StaffObserver {
public $aipFace;
public function __construct() {
if (!$this->aipFace) {
$this->aipFace = app(BaiduAipService::class)->aipFace();
}
}
// 创建用户时,往用户组注册用户,并将头像添加到用户人脸库,绑定用户id(如果之前没创建用户组,需要先创建用户组),把姓名也存入user_info
public function created(Staff $model) {
$result = $this->aipFace->addUserApi($model->avatar_url, $model->id, null, null, ['user_info' => $model->name]);
Log::info('人脸注册成功:' . $model->name, $result);
}
// 头像变更时,更新用户的人脸库
public function updating(Staff $model) {
if ($model->avatar) {
$result = $this->aipFace->updateUserApi($model->avatar_url, $model->id, null, null, ['user_info' => $model->name]);
Log::info('人脸更新成功:' . $model->name, $result);
}
}
// 删除用户时,删除用户组里的用户
public function deleted(Staff $model) {
$result = $this->aipFace->deleteUserApi($model->id);
Log::info('人脸删除成功:' . $model->name, $result);
}
}