
调用腾讯云人脸识别API,使用php可以快速实现人脸检测、比对、搜索等功能。关键在于正确配置SDK,获取密钥,并按接口要求传递参数。
准备工作:开通服务与获取密钥
在开始前,需完成以下步骤:
- 登录腾讯云官网,开通“人脸识别”服务
- 进入访问管理(CAM),创建子账号并授予QcloudaiRecognitionFullaccess权限
- 获取SecretId和SecretKey,用于后续API鉴权
- 记录所使用的区域(Region),如ap-beijing、ap-shanghai等
安装腾讯云PHP SDK
composer require tencentcloud/tencentcloud-sdk-php
安装完成后,在项目中引入自动加载文件:
立即学习“PHP免费学习笔记(深入)”;
require ‘vendor/autoload.php’;
调用人脸检测接口示例
以下代码演示如何检测图片中的人脸信息:
use TencentCloudCommonCredential;
use TencentCloudCommonProfileClientProfile;
use TencentCloudCommonProfileHttpProfile;
use TencentCloudIaiV20200303IaiClient;
use TencentCloudIaiV20200303ModelsDetectFaceRequest;
$cred = new Credential(“你的SecretId”, “你的SecretKey”);
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint(“iai.tencentcloudapi.com”);
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new IaiClient($cred, “ap-beijing”, $clientProfile);
$req = new DetectFaceRequest();
$params = ‘{“Url”: “https://example.com/face.jpg”, “MaxFaceNum”: 1}’;
$req->fromjsonString($params);
try {
$resp = $client->DetectFace($req);
echo $resp->tojsonString();
} catch(Exception $e) {
echo “Error: ” . $e->getMessage();
}
该接口返回人脸位置、性别、年龄、表情等信息,适用于注册、验证等场景。
常见调用场景说明
除检测外,常用功能包括:
- 人脸比对(CompareFace):传入两张图,判断是否为同一人,返回相似度分值
- 人脸搜索(SearchFaces):在已有的人脸库中查找最相似的人员
- 创建人员(CreatePerson):将人脸信息加入指定人员库
所有请求均需构造对应Request对象并传入JSON参数。注意图片可使用Url或Base64编码传输,大小限制一般为5MB以内。


