face++人脸识别工具

package org.example.cropland.Utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class face {
    
    public static String authentication(String faceset_token,String imageBase64,String apiSecret,String apiKey,String face_tokens) throws IOException {
        //获取face_token
        String detect = detect(apiKey, apiSecret, "E:\\demo\\cropland\\src\\main\\resources\\static\\image\\1.jpg");
        String face_token = detect.split("face_token\":\"")[1].split("\"")[0];
        if (face_tokens.split(",").length < 5) {
            face_tokens = face_tokens + "," + face_token;
        }else{
            face_tokens = face_token;
        }
        //添加token到集合中
        String s = addFaceToken(apiKey, apiSecret, faceset_token, face_tokens);
        //从前端获取图片数据进行识别
        String result = sendPostRequest(apiKey, apiSecret, imageBase64,faceset_token);
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray resultsArray = jsonObject.getJSONArray("results");
        if (resultsArray != null && !resultsArray.isEmpty()) {
            JSONObject resultObject = resultsArray.getJSONObject(0);
            double confidence = resultObject.getDoubleValue("confidence");
            System.out.println("Confidence: " + confidence);
            if (confidence>60){
                return "识别成功";
            }else{
               return "识别失败";
            }
        } else {
            return "识别失败";
        }
    }
    
    public static String createFaceset(String apiKey, String apiSecret, String displayName) {
        String apiUrl = "https://api-cn.faceplusplus.com/facepp/v3/faceset/create";
        // 构造请求参数
        Map<String, String> params = new HashMap<>();
        params.put("api_key", apiKey);
        params.put("api_secret", apiSecret);
        params.put("display_name", displayName);

        StringBuilder response = new StringBuilder();
        try {
            // 创建 URL 对象
            URL url = new URL(apiUrl);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为 POST
            connection.setRequestMethod("POST");
            // 启用输入输出
            connection.setDoInput(true);
            connection.setDoOutput(true);

            // 构造请求参数字符串
            StringBuilder paramsStr = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (paramsStr.length() > 0) {
                    paramsStr.append("&");
                }
                paramsStr.append(entry.getKey()).append("=").append(entry.getValue());
            }

            // 将参数字符串写入请求
            connection.getOutputStream().write(paramsStr.toString().getBytes());

            // 获取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 关闭连接
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 解析响应获取 faceset_token
        String jsonResponse = response.toString();
        // 这里需要根据具体响应内容来解析得到 faceset_token
        // 假设响应是 JSON 格式的,可以使用 JSON 解析库来解析
        // 这里简单处理,假设返回的 JSON 格式为 {"faceset_token": "YOUR_FACESET_TOKEN"}
        System.out.println(jsonResponse);
        String facesetToken = jsonResponse.split("\"")[3];
        return facesetToken;
    }

    public static String imageToBase64(String imagePath) {
        String base64Image = null;
        try {
            byte[] imageData = Files.readAllBytes(new File(imagePath).toPath());
            base64Image = Base64.getEncoder().encodeToString(imageData);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return base64Image;
    }

    private static String detect(String apiKey, String apiSecret, String imagePath) throws IOException {

        String imageToBase64 = imageToBase64(imagePath);

        // 创建 HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 HttpPost 请求
        HttpPost httpPost = new HttpPost("https://api-cn.faceplusplus.com/facepp/v3/detect");

        // 构建 multipart 请求实体
        HttpEntity build = MultipartEntityBuilder.create()
                .addTextBody("api_key", apiKey)
                .addTextBody("api_secret", apiSecret)
                .addTextBody("image_base64", imageToBase64)
                .build();

        // 设置请求实体
        httpPost.setEntity(build);

        // 发送请求并获取响应
        CloseableHttpResponse execute = httpClient.execute(httpPost);
        return EntityUtils.toString(execute.getEntity());
    }

    private static String addFaceToken(String apiKey, String apiSecret, String facesetToken, String faceTokens) {
        String endpoint = "https://api-cn.faceplusplus.com/facepp/v3/faceset/addface";
        String data = "api_key=" + apiKey + "&api_secret=" + apiSecret + "&faceset_token=" + facesetToken
                + "&face_tokens=" + faceTokens;
        try {
            URL url = new URL(endpoint);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.getOutputStream().write(data.getBytes());

            StringBuilder response = new StringBuilder();
            Scanner scanner = new Scanner(conn.getInputStream());
            while (scanner.hasNextLine()) {
                response.append(scanner.nextLine());
            }
            scanner.close();
            return response.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String sendPostRequest(String apiKey, String apiSecret, String base64Image,String faceset_token) throws IOException {
        String image_base64 = base64Image.split(":\"")[1].split("\"")[0].split(",")[1];
        // 创建 HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 HttpPost 请求
        HttpPost httpPost = new HttpPost("https://api-cn.faceplusplus.com/facepp/v3/search");

        // 构建 multipart 请求实体
        HttpEntity build = MultipartEntityBuilder.create()
                .addTextBody("api_key", apiKey)
                .addTextBody("api_secret", apiSecret)
                .addTextBody("faceset_token",faceset_token)
                .addTextBody("image_base64",image_base64)
                .build();
        // 设置请求实体
        httpPost.setEntity(build);
        // 发送请求并获取响应
        CloseableHttpResponse execute = httpClient.execute(httpPost);
        return EntityUtils.toString(execute.getEntity());
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值