springboot项目百度人脸识别工具类
·
springboot项目使用百度人脸识别
整体思路
通过注入application.yml文件中的百度人脸识别 API 密钥信息,初始化客户端,并提供一个静态方法,接收两张 Base64 格式的人脸图片数据,调用百度人脸对比接口,返回两张人脸的相似度得分。
pom.xml
<!-- 人脸识别 jdk-->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.16.7</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</exclusion>
</exclusions>
</dependency>
application.yml
#百度人脸识别配置
baidu:
face:
appId: "12********5"
apiKey: "K********************Ks"
secretKey: "GSm0********************5PK"
工具类
package com.common.util;
import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
@Component
@Slf4j
public class BaiduFaceUtils {
public static String APP_ID;
public static String API_KEY;
public static String SECRET_KEY;
@Value("${baidu.face.appId}")
private String appId;
@Value("${baidu.face.apiKey}")
private String apiKey;
@Value("${baidu.face.secretKey}")
private String secretKey;
// Bean初始化后执行(此时appId/apiKey/secretKey已从配置文件注入)
@PostConstruct
public void init() {
this.APP_ID = appId;
this.API_KEY = apiKey;
this.SECRET_KEY = secretKey;
}
public static Integer faceCompare(String image1, String image2) {
// 1. 创建百度人脸客户端实例(传入密钥信息)
AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
// 2. 设置客户端超时时间:连接超时2秒,读写超时60秒
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000);
// 3. 构造人脸对比请求列表:封装两张Base64格式的图片
ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
requests.add(new MatchRequest(image1, "BASE64"));
requests.add(new MatchRequest(image2, "BASE64"));
// 4. 调用百度人脸对比接口,获取返回结果(JSON格式)
JSONObject jsonObject = client.match(requests);
if (jsonObject != null && jsonObject.getInt("error_code") == 0) {
JSONObject result = jsonObject.getJSONObject("result");
if (result != null ) {
// 提取相似度得分(范围0-100,得分越高,人脸越相似)
return result.getInt("score");
}
}
return 0;
}
}
业务中使用
// 假设image1Base64、image2Base64是两张人脸的Base64字符串(无前缀)
Integer score = BaiduFaceUtils.faceCompare(image1Base64, image2Base64);
if (score > 80) { // 一般80分以上认为是同一个人
System.out.println("人脸匹配成功,相似度:" + score);
} else {
System.out.println("人脸匹配失败,相似度:" + score);
}
更多推荐



所有评论(0)