java调用百度人脸识别(已测试)

有成品和配套论文( 口 182480171)

由于电脑人脸签到的项目比较急,所以花了45分下载了【SSM调用百度人脸识别demo】。结果下载下来没啥了用,最后还是花了时间去解决,为了方便后来者。特把代码贴上

有疑问可站内消息我

目标效果:path1和path2的图片进行对比(这里为了简化,设置同一个图片,期望识别结果100分)

百度提示(80分就算同一人)

运行后结果:

{"error_code":0,"error_msg":"SUCCESS","log_id":12019494001,"timestamp":1602949391,"cached":0,"result":{"score":100,"face_list":[{"face_token":"19d4a0a9588f186f19ee0206c9b184ca"},{"face_token":"19d4a0a9588f186f19ee0206c9b184ca"}]}}
 

符合期望

代码中红色部分,需要自己去申请百度账号key

具体参见:

https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjgn3#2-%E5%88%9B%E5%BB%BA%E5%BA%94%E7%94%A8


import com.baidu.ai.aip.utils.Base64Util;
import com.baidu.ai.aip.utils.HttpUtil;
import com.baidu.ai.aip.utils.GsonUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
* 人脸对比
*/
public class FaceMatch {
    public static String faceMatch() {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
        try {
            String path1 = "D:/a1/1.jpg";
            String path2 = "D:/a1/1.jpg";
            Map map1 =  new HashMap();  
            map1.put("image", ImageToBase64(path1));  
            map1.put("image_type", "BASE64");
            map1.put("face_type", "LIVE");
            map1.put("quality_control", "LOW");
            map1.put("liveness_control", "HIGH");
            
            Map map2 =  new HashMap();  
            map2.put("image", ImageToBase64(path2));  
            map2.put("image_type", "BASE64");
            map2.put("face_type", "LIVE");
            map2.put("quality_control", "LOW");
            map2.put("liveness_control", "HIGH");
            
            List s = new ArrayList();
            s.add(map1);
            s.add(map2);
            String param = GsonUtils.toJson(s);
            System.out.println(param);

            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = new AuthService().getAuth();//"[调用鉴权接口获取的token]";

            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        FaceMatch.faceMatch();
    }
    
    private static String ImageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        Base64Util encoder = new Base64Util();
        // 返回Base64编码过的字节数组字符串
        String s = encoder.encode(Objects.requireNonNull(data));
        System.out.println("本地图片转换Base64:" + s);
        return s;
    } 
}

 

~~~~


import org.json.JSONObject;

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 {
    public static void main(String[] args){
        System.out.print(getAuth());
    }
    public static String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = " API Key";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "Secret Key ";
        return getAuth(clientId, clientSecret);
    }


    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;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值