使用百度人脸识别实现人脸识别后端逻辑

百度人脸识别API

https://ai.baidu.com/ai-doc/FACE/yk37c1u4t

获取access_token

由于百度API的access_token会定期更新,所以每次请求时就重新获取一个token

package com.example.emoswx.baiduFaceCheck;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * 获取token类
 */
public class AuthService {

    /**
     * 获取权限token
     * @return 返回示例:
     * {
     * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
     * "expires_in": 2592000
     * }
     */
    public static String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = "1XbaXPvpQ4n66TjhpntXa0gy";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "p5tbyEBb51pR9gRK1M9agipIpmAIrugI";
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例:
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败!");
            e.printStackTrace(System.err);
        }
        return null;
    }

}

人脸检测

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.emoswx.baiduFaceCheck.utils.HttpUtil;
import com.example.emoswx.baiduFaceCheck.utils.GsonUtils;
import com.example.emoswx.exception.EmosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


import java.util.*;


@Slf4j
@Component
public class BaiduFaceRecognition {
 /**
     * 人脸检测与属性分析,是否人脸,是否模糊
     */
    public void faceDetect(String imgParam) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect";
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("max_face_num",1);
            map.put("image_type", "BASE64");
            map.put("image", imgParam);
            map.put("face_field", "age,expression,face_shape,gender,glasses,quality,face_type");
            String param = GsonUtils.toJson(map);
            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = AuthService.getAuth();
            String result = HttpUtil.post(url, accessToken, "application/json", param);
            //result=JSONUtil.quote(result);

            JSONObject resultJson= (JSONObject) JSONUtil.parseObj(result).get("result");
            JSONObject faceListJson= JSONUtil.parseObj(JSONUtil.parseObj(resultJson, false, true).getJSONArray("face_list").get(0),false, true);
            JSONObject qualityJson= (JSONObject) faceListJson.get("quality");
            //判断是否成功
            String msg= (String) JSONUtil.parseObj(result).get("error_msg");
            if(!"SUCCESS".equals(msg)){
                log.error(msg);
                throw new EmosException(msg);
            }
            //照片的 face_token
            //String face_token= (String) faceListJson.get("face_token");
            //人脸模糊程度,范围[0~1],0表示清晰,1表示模糊
            int blur=qualityJson.getInt("blur");
            //真实人脸置信度,[0~1],大于0.5可以判断为人脸
            int human= (int) faceListJson.get("face_probability");
            //1表示人脸模糊
            if(blur==1){
                log.error("人脸模糊");
                throw new EmosException("人脸模糊");
            }
            //是否是人类的脸
            if(human==0){
                log.error("提供的人脸照片非人类的脸");
                throw new EmosException("提供的人脸照片非人类的脸");
            }
//            System.out.println("blur:"+blur);
//            System.out.println("human:"+human);
//            System.out.println(result);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new EmosException("人脸检测失败");
        }
    }
}

人脸注册

/**
     * 人脸信息入人脸库
     * @return face_token
     * imgParam:人脸base64串
     * 注册后会有生成一个face_token是永久的
     * @throws Exception
     */
    public String faceadd(String imgParam,int userId) throws Exception {
        String url="https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add"; //人脸注册链接
        Map<String, Object> map = new HashMap<>();
        map.put("group_id", "face_group");
        map.put("user_id", userId);
        map.put("image_type", "BASE64");
        map.put("image", imgParam);
        map.put("quality_control", "LOW");
        map.put("action_type","REPLACE");
        String param = GsonUtils.toJson(map);
        String accessToken = AuthService.getAuth();
        try {
            String result = HttpUtil.post(url, accessToken, "application/json",param);
            //判断是否成功
            String msg= (String) JSONUtil.parseObj(result).get("error_msg");
            if(!"SUCCESS".equals(msg)){
                log.error(msg);
                throw new EmosException(msg);
            }
            JSONObject resultJson= (JSONObject) JSONUtil.parseObj(result).get("result");
            return (String) resultJson.get("face_token");
        }
        catch (Exception e){
            log.error(e.getMessage(),e);
            throw new EmosException("人脸注册失败");
        }
    }

人脸识别 1:1

 /**
     * 人脸信息识别,判断指定人脸是否存在库中
     * @param imgParam:人脸信息,base64转码后的串
     * @return 相似度
     */
    public double facerecognition(String imgParam,int userId) {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/search";
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", imgParam);
            map.put("user_id", userId);
            map.put("group_id_list", "face_group");
            map.put("image_type", "BASE64");
            map.put("quality_control", "LOW");

            String param = GsonUtils.toJson(map);
            String accessToken = AuthService.getAuth();
            String result = HttpUtil.post(url, accessToken, "application/json", param);
            //人脸识别相似度

            JSONObject resultJson= (JSONObject) JSONUtil.parseObj(result).get("result");
            JSONObject userListJson= JSONUtil.parseObj(JSONUtil.parseObj(resultJson, false, true).getJSONArray("user_list").get(0),false, true);
            double score=userListJson.getDouble("score");
            //判断是否成功
            String msg= (String) JSONUtil.parseObj(result).get("error_msg");
            if(!"SUCCESS".equals(msg)){
                log.error(msg);
                throw new EmosException(msg);
            }

            if(score<85){
                log.error("人脸不匹配");
                throw new EmosException("人脸不匹配");
            }
            return score;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new EmosException(e.getMessage());
        }
    }

test

	@Autowired
    BaiduFaceRecognition baiduFaceRecognition;
    @Test
    void faceReconguration(){
        //人脸检测 ok
        try {
            byte[] imgData =imgData = FileUtil.readFileByBytes("E:\\AA多啦A梦的兜\\message\\大头照.jpg");
            String imgStr = Base64Util.encode(imgData);
            baiduFaceRecognition.faceDetect(imgStr);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //人脸注册 ok
        try {
            byte[] imgData =imgData = FileUtil.readFileByBytes("E:\\AA多啦A梦的兜\\message\\大头照.jpg");
            String imgStr = Base64Util.encode(imgData);
            baiduFaceRecognition.faceadd(imgStr,999);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //人脸识别 ok
        try {
            byte[] imgData =imgData = FileUtil.readFileByBytes("E:\\AA多啦A梦的兜\\message\\白底.jpg");
            String imgStr = Base64Util.encode(imgData);
            System.out.println(baiduFaceRecognition.facerecognition(imgStr, 999));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值