百度AI开放平台——简易人脸识别java版
程序员文章站
2022-03-25 12:23:51
...
准备工作
1、百度AI开发平台账号和人脸识别相关功能
2、一张人脸照片
流程:
1、页面调用摄像头拍照获取当前使用者照片,传入后台保存
2、利用事先保存的图片和前台传入的图片进行对比,返回一个匹配值
项目结构和代码:
- FaceMatch.java(百度AI账号配置和进行人脸匹配的类)
package home.face.controller;
import home.face.utils.Base64Util;
import home.face.utils.FileUtil;
import home.face.utils.HttpUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* 人脸对比
*/
public class FaceMatch {
/**
* 百度云AK
*/
private static final String API_KEY = "API_KEY";
/**
* 百度云SK
*/
private static final String SECRET_KEY = "SECRET_KEY";
/**
* 获取access_token的接口地址
*/
private static final String AUTH_HOST = "https://aip.baidubce.com/oauth/2.0/token?";
/**
* 进行人脸探测的接口地址
*/
private static final String DETECT_HOST = "https://aip.baidubce.com/rest/2.0/face/v3/detect";
/**
* 重要提示代码中所需工具类
* FileUtil,Base64Util,HttpUtil,GsonUtils请从
* https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
* https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
* https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
* https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
* 下载
*/
public static String faceMatch() {
// 请求url
String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
String score = "0";
try {
JSONArray jsonArray = new JSONArray();
JSONObject json = new JSONObject();
json.put("image_type", "BASE64");
byte[] imgData = FileUtil.readFileByBytes("/Users/miyakohiroshi/Desktop/picture.jpg");
String imgStr = Base64Util.encode(imgData);
json.put("image", imgStr);
JSONObject json1 = new JSONObject();
json1.put("image_type", "BASE64");
byte[] imgData1 = FileUtil.readFileByBytes("/Users/miyakohiroshi/Desktop/pingchang.jpg");
String imgStr1 = Base64Util.encode(imgData1);
json1.put("image", imgStr1);
jsonArray.add(json1);
jsonArray.add(json);
// 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
String accessToken = getAuth();
String result = HttpUtil.post(url, accessToken, "application/json", jsonArray.toString());
// System.out.println(result);
JSONObject resultString = JSONObject.fromObject(result);
if(resultString.has("result") && JSONObject.fromObject(result).getInt("error_code") == 0){
score = JSONObject.fromObject(resultString.getString("result")).getString("score");
System.out.println("===="+score);
}
return score;
} catch (Exception e) {
e.printStackTrace();
}
return score;
}
/**
* 获取权限token
* @return
*/
public static String getAuth(){
// 获取token地址
String getAccessTokenUrl = AUTH_HOST
// 1. grant_type为固定参数
+ "grant_type=client_credentials"
// 2. 官网获取的 API Key
+ "&client_id=" + API_KEY
// 3. 官网获取的 Secret Key
+ "&client_secret=" + SECRET_KEY;
JSONObject jsonObject = null;
BufferedReader in = null;
try {
URL realUrl = new URL(getAccessTokenUrl);
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的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
/**
* 返回结果示例
*/
jsonObject = JSONObject.fromObject(result);
String access_token = jsonObject.getString("access_token");
return access_token;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static void main(String[] args) {
FaceMatch.faceMatch();
}
}
- TestController.java(进行图片保存和返回结果的类)
package home.face.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@RestController
@RequestMapping("Test")
public class TestController {
//base64字符串转化成图片
@RequestMapping("/test")
public String GenerateImage(String imgStr, HttpServletRequest req, HttpServletResponse res)
{
String modelInfo = "人脸识别的阈值是80;你的识别结果是";
String origin = req.getHeader("Origin");
if( null != origin) {
res.addHeader("Access-Control-Allow-Origin", origin);
}
//对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) //图像数据为空
return modelInfo+"0";
BASE64Decoder decoder = new BASE64Decoder();
imgStr = imgStr.split(",")[1];
try
{
//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
b[i]+=256;
}
}
//生成jpeg图片
String imgFilePath = "/Users/miyakohiroshi/Desktop/picture.jpg";//新生成的图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
String socre = FaceMatch.faceMatch();
return modelInfo+socre;
}
catch (Exception e)
{
return modelInfo+"0";
}
}
}
- cutpicture.html(进行图片获取和结果返回)
<!doctype html>
<html lang="en">
<head>
<title>GET VIDEO</title>
<meta charset="utf-8">
</head>
<body>
<input type="button" title="开启摄像头" value="开启摄像头" οnclick="getMedia()" />
<video id="video" width="500px" height="500px" autoplay="autoplay"></video>
<canvas id="canvas" width="500px" height="500px"></canvas>
<button id="snap" οnclick="takePhoto()">拍照</button>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>>
<script>
//获得video摄像头区域
var video = document.getElementById("video");
function getMedia() {
var constraints = {
video: {width: 500, height: 500},
audio: true
};
var promise = navigator.mediaDevices.getUserMedia(constraints);
promise.then(function (MediaStream) {
video.srcObject = MediaStream;
video.play();
}).catch(function (PermissionDeniedError) {
console.log(PermissionDeniedError);
})
}
function takePhoto() {
//获得Canvas对象
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, 500, 500);
var url = canvas.toDataURL('image/jpeg',1);
saveimage(url);
}
function saveimage(url){
$.ajax({
url: "http://localhost:8080/Test/test",
type: "POST",
data:{
imgStr:url
},
success: function (data) {
console.log("success")
alert(data)
}
});
}
</script>
</body>
</html>
- application.properties(配置文件)
server.port=8080
spring.thymeleaf.mode=HTML
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>Home</groupId>
<artifactId>face</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>face</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
最终效果:
注:
1、页面获取的人脸图片存放地址/Users/miyakohiroshi/Desktop/picture.jpg
2、事先准备的人脸地址/Users/miyakohiroshi/Desktop/pingchang.jpg
3、百度人脸匹配推荐的阈值是80