百度API Java-SDK人脸对比的使用

人脸对比是用来判断两张图片里的人是不是同一个人的应用

1.首先使用百度API之前,我们需要去创建自己的百度应用

首先进入百度AI开放平台https://ai.baidu.com/track=cp:ainsem|pf:pc|pp:tongyong-pinpai|pu:pinpai-baidurengongzhineng|ci:|kw:10003820

1.1 首先进入控制台

首先进入控制台

1.2 点击后登录自己的百度账号(没有的去注册啊= =)

在这里插入图片描述

1.3 进去之后点击人脸识别

在这里插入图片描述

1.4 进去之后去创建自己的应用

在这里插入图片描述

1.5自己创建完后,点击第四点图片里的管理应用,就可以看到如下图所示的数据(这些数据是你后面需要的数据)

在这里插入图片描述

2.创建完应用后我们就可以写代码了(本文章基本代码都参考百度API,感兴趣的可以自己去看看,网址:https://ai.baidu.com/aidoc/FACE/8k37c1rqz#%E4%BA%BA%E8%84%B8%E5%AF%B9%E6%AF%94

2.1 文件读取工具类(主要是用来将图片转换成byte数组)
import java.io.*;

/**
 * 文件读取工具类
 */
public class FileUtil {

    /**
     * 读取文件内容,作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } 

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        } 

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流  
        FileInputStream fis = new FileInputStream(filePath);  
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];  
        // 用于保存实际读取的字节数  
        int hasRead = 0;  
        while ( (hasRead = fis.read(bbuf)) > 0 ) {  
            sb.append(new String(bbuf, 0, hasRead));  
        }  
        fis.close();  
        return sb.toString();
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }
}
2.2 Base64 工具类(将byte数组转换成Base64编码)
package boss.xtrain.common.baidu;

/**
 * Base64 工具类
 */
public class Base64Util {
    private static final char last2byte = (char) Integer.parseInt("00000011", 2);
    private static final char last4byte = (char) Integer.parseInt("00001111", 2);
    private static final char last6byte = (char) Integer.parseInt("00111111", 2);
    private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
    private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
    private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
    private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};

    public Base64Util() {
    }

    public static String encode(byte[] from) {
        StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
        int num = 0;
        char currentByte = 0;

        int i;
        for (i = 0; i < from.length; ++i) {
            for (num %= 8; num < 8; num += 6) {
                switch (num) {
                    case 0:
                        currentByte = (char) (from[i] & lead6byte);
                        currentByte = (char) (currentByte >>> 2);
                    case 1:
                    case 3:
                    case 5:
                    default:
                        break;
                    case 2:
                        currentByte = (char) (from[i] & last6byte);
                        break;
                    case 4:
                        currentByte = (char) (from[i] & last4byte);
                        currentByte = (char) (currentByte << 2);
                        if (i + 1 < from.length) {
                            currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
                        }
                        break;
                    case 6:
                        currentByte = (char) (from[i] & last2byte);
                        currentByte = (char) (currentByte << 4);
                        if (i + 1 < from.length) {
                            currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
                        }
                }

                to.append(encodeTable[currentByte]);
            }
        }

        if (to.length() % 4 != 0) {
            for (i = 4 - to.length() % 4; i > 0; --i) {
                to.append("=");
            }
        }

        return to.toString();
    }
}
2.3 人脸对比类
import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

/**
 * @author wsq
 * 用来判断两张图片里的是不是同一个人
 */
public class VerifyIdentity {

    /**
     *
     * @param filePath1
     * @param filePath2
     * @return 返回score代表人脸相似度得分(满分100)
     * @throws IOException
     * @example checkPhotos("D:/image/test.png","D:/image/test.png");
     */
    public static float checkPhotos(String filePath1,String filePath2) throws IOException {

        //先将路径上的两张图片转换为BASE64编码
        byte[] bytes1 = FileUtil.readFileByBytes(filePath1);
        byte[] bytes2 = FileUtil.readFileByBytes(filePath2);

        // 调用接口
        //"取决于image_type参数,传入BASE64字符串或URL字符串或FACE_TOKEN字符串";
        String image1 = Base64Util.encode(bytes1);
        String image2 = Base64Util.encode(bytes2);

        // image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
        MatchRequest req1 = new MatchRequest(image1, "BASE64");
        MatchRequest req2 = new MatchRequest(image2, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        requests.add(req1);
        requests.add(req2);

        JSONObject res = client.match(requests);
        System.out.println(res.toString(2));

        return Float.parseFloat(res.getJSONObject("result").get("score").toString());

    }
  
    /**
     * 百度云api_id
     */
    public final static String APP_ID = "你的APP_ID";

    /**
     * 百度云api_key
     */
    public final static String API_KEY = "你的API_KEY";

    /**
     * 百度云密匙
     */
    public final static String SECRET_KEY = "你的SECRET_KEY";

    // 初始化一个AipFace
    public static final AipFace client = new AipFace(StaticPeram.APP_ID, StaticPeram.API_KEY, StaticPeram.SECRET_KEY);

你运行后百度会给你一串JSON字符串
{
“result”: {
“score”: 100,
“face_list”: [
{“face_token”: “49e1243cd8492125829a74e73b911675”},
{“face_token”: “49e1243cd8492125829a74e73b911675”}
]
},
“log_id”: 2594550015579,
“error_msg”: “SUCCESS”,
“cached”: 0,
“error_code”: 0,
“timestamp”: 1576255614
}

里面的score代表的是人脸相似度得分,是单独只把这个score取出来返回了(因为我测试用例里是用同一张图片做对比,使用肯定是100分啦,不要在意这个数据…)

2.4 我使用的maven依赖
<!-- https://mvnrepository.com/artifact/com.baidu.aip/java-sdk -->
<dependency>
  <groupId>com.baidu.aip</groupId>
  <artifactId>java-sdk</artifactId>
  <version>4.11.3</version>
</dependency>
<!-- 引入org.json所需依赖 -->
<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20160810</version>
</dependency>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值