关键技术掌握
1.了解现有的技术以及相关代码;
2.掌握base64编码,将图片转换为base64编码字符;
3.了解Maven加载第三方库;
4.掌握界面类和监听器类知识点;
5.字符串的拆分与拼接;
一、借助百度云探索人脸识别功能
正所谓“工欲善其事,必先利其器”,在各种技术快速发展的时代,我们借助时代的力量才会成就更好的自己。
首先打开百度云注册账号,找到人脸识别板块,进去之后点击板块下的技术文档,识别到人脸对比,完成百度云平台的配置和在线调试,感受一下智能的魅力~
二、创建Maven java项目
Maven可以通过配置清单的形式加载第三方库
我们先将线上调试的代码下载下来,复制到自己的项目里,随后在技术文档里面的SDK中,下载相应的库。
okhttp3库 用于模拟浏览器发送一个请求到百度云上,再解析百度传来的json结果。
注意:
String 存储字符串的最大长度
静态加载 : 不能超过2^16
动态增长 : 上限就是数组长度最大值
示例代码如下:
s1,s2对应的省略号为图片转换后的64编码,因为过多,这里就不一一展示了。
import okhttp3*;
import org.json.JSONObject;
import java.oi.IOException;
/**
* 需要添加依赖
* <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
* <dependency>
* <groupId>com.squareup.okhttp3</groupId>
* <artifactId>okhttp</artifactId>
* <version>4.12.0</version>
* </dependency>
*/
class Sample {
public static final String API_KEY = "ELt1pYkN74Gb7yXti1152k4X";
public static final String SECRET_KEY = "8QSL4uoafWl0rmREcBsPUHvzYAIOQjp3";
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
public static String getConstant(String s1, String s2) {
StringBuilder builder = new StringBuilder();
builder.append(s1);
builder.append(s2);
return builder.toString();
}
public static void main(String[] args) throws IOException {
MediaType mediaType = MediaType.parse("application/json");
String s1 = "......"
String s2="......"
String constant = getConstant(s1, s2);
RequestBody body = RequestBody.create(mediaType,
constant);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=" +
getAccessToken())
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
String jsonString = response.body().string();
System.out.println(jsonString);
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject resultObject = jsonObject.getJSONObject("result");
double score = resultObject.getDouble("score");
System.out.println("Score: " + score);
}
/**
* 从用户的AK,SK生成鉴权签名(Access Token)
*
* @return 鉴权签名(Access Token)
* @throws IOException IO异常
*/
static String getAccessToken() throws IOException {
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType,
"grant_type=client_credentials&client_id=" + API_KEY
+ "&client_secret=" + SECRET_KEY);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/oauth/2.0/token")
.method("POST", body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
return new JSONObject(response.body().string()).getString("access_token");
}
}
三、选择文件直接转成字符串对象
因为上面的代码中图片转换为base64编码的字符串太长,影响了我们的运行速度,所以我们考虑将它直接转为base64编码的形式而不直接显示出来,Java中自带base64的库。
关键:
“[{“image_type”:“BASE64”},{“image_type”:“BASE64”}]”
“[{“image”:“iVBORw0KGgAMoAAAEpCAI…”,“image_type”:“BASE64”},{“image_type”:“BASE64”}]"
先是调用api,再是实现人脸对比,最后给出结果。
import okhttp3.*;
import org.json.JSONObject;
import java.io.IOException;
/**
* 需要添加依赖
* <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
* <dependency>
* <groupId>com.squareup.okhttp3</groupId>
* <artifactId>okhttp</artifactId>
* <version>4.12.0</version>
* </dependency>
*/
//调用API
public class API {
public static final String API_KEY = "bin5PUntOjhAIdvv5FSSkSSd";
public static final String SECRET_KEY = "eAKgXOpRDfOXahbFH1FdnzibtGVL0f59";
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
/**
* 从用户的AK,SK生成鉴权签名(Access Token)
*
* @return 鉴权签名(Access Token)
* @throws IOException IO异常
*/
static String getAccessToken() throws IOException {
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
+ "&client_secret=" + SECRET_KEY);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/oauth/2.0/token")
.method("POST", body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
return new JSONObject(response.body().string()).getString("access_token");
}
//对比人脸
public static double compareFace(String img1Base64, String img2Base64) throws
IOException {
MediaType mediaType = MediaType.parse("application/json");
String constant = "[{\"image\":\"" + img1Base64 +
"\",\"image_type\":\"BASE64\"},{\"image\":\"" + img2Base64 +
"\",\"image_type\":\"BASE64\"}]";
System.out.println(constant);
RequestBody body = RequestBody.create(mediaType, constant);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=" +
getAccessToken())
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
String jsonString = response.body().string();
System.out.println(jsonString);
//获取结果
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject resultObject = jsonObject.getJSONObject("result");
double score = resultObject.getDouble("score");
System.out.println("Score: " + score);
return score;
}
}
四、创建界面和监听器
系统结构:
(1)界面类:图片显示区域、上传和对比按钮;
(2)监听器类:上传图片按钮(将图片转为base64编码)、对比按钮(调用百度云人脸对比的API接口,将结果显示在界面上)
import javax.swing.*;
public class UI {
public void showUI() {
JFrame frame = new JFrame();
frame.setSize(1000, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
//添加按钮
JButton up1but = new JButton("上传1");
JButton up2but= new JButton("上传2");
JButton subbut = new JButton("对比");
//设置
up1but.setActionCommand("up1");
up2but.setActionCommand("up2");
subbut.setActionCommand("sub");
up1but.setBounds(150, 600, 100, 50);
subbut.setBounds(450, 600, 100, 50);
up2but.setBounds(750, 600, 100, 50);
frame.add(up1but);
frame.add(up2but);
frame.add(subbut);
frame.setVisible(true);
FaceListener faceListener = new FaceListener();
up1but.addActionListener(faceListener);
up2but.addActionListener(faceListener);
subbut.addActionListener(faceListener);
faceListener.gr = frame.getGraphics();
}
public static void main(String[] args) {
UI ui = new UI();
ui.showUI();
}
}
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.Base64;
public class FaceListener implements ActionListener {
String encoded1;
String encoded2;
Graphics gr;
String click = "";
public void drawImage(File file, int x, int y) {
BufferedImage image = null;
try {
image = ImageIO.read(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
gr.drawImage(image, x, y, 300, 400, null);
}
@Override
public void actionPerformed(ActionEvent e) {
click = e.getActionCommand();
System.out.println(e.getActionCommand());
if (click.equals("up1")) {
encoded1 = getImageBase64();
} else if (click.equals("up2")) {
encoded2 = getImageBase64();
} else if (click.equals("sub")) {
try {
double score = API.compareFace(encoded1, encoded2);
if (score >= 70) {
JOptionPane.showMessageDialog(null, "匹配成功 分数:" + score);
} else {
JOptionPane.showMessageDialog(null, "匹配失败 分数:" + score);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
public String getImageBase64() {
JFileChooser chooser = new JFileChooser();
int openDialog = chooser.showOpenDialog(null);
if (openDialog == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
if (click.equals("up1")) {
drawImage(file, 100, 100);
} else {
drawImage(file, 600, 100);
}
try (FileInputStream fileInputStream = new FileInputStream(file)) {
byte[] fileContent = new byte[(int) file.length()];
fileInputStream.read(fileContent);
// 编码
String encoded = Base64.getEncoder().encodeToString(fileContent);
System.out.println("Encoded: " + encoded);
return encoded;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}
五、最终效果图


今日分享结束啦~
1022

被折叠的 条评论
为什么被折叠?



