人脸—>face_token
人脸 在人脸识别技术中特指图像中发现的人脸,当对一张图片进行人脸检测时,会将监测到的人脸记录下来,包括人脸在图片的位置,用一个系统标识face_token来表示
人脸集合—>faceSet
人脸集合是用来存储检测到的的人脸存储对象 一个FaceSet内face_token是不重复的
人脸搜索
计算机检测到一个人脸后,通过人脸判断人身份的过程叫着人脸搜索 ,指的是采集用户新的人脸,在多个已知已知身份用户的人脸集合中进行搜索找出新的人脸属于哪一个已知身份用户,人脸搜索需要SearchAPI
Face++使用方式
1.去https://console.faceplusplus.com.cn/documents/6329752API入门查看代码实例将代码实例全部拷贝下来
public static void main(String[] args) throws Exception{String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();File file = new File(path+"/lk.jpg");//将图片获取过滤byte[] buff = getBytesFromFile(file);//将文件变成byte数组String url = "https://api-cn.faceplusplus.com/facepp/v3/detect";//调用的api地址HashMap<String, String> map = new HashMap<String, String>();//传的参数地址HashMap<String, byte[]> byteMap = new HashMap<String, byte[]>();//传图片地址map.put("api_key", "R3vhEkjMELB3cxiZFzl-Wt_IUUAR41Fx");map.put("api_secret", "WXMJZdt95JBw0Hd-TH5xcct2Lt5LkqA_");map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");byteMap.put("image_file", buff);try{byte[] bacd = post(url, map, byteMap);String str = new String(bacd);System.out.println(str);}catch (Exception e) {e.printStackTrace();}}//======以下代码不需要做任何修改=====private final static int CONNECT_TIME_OUT = 30000;private final static int READ_OUT_TIME = 50000;private static String boundaryString = getBoundary();protected static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception {HttpURLConnection conne;URL url1 = new URL(url);conne = (HttpURLConnection) url1.openConnection();conne.setDoOutput(true);conne.setUseCaches(false);conne.setRequestMethod("POST");conne.setConnectTimeout(CONNECT_TIME_OUT);conne.setReadTimeout(READ_OUT_TIME);conne.setRequestProperty("accept", "*/*");conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);conne.setRequestProperty("connection", "Keep-Alive");conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");DataOutputStream obos = new DataOutputStream(conne.getOutputStream());Iterator iter = map.entrySet().iterator();while(iter.hasNext()){Map.Entry<String, String> entry = (Map.Entry) iter.next();String key = entry.getKey();String value = entry.getValue();obos.writeBytes("--" + boundaryString + "\r\n");obos.writeBytes("Content-Disposition: form-data; name=\"" + key+ "\"\r\n");obos.writeBytes("\r\n");obos.writeBytes(value + "\r\n");}if(fileMap != null && fileMap.size() > 0){Iterator fileIter = fileMap.entrySet().iterator();while(fileIter.hasNext()){Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();obos.writeBytes("--" + boundaryString + "\r\n");obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()+ "\"; filename=\"" + encode(" ") + "\"\r\n");obos.writeBytes("\r\n");obos.write(fileEntry.getValue());obos.writeBytes("\r\n");}}obos.writeBytes("--" + boundaryString + "--" + "\r\n");obos.writeBytes("\r\n");obos.flush();obos.close();InputStream ins = null;int code = conne.getResponseCode();try{if(code == 200){ins = conne.getInputStream();}else{ins = conne.getErrorStream();}}catch (SSLException e){e.printStackTrace();return new byte[0];}ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buff = new byte[4096];int len;while((len = ins.read(buff)) != -1){baos.write(buff, 0, len);}byte[] bytes = baos.toByteArray();ins.close();return bytes;}private static String getBoundary() {StringBuilder sb = new StringBuilder();Random random = new Random();for(int i = 0; i < 32; ++i) {sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));}return sb.toString();}private static String encode(String value) throws Exception{return URLEncoder.encode(value, "UTF-8");}public static byte[] getBytesFromFile(File f) {if (f == null) {return null;}try {FileInputStream stream = new FileInputStream(f);ByteArrayOutputStream out = new ByteArrayOutputStream(1000);byte[] b = new byte[1000];int n;while ((n = stream.read(b)) != -1)out.write(b, 0, n);stream.close();out.close();return out.toByteArray();} catch (IOException e) {}return null;}
2.调用不同API只需要更改地址 将不同的参数写入map就可以了 byteMap传图片文件的时候需要 不用设置成null就可以 规范给出的代码实例main一下的方法不要变动 变动API增加参数只需要增加map中的内容就可以
两张图片比较—无byteMap
//两张照片的比较
public static double compareImg(String face_token1,String face_token2){
String url = "https://api-cn.faceplusplus.com/facepp/v3/compare";
HashMap<String, String> map = new HashMap<String, String>();
map.put("api_key", "R3vhEkjMELB3cxiZFzl-Wt_IUUAR41Fx");
map.put("api_secret", "WXMJZdt95JBw0Hd-TH5xcct2Lt5LkqA_");
map.put("image_file1", face_token1);
map.put("image_file2",face_token2);
try{
byte[] bacd = post(url, map, null);//调用post方法获取结果
String str = new String(bacd);//将字节数组转成字符串
if (str.contains("error_message")) {
System.out.println("发生了错误");
return 0;
}
JsonObject jsonObject = new Gson().fromJson(str, JsonObject.class);
JsonElement confidence = jsonObject.get("confidence");
double asDouble = confidence.getAsDouble();
return asDouble;
}catch (Exception e) {
e.printStackTrace();
}
return 0;
}
3.如果使用搜索API必须将图片的face_token加入到FaceSet中去 使用FaceSet必须要创建
创建和将face_token加入到FaceSet中去
//创建一个FaceSet
public static void createFaceSet() {
String url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/create";
HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, byte[]> byteMap = new HashMap<String, byte[]>();
map.put("api_key", "R3vhEkjMELB3cxiZFzl-Wt_IUUAR41Fx");
map.put("api_secret", "WXMJZdt95JBw0Hd-TH5xcct2Lt5LkqA_");
map.put("outer_id", "lkFaceSet"); //faceSetID固定不更改了
try {
byte[] bacd = post(url, map, null);//调用post方法获取结果
String str = new String(bacd);//将字节数组转成字符串
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
//将生成的face_token添加到FaceSet中
public static String face_tokenAddFaceSet(String face_token) {
String url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/addface";
HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, byte[]> byteMap = new HashMap<String, byte[]>();
map.put("api_key", "R3vhEkjMELB3cxiZFzl-Wt_IUUAR41Fx");
map.put("api_secret", "WXMJZdt95JBw0Hd-TH5xcct2Lt5LkqA_");
map.put("outer_id", "lkFaceSet");
map.put("face_tokens", face_token);
try {
byte[] bacd = post(url, map, null);//调用post方法获取结果
String str = new String(bacd);//将字节数组转成字符串
System.out.println(str);
return str;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//从FaceSet中搜索出相似度最高的照片
public static String search(String search) throws Exception {
String url = "https://api-cn.faceplusplus.com/facepp/v3/search";
HashMap<String, String> map = new HashMap<String, String>();
map.put("api_key", "R3vhEkjMELB3cxiZFzl-Wt_IUUAR41Fx");
map.put("api_secret", "WXMJZdt95JBw0Hd-TH5xcct2Lt5LkqA_");
map.put("outer_id", "lkFaceSet");//faceSet的自定义ID
map.put("face_token", search);
try {
byte[] bacd = post(url, map, null);//调用post方法获取结果
String str = new String(bacd);//将字节数组转成字符串
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
具体实现
前端
调用摄像头
<video src="" id="video" style="border:1px solid red;display: none" width="200px"></video>
<canvas id="canvas"></canvas>
<div id="div1" style="background:rosybrown;width: 200px;height: 200px">开启摄像头</div>
<div id="div" style="background:rosybrown;width: 200px;height: 200px">拍照</div>
<script>
var video = document.getElementById('video');
var div = document.getElementById('div');
var div1 = document.getElementById('div1');
var img = document.getElementById('img');
var canvas = document.getElementById('canvas');
//开启摄像头
div.onclick = () => {
video.style["display"] = "block"
//navigator.mediaDevices.getUserMedia()开启摄像头的方法 成功后有个回参 video接收 启动
navigator.mediaDevices.getUserMedia({video: true}).then(res => {
video.srcObject = res;
video.play();
})
}
//通过cavas生成图片
div1.onclick = () => {
let ctx = canvas.getContext('2d');
//将视频中的图片化成图片
ctx.drawImage(document.getElementById("video"), 0, 0, 200, 200)
//toDataURL方法会把图片转成一个Base64加密数据 参数可以设置图片出来的格式 默认image/jpeg\
////data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAS大概的样子是这样的 逗号后面才是真正要的加密数据要进行截取
var data = canvas.toDataURL("image/png");
console.log(data.split(',')[1])
//将真正的加密数据传给后端
axios.post("search2",{base:JSON.stringify(data.split(',')[1])}).then(res=>{
})
}
</script>
后端
@PostMapping("/search2")
@ResponseBody
public String adds(@RequestBody String base) throws IOException {
//将数据转成JsonObject对象
{"base":"iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAY..."}大概是这个样子的就是到的内容
JsonObject jsonObject = new Gson().fromJson(base, JsonObject.class);
//将json中的加密字符串提取出来两边引号去掉 通过hutoolBase64进行界面将得到的byte[]进行输出
byte[] decode = Base64.decode(jsonObject.get("base").toString().substring(1,jsonObject.get("base").toString().length() - 1));
//创建一个输出流 将byte[]转成图片保存下来
OutputStream os = new FileOutputStream("abc.png");
os.write(decode,0,decode.length);
os.flush();
os.close();
return "rest";
}
