使用JAVA通过AWS来进行人脸识别和对比

分为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)
	

原因:照片无法识别出人脸,附上几张可以识别的我伦人脸

我伦001https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%91%A8%E6%9D%B0%E4%BC%A6%E8%87%AA%E6%8B%8D%E7%85%A7&step_word=&hs=0&pn=9&spn=0&di=7214885350303334401&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=3529609012%2C3316555515&os=3521870420%2C155775053&simid=3529609012%2C3316555515&adpicid=0&lpn=0&ln=894&fr=&fmq=1688380466741_R&fm=&ic=undefined&s=undefined&hd=undefined&latest=undefined©right=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&oriquery=&objurl=https%3A%2F%2Fimage11.m1905.cn%2Fuploadfile%2F2019%2F0422%2F20190422015848928788.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fo7iwgxyx_z%26e3Bv54AzdH3Fnadb0d_z%26e3Bip4s&gsm=1e&rpstart=0&rpnum=0&islist=&querylist=&nojc=undefined&dyTabStr=MCwzLDIsMSw2LDQsNSw3LDgsOQ%3D%3D

我伦002https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%91%A8%E6%9D%B0%E4%BC%A6%E8%87%AA%E6%8B%8D%E7%85%A7&step_word=&hs=0&pn=4&spn=0&di=41943041&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=3944045601%2C19824325&os=3713968170%2C3515901283&simid=4204898456%2C876171975&adpicid=0&lpn=0&ln=894&fr=&fmq=1688380466741_R&fm=&ic=undefined&s=undefined&hd=undefined&latest=undefined©right=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&oriquery=&objurl=https%3A%2F%2Fpic.rmb.bdstatic.com%2Fbjh%2Fevents%2F39db0e70f504521ed0df03578d3daf115143.png%40h_1280&gsm=3c&rpstart=0&rpnum=0&islist=&querylist=&nojc=undefined&dyTabStr=MCwzLDIsMSw2LDQsNSw3LDgsOQ%3D%3D

我伦003https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%91%A8%E6%9D%B0%E4%BC%A6%E8%87%AA%E6%8B%8D%E7%85%A7&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined©right=undefined&cs=3944045601,19824325&os=3713968170,3515901283&simid=4204898456,876171975&pn=4&rn=1&di=41943041&ln=894&fr=&fmq=1688380466741_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=10&spn=0&pi=0&gsm=1e&objurl=https%3A%2F%2Fpic.rmb.bdstatic.com%2Fbjh%2Fevents%2F39db0e70f504521ed0df03578d3daf115143.png%40h_1280&rpstart=0&rpnum=0&adpicid=0&nojc=undefined&dyTabStr=MCwzLDIsMSw2LDQsNSw3LDgsOQ%3D%3D&ctd=1688380512282%5E3_1903X920%251

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值