分为3大步骤:
1:将照片上传到桶;
2:检测桶里面照片的人脸获取参数;
3:下载桶里面的照片到客户端,前端获取到用户的实时照片;
4:比较两张照片中的人脸;
1:注册AWS账户并创建IAM用户(略过);
2:创建存储桶:https://s3.console.aws.amazon.com/s3/home?region=us-east-1
3:开通桶权限
4:上传工具类
导包:
<!-- 亚马逊人脸识别 https://mvnrepository.com/artifact/software.amazon.awssdk/rekognition -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-rekognition</artifactId>
<version>1.12.332</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.347</version>
</dependency>
package com.ruoyi.system.utils.arcface;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.transfer.TransferManager;
import org.junit.Test;
/**
* AWS文件上传
* */
public class UploadTest {
static AmazonS3 s3;
static String AWS_ACCESS_KEY = "****"; // 【你的 access_key】
static String AWS_SECRET_KEY = "****"; // 【你的 aws_secret_key】
String bucketName = "****"; // 【你 bucket 的名字】 # 首先需要保证 s3 上已经存在该存储桶
static {
s3 = new AmazonS3Client(new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY));
s3.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1)); // 此处根据自己的 s3 地区位置改变
}
public String uploadToS3(File tempFile, String remoteFileName) throws IOException {
try {
String bucketPath = bucketName + "/upload" ;
s3.putObject(new PutObjectRequest(bucketPath, remoteFileName, tempFile)
.withCannedAcl(CannedAccessControlList.PublicRead));
GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, remoteFileName);
URL url = s3.generatePresignedUrl(urlRequest);
return url.toString();
} catch (AmazonServiceException ase) {
ase.printStackTrace();
} catch (AmazonClientException ace) {
ace.printStackTrace();
}
return null;
}
@Test
public void test() throws IOException {
File uploadFile = new File("C://Users//Administrator//Desktop//006.jpg");
String uploadKey = "006.jpg";
String s = uploadToS3(uploadFile, uploadKey);
System.out.println(s);
}
}
5:检测桶里面照片的人脸
文档:检测图像中的人脸 - Amazon Rekognition
注意!这一步一定要设置:第 2 步:设置AWS CLI和AWS软件开发工具包 - Amazon Rekognition
//Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
package com.ruoyi.system.utils.arcface;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.rekognition.AmazonRekognition;
import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
import com.amazonaws.services.rekognition.model.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class DetectFaces {
/**
* 人脸识别
* */
public static void main(String[] args) throws Exception {
//桶里面照片
String photo = "***";
//桶名字
String bucket = "***";
//Regions.AP_SOUTHEAST_1 选择地区
AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.standard().withRegion(Regions.AP_SOUTHEAST_1).build();
DetectFacesRequest request = new DetectFacesRequest()
.withImage(new Image()
.withS3Object(new S3Object()
.withName(photo)
.withBucket(bucket)))
.withAttributes(Attribute.ALL);
// Replace Attribute.ALL with Attribute.DEFAULT to get default values.
try {
DetectFacesResult result = rekognitionClient.detectFaces(request);
List<FaceDetail> faceDetails = result.getFaceDetails();
for (FaceDetail face : faceDetails) {
if (request.getAttributes().contains("ALL")) {
AgeRange ageRange = face.getAgeRange();
System.out.println("检测到的人脸估计在 "
+ ageRange.getLow().toString() + " 和 " + ageRange.getHigh().toString()
+ " 岁");
System.out.println("下面是完整的属性集:");
} else { // non-default attributes have null values.
System.out.println("下面是默认的属性集:");
}
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(face));
}
} catch (AmazonRekognitionException e) {
e.printStackTrace();
}
}
}
6:人脸对比:比较图像中的人脸 - Amazon Rekognition
//Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
package com.ruoyi.system.utils.arcface;
import com.amazonaws.services.rekognition.AmazonRekognition;
import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
import com.amazonaws.services.rekognition.model.*;
import com.amazonaws.util.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.List;
public class CompareFaces {
/**
* 人脸对比
* */
public static void main(String[] args) throws Exception {
//两张图片通过阈值
Float similarityThreshold = 70F;
//源图片
String sourceImage = "C://Users//Administrator//Desktop//004.jpg";
//对比图片
String targetImage = "C://Users//Administrator//Desktop//006.jpg";
ByteBuffer sourceImageBytes = null;
ByteBuffer targetImageBytes = null;
AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
//Load source and target images and create input parameters
try (InputStream inputStream = new FileInputStream(new File(sourceImage))) {
sourceImageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
} catch (Exception e) {
System.out.println("加载源映像失败 " + sourceImage);
System.exit(1);
}
try (InputStream inputStream = new FileInputStream(new File(targetImage))) {
targetImageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
} catch (Exception e) {
System.out.println("加载目标映像失败: " + targetImage);
System.exit(1);
}
Image source = new Image().withBytes(sourceImageBytes);
Image target = new Image().withBytes(targetImageBytes);
CompareFacesRequest request = new CompareFacesRequest()
.withSourceImage(source)
.withTargetImage(target)
.withSimilarityThreshold(similarityThreshold);
// Call operation
CompareFacesResult compareFacesResult = rekognitionClient.compareFaces(request);
// Display results
List<CompareFacesMatch> faceDetails = compareFacesResult.getFaceMatches();
for (CompareFacesMatch match : faceDetails) {
ComparedFace face = match.getFace();
BoundingBox position = face.getBoundingBox();
System.out.println("Face at 匹配人脸" + position.getLeft().toString()
+ " " + position.getTop()
+ " matches with " + match.getSimilarity().toString()
+ "% 相似度");
}
List<ComparedFace> uncompared = compareFacesResult.getUnmatchedFaces();
System.out.println("有 " + uncompared.size()
+ " 个不匹配的面孔");
}
}
遇到的坑:
1:人脸识别报错
com.amazonaws.services.rekognition.model.InvalidS3ObjectException: Unable to get object metadata from S3. Check object key, region and/or access permissions. (Service: AmazonRekognition; Status Code: 400; Error Code: InvalidS3ObjectException; Request ID: 56ab3e98-ba45-4753-9143-a44597267cd9; Proxy: null)
原因:photo 填错 应该是upload/006.jpg 而不是 https://test001.s3.ap-southeast-1.amazonaws.com/upload/006.jpg
2:人脸对比报错
Exception in thread "main" com.amazonaws.services.rekognition.model.InvalidImageFormatException: Request has invalid image format (Service: AmazonRekognition; Status Code: 400; Error Code: InvalidImageFormatException; Request ID: c0ea05ad-b74d-4506-b102-03fd9dafead9; Proxy: null)
原因:照片无法识别出人脸,附上几张可以识别的我伦人脸