当前位置:网站首页>百度云人脸识别
百度云人脸识别
2022-07-27 00:14:00 【L1569850979】
百度人脸识别(这是是使用的v3版本)
业务需求:创建一个主题,一个主题下有多个活动,用户只要在主题上报名了就可以在多个活动下进行签到,这里采用的是人脸签到(可以用户自己人脸签到,也可以工作人员帮忙拍摄签到),用户报名的就将人脸信息录入进入百度云的人脸库中,签到的时候去百度云人脸库中找,如果找到就可以签到,没有找到则不能签到。
jar包引入
<!-- 百度云 -->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.15.8</version>
<exclusions>
<exclusion>
<artifactId>slf4j-simple</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
百度云工具类
import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.benwunet.sign.enums.*;
import com.benwunet.sign.pojo.face.FaceInfo;
import com.benwunet.sign.pojo.face.FaceResult;
import com.benwunet.sign.pojo.face.ImageU;
import com.wencoder.core.exec.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
/** * @author lilinchun * @date 2022/7/21 0021 14:07 */
@Service
@Slf4j
public class FaceService {
private static final Logger logger = LoggerFactory.getLogger("百度API接口请求结果解析");
private static AipFace aipFace;
@Value("${face.appId}")
public String APP_ID;
@Value("${face.appKey}")
private String APP_KEY;
@Value("${face.secretKey}")
private String SECRET_KEY;
@Bean
public AipFace service() {
aipFace = new AipFace(APP_ID, APP_KEY, SECRET_KEY);
aipFace.setConnectionTimeoutInMillis(2000);
aipFace.setSocketTimeoutInMillis(60000);
return aipFace;
}
/** * 人脸识别 * @param image * @return */
public FaceResult faceDetect(String image) {
int i = image.indexOf("base64,");
if (i != -1) {
image = image.substring(i + 7);
}
// image = image.replace("data:image/png;base64,", "");
HashMap<String, String> options = new HashMap<String, String>();
options.put("face_field", "age");
options.put("max_face_num", "120");
options.put("face_type", "LIVE");
// 人脸检测
JSONObject res = aipFace.detect(image, "BASE64", options);
return isSuccess(res);
}
public FaceResult isSuccess(JSONObject res) {
FaceResult result = parseJsonObject(res);
if (!result.isSuccess()) {
// 对错误进行分类
ErrorEnum errorEnum = ErrorEnum.getInstance(result.getErrorCode());
if (errorEnum == null) {
logger.error("百度接口请求失败" + result.getErrorMsg());
errorEnum = ErrorEnum.ERROR_ENUM_1;
}
BusinessException businessException = BusinessException.busExp(errorEnum.getCnDesc());
businessException.setCode(errorEnum.getErrorCode());
throw businessException;
}
return result;
}
/** * 人脸对比 * * @param imageU1 * @param imageU2 */
public int faceMatchScore(ImageU imageU1, ImageU imageU2) {
MatchRequest req1 = new MatchRequest(imageU1.getData(), imageU1.getImageType());
MatchRequest req2 = new MatchRequest(imageU2.getData(), imageU2.getImageType());
ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
requests.add(req1);
requests.add(req2);
JSONObject res = aipFace.match(requests);
FaceResult result = isSuccess(res);
// 对结果进行特殊处理
Integer score = result.getData().getInteger(FaceConstant.SCORE);
return score == null ? 0 : score;
}
/** * 解析JsonObject * * @return */
private FaceResult parseJsonObject(JSONObject res) {
FaceResult faceResult = FaceResult.builder().build();
try {
String logId = res.has(FaceConstant.LOG_ID) ? res.get(FaceConstant.LOG_ID).toString() : "0";
int errorCode = res.has(FaceConstant.ERROR_CODE) ? res.getInt(FaceConstant.ERROR_CODE) : -1;
String errorMsg = res.has(FaceConstant.ERROR_MSG) ? res.getString(FaceConstant.ERROR_MSG) : "";
int cached = res.has(FaceConstant.CACHED) ? res.getInt(FaceConstant.CACHED) : 0;
long timestamp = res.has(FaceConstant.TIMESTAMP) ? res.getLong(FaceConstant.TIMESTAMP) : 0;
Object dataString = res.has(FaceConstant.RESULT) ? res.get(FaceConstant.RESULT) : "";
com.alibaba.fastjson.JSONObject data = null;
if (dataString != null) {
data = com.alibaba.fastjson.JSONObject.parseObject(dataString.toString());
}
faceResult.setLogId(logId);
faceResult.setErrorCode(errorCode);
faceResult.setErrorMsg(errorMsg);
faceResult.setCached(cached);
faceResult.setTimestamp(timestamp);
faceResult.setData(data);
} catch (Exception e) {
logger.error("JSONObject解析失败", e);
}
return faceResult;
}
/** * 人脸注册 */
public FaceResult faceRegister(FaceInfo faceInfo) {
// 传入可选参数调用接口
HashMap<String, String> options = new HashMap<String, String>();
// 图片质量
options.put("quality_control", QualityControlEnum.LOW.name());
// 活体检测控制
options.put("liveness_control", LivenessControlEnum.NONE.name());
// 操作方式
options.put("action_type", ActionTypeEnum.REPLACE.name());
// 人脸注册
JSONObject res = aipFace.addUser(faceInfo.getImage(), faceInfo.getImageType(), faceInfo.getGroupId(), faceInfo.getUserId(), options);
log.info("人脸注册成功");
return isSuccess(res);
}
/** * 人脸删除 * * @param userId * @param groupId * @param faceToken */
public FaceResult faceDelete(String userId, String groupId, String faceToken) {
// 传入可选参数调用接口
HashMap<String, String> options = new HashMap<String, String>();
// 人脸删除
JSONObject res = aipFace.faceDelete(userId, groupId, faceToken, options);
return isSuccess(res);
}
/** * 人脸更新 * * @param faceInfo */
public FaceResult faceUpdate(FaceInfo faceInfo) {
// 传入可选参数调用接口
HashMap<String, String> options = new HashMap<String, String>();
// 图片质量
options.put("quality_control", QualityControlEnum.LOW.name());
// 活体检测控制
options.put("liveness_control", LivenessControlEnum.NONE.name());
// 操作方式
options.put("action_type", ActionTypeEnum.REPLACE.name());
// 人脸更新
JSONObject res = aipFace.updateUser(faceInfo.getImage(), faceInfo.getImageType(), faceInfo.getGroupId(), faceInfo.getUserId(), options);
return isSuccess(res);
}
/** * 创建用户组 * * @param groupId */
public FaceResult addGroup(String groupId) {
HashMap<String, String> options = new HashMap<String, String>();
// 创建用户组
JSONObject res = aipFace.groupAdd(groupId, options);
log.info("创建用户组 {}", res.toString(2));
return isSuccess(res);
}
/** * 人脸搜索 * * @param groupIds * @param imageU */
public FaceResult faceSearch(String groupIds, ImageU imageU) {
HashMap<String, String> options = new HashMap<String, String>();
options.put("max_face_num", "1");
options.put("max_user_num", "1");
options.put("quality_control", QualityControlEnum.LOW.name());
options.put("liveness_control", LivenessControlEnum.NONE.name());
// 人脸搜索
JSONObject res = aipFace.search(imageU.getData(), imageU.getImageType(), groupIds, options);
return isSuccess(res);
}
/** * 删除用户组 * * @param groupId */
public FaceResult deleteGroup(String groupId) {
HashMap<String, String> options = new HashMap<String, String>();
// 删除用户组
JSONObject res = aipFace.groupDelete(groupId, options);
log.info("删除用户组 {}", res.toString(2));
return isSuccess(res);
}
}
import lombok.Data;
import java.io.Serializable;
/** * 图像对象 */
@Data
public class ImageU implements Serializable {
private static final long serialVersionUID = -5979190946797896926L;
private String imageType;
private String data;
public ImageU(String imageType, String data) {
this.imageType = imageType;
this.data = data;
}
}
import io.swagger.annotations.ApiModel;
import lombok.Data;
import java.io.Serializable;
/** * @author lilinchun * @date 2022/7/21 0021 10:44 */
@Data
@ApiModel
public class FaceInfo implements Serializable {
/** * 图片 */
private String image;
/** * 图片类型:BASE64,URL,FACE_TOKEN */
private String imageType;
/** * 用户组id(这里是活动id) */
private String groupId;
/** * 用户id(我们项目是使用的mobile作为用户识别信息) */
private String userId;
}
/** * 操作方式 */
public enum ActionTypeEnum {
/** * 操作方式 */
APPEND("重复注册"),
REPLACE("会用新图替换");
ActionTypeEnum(String desc){
this.desc = desc;
}
private String desc;
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
/** * @description 百度接口错误码,还需要加CODE看官方文档 **/
public enum ErrorEnum {
/** * 百度云错误异常信息 */
ERROR_ENUM_1(1, "Unknown error", "服务器内部错误,请再次请求"),
ERROR_ENUM_13(13, "Get service token failed", "获取token失败"),
ERROR_ENUM_222202(222202, "pic not has face", "图片中没有人脸"),
ERROR_ENUM_222203(222203, "image check fail", "无法解析人脸"),
ERROR_ENUM_222207(222207, "match user is not found", "未找到匹配的用户"),
ERROR_ENUM_222209(222209, "face token not exist", "face token不存在"),
ERROR_ENUM_222301(222301, "get face fail", "获取人脸图片失败"),
ERROR_ENUM_223102(223102, "user is already exist", "该用户已存在"),
ERROR_ENUM_223106(223106, "face is not exist", "该人脸不存在"),
ERROR_ENUM_223113(223113, "face is covered", "人脸模糊"),
ERROR_ENUM_223114(223114, "face is fuzzy", "人脸模糊"),
ERROR_ENUM_223115(223115, "face light is not good", "人脸光照不好"),
ERROR_ENUM_223116(223116, "incomplete face", "人脸不完整"),
;
ErrorEnum(int errorCode, String desc, String cnDesc){
this.errorCode = errorCode;
this.desc = desc;
this.cnDesc = cnDesc;
}
private int errorCode;
private String desc;
private String cnDesc;
public static ErrorEnum getInstance(int errorCode){
for (ErrorEnum value : values()) {
if (value.errorCode == errorCode){
return value;
}
}
return null;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getCnDesc() {
return cnDesc;
}
public void setCnDesc(String cnDesc) {
this.cnDesc = cnDesc;
}
}
/** * 活体检测控制 * */
public enum LivenessControlEnum {
/** * 活体检测控制 */
NONE("不进行控制"),
LOW("较低的活体要求(高通过率 低攻击拒绝率)"),
NORMAL("一般的活体要求(平衡的攻击拒绝率, 通过率)"),
HIGH("较高的活体要求");
LivenessControlEnum(String desc) {
this.desc = desc;
}
private String desc;
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
这是使用的百度云的企业版
边栏推荐
- Interview shock 68: why does TCP need three handshakes?
- 云开发寝适闹钟微信小程序源码
- #博客大赛# 斗胆尝试浅入门之BAC
- 基于GoLang实现API短信网关
- C language program compilation (preprocessing)
- [redis] five common data types
- ArduinoUNO驱动RGB模块全彩效果示例
- Getlocation:fail the API need to be declared in the requiredprivateinfo field in app.json
- [Ryu] common problems and solutions in installing Ryu
- 数据资产管理的概念
猜你喜欢

OD-Paper【3】:Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks

Greed - 376. Swing sequence

使用 WebSocket 实现一个网页版的聊天室(摸鱼更隐蔽)

CS224W fall 1.2 Applications of Graph ML

【Redis】快速入门

杀毒软件 clamav 的安装和使用

c语言:深度学习递归

JMeter interface test, quickly complete a single interface request

iNFTnews | “流量+体验”白衬e数字时装节引领数字时装新变迁

Kubernetes Dashboard 部署应用以及访问
随机推荐
无效的目标发行版:17 的解决办法
Turn: YuMinHong: what hinders your growth is yourself
Okaleido tiger is about to log in to binance NFT in the second round, which has aroused heated discussion in the community
Invalid target distribution: solution for 17
Rust Web(一)—— 自建TCP Server
swiperjs自定义宽度
Arduino UNO +74hc164 water lamp example
Favicon web page collection icon online production PHP website source code /ico image online generation / support multiple image format conversion
bp 插件临时代码记录
Go to export excel form
Rust web (I) -- self built TCP server
哈希表与一致性哈希的原理理解以及应用
"Software testing" packaging resume directly improves the pass rate from these points
F8 catch traffic, F9 catch rabbits, f10turttle
Information collection port scanning tool nmap instructions
Manually build ABP framework from 0 -abp official complete solution and manually build simplified solution practice
[NISACTF 2022]上
次轮Okaleido Tiger即将登录Binance NFT,引发社区热议
系统安全测试要怎么做,详细来说说
手动从0搭建ABP框架-ABP官方完整解决方案和手动搭建简化解决方案实践