package com;
import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.baidu.aip.util.Base64Util;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Scanner;
public class FaceCompare {
//设置APPID/AK/SK
public static final String APP_ID = "25283311";
public static final String API_KEY = "BXyugdVgLebW6AFqmouB5UUA";
public static final String SECRET_KEY = "lU5YkbFD2hvIkQHF5BKxw29UhtCjmza3";
public static void main(String[] args) {
// 初始化一个AipFace
AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
// 可选:设置网络连接参数
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000);
getFTF(client);
}
//将图片路径转为byte数组
public static byte[] imgTByte(String src){
FileInputStream file;
byte[] bytes = null;
try {
file = new FileInputStream(new File(src));
bytes = new byte[file.available()];
file.read(bytes);
file.close();
}catch (Exception e){
e.printStackTrace();
}
return bytes;
}
//人脸对比sdk
public static void getFTF(AipFace client) {
String image1 = "";
String image2 = "";
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一张图片的路径:");
image1 = scanner.nextLine();
System.out.print("请输入第二张图片的路径:");
image2 = scanner.nextLine();
File file1 = new File(image1);
File file2 = new File(image1);
boolean flag1 = file1.exists();
boolean flag2 = file2.exists();
boolean flag3 = image1.endsWith(".png") || image1.endsWith(".jpg");
boolean flag4 = image2.endsWith(".png") || image2.endsWith(".jpg");
while (!(flag1 && flag2) || !(flag3 && flag4)){
System.out.print("图片不存在或者文件格式不对,请重新输入第一张图片的路径:");
image1 = scanner.nextLine();
System.out.print("图片不存在或者文件格式不对,请重新输入第二张图片的路径:");
image2 = scanner.nextLine();
file1 = new File(image1);
file2 = new File(image1);
flag1 = file1.exists();
flag2 = file2.exists();
flag3 = image1.endsWith(".png") || image1.endsWith(".jpg");
flag4 = image2.endsWith(".png") || image2.endsWith(".jpg");
}
//讲输入的url转为byte数组再转为Base4
String bs1 = Base64Util.encode(imgTByte(image1));
String bs2 = Base64Util.encode(imgTByte(image2));
// image1/image2也可以为url或facetoken, 相应的imageType参数需要与之对应。
MatchRequest req1 = new MatchRequest(bs1, "BASE64");
MatchRequest req2 = new MatchRequest(bs2, "BASE64");
ArrayList requests = new ArrayList();
requests.add(req1);
requests.add(req2);
JSONObject res = client.match(requests);
System.out.println(res.toString(2));
System.out.println("============================");
JSONObject result = res.getJSONObject("result");
float score = result.getFloat("score");
if (score>90){
System.out.println("两个人的相似度为:"+score+",是同一个人");
}
if (score<90){
System.out.println("两个人的相似度为:"+score+",不是同一个人");
}
}
}