人脸对比
/**
* 功能描述:人脸对比性别检测
* @author zhangpu
* @date 2021/12/1
* @param appId
* @param sdkKey
* @param libPath 动态链接库地址
* @param tempPath 网络图片暂存本地地址
* @param fileType 文件类型 1:本地文件 2:oss地址
* @param acceptFacePath 接收图片路径
* @param mysqlDataPath 数据库中图片路径
*/
public static Map<String,Object> getScoreAndSex(String appId,String sdkKey,String libPath,String acceptFacePath,String mysqlDataPath,Integer fileType,String tempPath){
Map<String,Object> resultMap=new HashMap<>();
FaceEngine faceEngine = new FaceEngine(libPath);//引入动态链接库
int errorCode = faceEngine.activeOnline(appId, sdkKey); //激活引擎
if (errorCode != ErrorInfo.MOK.getValue() && errorCode != ErrorInfo.MERR_ASF_ALREADY_ACTIVATED.getValue())
{
System.out.println("引擎激活失败");
}
ActiveFileInfo activeFileInfo=new ActiveFileInfo();
errorCode = faceEngine.getActiveFileInfo(activeFileInfo);
if (errorCode != ErrorInfo.MOK.getValue() && errorCode != ErrorInfo.MERR_ASF_ALREADY_ACTIVATED.getValue())
{
System.out.println("获取激活文件信息失败");
}
//引擎配置
EngineConfiguration engineConfiguration = new EngineConfiguration();
engineConfiguration.setDetectMode(DetectMode.ASF_DETECT_MODE_IMAGE);
engineConfiguration.setDetectFaceOrientPriority(DetectOrient.ASF_OP_ALL_OUT);
engineConfiguration.setDetectFaceMaxNum(10);
engineConfiguration.setDetectFaceScaleVal(16);
//功能配置
FunctionConfiguration functionConfiguration = new FunctionConfiguration();
functionConfiguration.setSupportAge(true);
functionConfiguration.setSupportFace3dAngle(true);
functionConfiguration.setSupportFaceDetect(true);
functionConfiguration.setSupportFaceRecognition(true);
functionConfiguration.setSupportGender(true);
functionConfiguration.setSupportLiveness(true);
functionConfiguration.setSupportIRLiveness(true);
engineConfiguration.setFunctionConfiguration(functionConfiguration);
//初始化引擎
errorCode = faceEngine.init(engineConfiguration);
if (errorCode != ErrorInfo.MOK.getValue())
{
System.out.println("初始化引擎失败");
}
//TODO 接收到的人脸图片地址
ImageInfo imageInfo = getRGBData(fileType==1?new File(acceptFacePath):new File(saveToFile(mysqlDataPath,tempPath)));
List<FaceInfo> faceInfoList = new ArrayList<>();
errorCode = faceEngine.detectFaces(imageInfo.getImageData(), imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getImageFormat(), faceInfoList);
if(faceInfoList==null||faceInfoList.size()==0)
{
return null;
}
//TODO 提出接收到的特征
FaceFeature faceFeature = new FaceFeature();
errorCode = faceEngine.extractFaceFeature(imageInfo.getImageData(), imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getImageFormat(), faceInfoList.get(0), faceFeature);
System.out.println("特征值大小:" + faceFeature.getFeatureData().length);
//TODO 数据库中的人脸信息
ImageInfo imageInfo2 = getRGBData(fileType==1?new File(mysqlDataPath):new File(saveToFile(mysqlDataPath,tempPath)));
List<FaceInfo> faceInfoList2 = new ArrayList<>();
errorCode = faceEngine.detectFaces(imageInfo2.getImageData(), imageInfo2.getWidth(), imageInfo2.getHeight(),imageInfo.getImageFormat(), faceInfoList2);
if(faceInfoList2==null||faceInfoList2.size()==0)
{
return null;
}
//TODO 数据库中的人脸信息特征
FaceFeature faceFeature2 = new FaceFeature();
errorCode = faceEngine.extractFaceFeature(imageInfo2.getImageData(), imageInfo2.getWidth(), imageInfo2.getHeight(), imageInfo.getImageFormat(), faceInfoList2.get(0), faceFeature2);
System.out.println("特征值大小:" + faceFeature.getFeatureData().length);
//特征比对
FaceFeature targetFaceFeature = new FaceFeature();
targetFaceFeature.setFeatureData(faceFeature.getFeatureData());
FaceFeature sourceFaceFeature = new FaceFeature();
sourceFaceFeature.setFeatureData(faceFeature2.getFeatureData());
FaceSimilar faceSimilar = new FaceSimilar();
errorCode = faceEngine.compareFaceFeature(targetFaceFeature, sourceFaceFeature, faceSimilar);
resultMap.put("score",faceSimilar.getScore());
//设置活体测试
errorCode = faceEngine.setLivenessParam(0.5f, 0.7f);
//人脸属性检测
FunctionConfiguration configuration = new FunctionConfiguration();
configuration.setSupportAge(true);
configuration.setSupportFace3dAngle(true);
configuration.setSupportGender(true);
configuration.setSupportLiveness(true);
errorCode = faceEngine.process(imageInfo.getImageData(), imageInfo.getWidth(), imageInfo.getHeight(), imageInfo.getImageFormat(), faceInfoList, configuration);
//性别检测
List<GenderInfo> genderInfoList = new ArrayList<GenderInfo>();
errorCode = faceEngine.getGender(genderInfoList);
System.out.println("性别:" + (genderInfoList.get(0).getGender()==0?"男":"女"));
resultMap.put("sex",genderInfoList.get(0).getGender()==0?"男":genderInfoList.get(0).getGender()==-1?"未知":"女");
//引擎卸载
errorCode = faceEngine.unInit();
return resultMap;
}
保存url图片到本地
/**
* 功能描述:将url图片保存本地
* @author zhangpu
* @date 2021/12/1
* @param destUrl
* @param tempPath
*/
public static String saveToFile(String destUrl,String tempPath) {
FileOutputStream fos = null;
BufferedInputStream bis = null;
HttpURLConnection httpUrl = null;
URL url = null;
int BUFFER_SIZE = 1024;
byte[] buf = new byte[BUFFER_SIZE];
int size = 0;
try {
url = new URL(destUrl);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
fos = new FileOutputStream(tempPath);
while ((size = bis.read(buf)) != -1)
{
fos.write(buf, 0, size);
}
fos.flush();
} catch (IOException e) {
} catch (ClassCastException e) {
} finally {
try {
fos.close();
bis.close();
httpUrl.disconnect();
} catch (IOException e) {
} catch (NullPointerException e) {
}
}
return tempPath;
}
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>摄像头拍照</title>
</head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<style>
#capture{
position: absolute;
right: 190px;
bottom: -40px;
}
#video{
position: absolute;
right: 0;
top: 0;
}
#img{
position: absolute;
left: 0;
top: 0;
}
.auto{
position: absolute;
left: 50%;
top: 50%;
height: 320px;
margin-top: -160px;
}
#sure{
position: absolute;
left: 210px;
bottom: -40px;
}
button{
cursor: pointer;
margin: 0 auto;
border: 1px solid #f0f0f0;
background: #5CACEE;
color: #FFF;
width: 100px;
height: 36px;
line-height: 36px;
border-radius: 8px;
text-align: center;
/*禁止选择*/
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Chrome/Safari/Opera */
-khtml-user-select: none; /* Konqueror */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently not supported by any browser */
}
</style>
<body>
<div class="auto">
<video id="video" width="480" height="320" autoplay></video>
<canvas id="canvas" width="480" height="320" style="display: none;"></canvas>
<img src="./body_default.png" id="img" width="480" height="320" style="margin-left: 20px;">
<div>
<button id="capture" title="点击进行拍照">拍照</button>
</div>
<div>
<button id="sure" title="是否用这张图片进行验证">确认</button>
</div>
</div>
<script>
var file ,stream;
//访问用户媒体设备的兼容方法
function getUserMedia(constraints, success, error) {
if (navigator.mediaDevices.getUserMedia) {
//最新的标准API
navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
} else if (navigator.webkitGetUserMedia) {
//webkit核心浏览器
navigator.webkitGetUserMedia(constraints,success, error)
} else if (navigator.mozGetUserMedia) {
//firfox浏览器
navigator.mozGetUserMedia(constraints, success, error);
} else if (navigator.getUserMedia) {
//旧版API
navigator.getUserMedia(constraints, success, error);
}
}
let video = document.getElementById('video');
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
function success(stream) {
//兼容webkit核心浏览器
let CompatibleURL = window.URL || window.webkitURL;
//将视频流设置为video元素的源
console.log(stream);
stream = stream;
//video.src = CompatibleURL.createObjectURL(stream);
video.srcObject = stream;
video.play();
}
function error(error) {
console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
}
if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
//调用用户媒体设备, 访问摄像头
getUserMedia({video : {width: 480, height: 320}}, success, error);
} else {
alert('不支持访问用户媒体');
}
// base64转文件
document.getElementById('capture').addEventListener('click', function () {
context.drawImage(video, 0, 0, 480, 320);
// 获取图片base64链接
var image = canvas.toDataURL('image/png');
// 定义一个img
var img = document.getElementById("img");
//设置属性和src
//img.id = "imgBoxxx";
img.src = image;
//将图片添加到页面中
//document.body.appendChild(img);
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
file = new File([u8arr], filename, {type: mime});
return new File([u8arr], filename, {type: mime});
}
console.log(dataURLtoFile(image, 'aa.png'));
})
document.getElementById('sure').addEventListener('click', function () {
var formData = new FormData();
formData.append("file",file);
$.ajax({
type: "POST", // 数据提交类型
url: "xxxxx", // 发送地址
data: formData, //发送数据
async: true, // 是否异步
processData: false, //processData 默认为false,当设置为true的时候,jquery ajax 提交的时候不会序列化 data,而是直接使用data
contentType: false,
success:function(data){
if(data.code === 200){
console.log(`${data.data.files.filepath}`);
}else{
console.log(`${data.message}`);
}
},
error:function(e){
self.$message.warning(`${e}`);
//console.log("不成功"+e);
}
});
stream.getTracks()[0].stop();//结束关闭流
})
</script>
</body>
</html>