当前位置:网站首页>Baidu cloud face recognition
Baidu cloud face recognition
2022-07-27 03:07:00 【L1569850979】
Baidu face recognition ( This is used v3 edition )
Business needs : Create a theme , There are multiple activities under a theme , As long as users sign up on the theme, they can sign in under multiple activities , Face check-in is used here ( Users can sign in with their own faces , Staff can also help shoot and sign in ), Users who sign up will enter face information into Baidu cloud face database , When checking in, go to Baidu cloud face database to find , If you find it, you can sign in , If you don't find it, you can't sign in .
jar Package introduction
<!-- Baidu cloud -->
<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>
Baidu cloud tools 
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(" Baidu API Interface request result parsing ");
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;
}
/** * Face recognition * @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");
// Face detection
JSONObject res = aipFace.detect(image, "BASE64", options);
return isSuccess(res);
}
public FaceResult isSuccess(JSONObject res) {
FaceResult result = parseJsonObject(res);
if (!result.isSuccess()) {
// Classify errors
ErrorEnum errorEnum = ErrorEnum.getInstance(result.getErrorCode());
if (errorEnum == null) {
logger.error(" Baidu interface request failed " + result.getErrorMsg());
errorEnum = ErrorEnum.ERROR_ENUM_1;
}
BusinessException businessException = BusinessException.busExp(errorEnum.getCnDesc());
businessException.setCode(errorEnum.getErrorCode());
throw businessException;
}
return result;
}
/** * Face comparison * * @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);
// Special treatment of the results
Integer score = result.getData().getInteger(FaceConstant.SCORE);
return score == null ? 0 : score;
}
/** * analysis 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 Parse failure ", e);
}
return faceResult;
}
/** * Face registration */
public FaceResult faceRegister(FaceInfo faceInfo) {
// Passing in optional parameters to call the interface
HashMap<String, String> options = new HashMap<String, String>();
// Picture quality
options.put("quality_control", QualityControlEnum.LOW.name());
// Vivisection control
options.put("liveness_control", LivenessControlEnum.NONE.name());
// Mode of operation
options.put("action_type", ActionTypeEnum.REPLACE.name());
// Face registration
JSONObject res = aipFace.addUser(faceInfo.getImage(), faceInfo.getImageType(), faceInfo.getGroupId(), faceInfo.getUserId(), options);
log.info(" Face registration succeeded ");
return isSuccess(res);
}
/** * Face delete * * @param userId * @param groupId * @param faceToken */
public FaceResult faceDelete(String userId, String groupId, String faceToken) {
// Passing in optional parameters to call the interface
HashMap<String, String> options = new HashMap<String, String>();
// Face delete
JSONObject res = aipFace.faceDelete(userId, groupId, faceToken, options);
return isSuccess(res);
}
/** * Face update * * @param faceInfo */
public FaceResult faceUpdate(FaceInfo faceInfo) {
// Passing in optional parameters to call the interface
HashMap<String, String> options = new HashMap<String, String>();
// Picture quality
options.put("quality_control", QualityControlEnum.LOW.name());
// Vivisection control
options.put("liveness_control", LivenessControlEnum.NONE.name());
// Mode of operation
options.put("action_type", ActionTypeEnum.REPLACE.name());
// Face update
JSONObject res = aipFace.updateUser(faceInfo.getImage(), faceInfo.getImageType(), faceInfo.getGroupId(), faceInfo.getUserId(), options);
return isSuccess(res);
}
/** * Create user group * * @param groupId */
public FaceResult addGroup(String groupId) {
HashMap<String, String> options = new HashMap<String, String>();
// Create user group
JSONObject res = aipFace.groupAdd(groupId, options);
log.info(" Create user group {}", res.toString(2));
return isSuccess(res);
}
/** * Face search * * @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());
// Face search
JSONObject res = aipFace.search(imageU.getData(), imageU.getImageType(), groupIds, options);
return isSuccess(res);
}
/** * Delete user group * * @param groupId */
public FaceResult deleteGroup(String groupId) {
HashMap<String, String> options = new HashMap<String, String>();
// Delete user group
JSONObject res = aipFace.groupDelete(groupId, options);
log.info(" Delete user group {}", res.toString(2));
return isSuccess(res);
}
}
import lombok.Data;
import java.io.Serializable;
/** * Image object */
@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 {
/** * picture */
private String image;
/** * Picture type :BASE64,URL,FACE_TOKEN */
private String imageType;
/** * User group id( This is the event id) */
private String groupId;
/** * user id( Our project uses mobile As user identification information ) */
private String userId;
}
/** * Mode of operation */
public enum ActionTypeEnum {
/** * Mode of operation */
APPEND(" Duplicate registration "),
REPLACE(" Will replace with a new figure ");
ActionTypeEnum(String desc){
this.desc = desc;
}
private String desc;
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
/** * @description Baidu interface error code , It needs to be added CODE Look at the official documents **/
public enum ErrorEnum {
/** * Baidu cloud error exception information */
ERROR_ENUM_1(1, "Unknown error", " Server internal error , Please ask again "),
ERROR_ENUM_13(13, "Get service token failed", " obtain token Failure "),
ERROR_ENUM_222202(222202, "pic not has face", " There is no face in the picture "),
ERROR_ENUM_222203(222203, "image check fail", " Unable to parse face "),
ERROR_ENUM_222207(222207, "match user is not found", " No matching user found "),
ERROR_ENUM_222209(222209, "face token not exist", "face token non-existent "),
ERROR_ENUM_222301(222301, "get face fail", " Failed to get face image "),
ERROR_ENUM_223102(223102, "user is already exist", " The user already exists "),
ERROR_ENUM_223106(223106, "face is not exist", " The face does not exist "),
ERROR_ENUM_223113(223113, "face is covered", " Face blur "),
ERROR_ENUM_223114(223114, "face is fuzzy", " Face blur "),
ERROR_ENUM_223115(223115, "face light is not good", " The face is not well illuminated "),
ERROR_ENUM_223116(223116, "incomplete face", " 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;
}
}
/** * Vivisection control * */
public enum LivenessControlEnum {
/** * Vivisection control */
NONE(" No control "),
LOW(" Lower living requirements ( High pass rate Low attack rejection rate )"),
NORMAL(" General living requirements ( Balanced attack rejection rate , Passing rate )"),
HIGH(" Higher living requirements ");
LivenessControlEnum(String desc) {
this.desc = desc;
}
private String desc;
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
This is the enterprise version of Baidu cloud 
边栏推荐
- [二分查找简单题] LeetCode 35. 搜索插入位置,69. x 的平方根,367. 有效的完全平方数,441. 排列硬币
- Which securities firm is safer to open an account and buy REITs funds?
- Cs224w fall course - --- 1.1 why graphs?
- [binary search simple question] leetcode 35. search insertion position, 69. Square root of X, 367. Effective complete square, 441. Arrange coins
- 数据资产管理的概念
- 一个测试类了解BeanUtils.copyProperties
- Kubeadmin到底做了什么?
- 毕业2年转行软件测试获得12K+,不考研月薪过万的梦想实现了
- [哈希表] 刷题合集
- Is the low commission account opening of Galaxy Securities Fund reliable, reliable and safe
猜你喜欢
随机推荐
MarqueeView实现滑动展示效果
Cuteone: a onedrive multi network disk mounting program / with member / synchronization and other functions
[二分查找简单题] LeetCode 35. 搜索插入位置,69. x 的平方根,367. 有效的完全平方数,441. 排列硬币
我的爬虫笔记(七) 通过爬虫实现blog访问量+1
关于url编解码应该选用的函数
[动态规划中等题] LeetCode 198. 打家劫舍 740. 删除并获得点数
使用 WebSocket 实现一个网页版的聊天室(摸鱼更隐蔽)
2513: 小勇学分数(公约数问题)
Getlocation:fail the API need to be declared in the requiredprivateinfo field in app.json
[栈和队列简单题] LeetCode 232. 用栈实现队列,225. 用队列实现栈
Why do people like to rank things
ansible系列之:不收集主机信息 gather_facts: False
Static keyword
[binary search simple question] leetcode 35. search insertion position, 69. Square root of X, 367. Effective complete square, 441. Arrange coins
[redis] five common data types
一道数学题,让芯片巨头亏了5亿美金!
Shell 分析日志文件命令全面总结
Information collection port scanning tool nmap instructions
Arduino UNO +74HC164流水灯示例
对象创建的流程分析









