• AmazonRekognition-Java对接


    AmazonRekognition-Java对接

      AmazonRekognition类似于百度EasyDL,是一款图像分析服务,检测图像分类及图像内容等。

    1、项目创建

      项目创建的方式有一下三种方式:

      1:AWS官网创建

      2:CLI创建

      3:编码创建(Java)

    AWS官网创建文档见:

      链接:https://pan.baidu.com/s/1WMnUIjNug53YEzWMXENVKw
      提取码:flny

    2、依赖

            <!--AmazonRekognition依赖-->
            <dependency>
                <groupId>com.amazonaws</groupId>
                <artifactId>aws-java-sdk-rekognition</artifactId>
                <version>1.11.759</version>
            </dependency>

    3、功能代码

    1、客户端验证连接

      客户端连接方式及问题见https://www.cnblogs.com/StefanieYang/p/13212508.html

    2、功能

    public class RekognitionClient{
      
      private final static String regoin = "us-east-1"; //区域设置
      private final static String projectArn = ""; //项目Arn
      private final static String versionName = ""; //模型
      private final static String projectVersionArn = ""; //项目模型Arn
      private final static int minInferenceUnits = 1; //最小推理数
      private final static String projectName = ""; //项目名称
      
    
      // Rekognition客户端生成/连接
      public static AmazonRekognition getRekognition(){
        AWSCredentials credentials = new ProfileCredentialsProvider().getCredentials();
        AmazonRekognition amazonRekognition = AmazonRekognitionClientBuilder.standard()
                               .withCredentials(new AWSStaticCredentialsProvider(credentials))
                               .build();
        return amazonRekognition;
      }
    
      // Create
      public static void createProject(AmazonRekognition amazonRekognition){
        try{
          CreateProjectRequest request = new CreateProjectRequest().withProjectName(projectName);//创建请求
          CreateProjectResult result = amazonRekognition.createProject(request);
          log.info("Project ARN:" + result.getProjectArn());
        }catch(Exception e){
          log.error(e.getMessage());
        }
      }
    
      
      // Delete
      public static void deleteProject(AmazonRekognition amazonRekognition){
        try{
           DeleteProjectRequest request = new DeleteProjectRequest().withPojectArn(projectArn);
           DeleteProjectResult result = amazonRekognition.deleteProject(request);
           log.info("Project Status:" + result.getStatus());
        }catch(Exception e){
           log.error(e.getMessage());
        }
      }
    
      
      // Start
      public static void startProject(AmazonRekognition amazonRekognition){
        try{
          StartProjectVersionRequest request = new StartProjectVersionRequest().withProjectVersionArn(projectVersionArn).withMinInferenceUnits(minInferenceUnits);
          StartProjectVersionResult  result = amazonRekognition.startProjectVersion(request);
          log.info("Project Status:" + result.getStatus());
        }catch(Exception e){
          log.error(e.getMessage());
        }
      }
    
      // Stop
      public static void stopProject(AmazonRekognition amazonRekognition){
        try{
          StopProjectVersionRequest request = new StopProjectVersionRequest().withProjectVersionArn(projectVersionArn);
          StopProjectVersionResult result = amazonRekognition.stopProjectVersion(request);
          log.info("Project Status:" + result.getStatus());
        }catch(Exception e){
          log.error(e.getMessage());
        }
      }
    
      
      // LocalImage Upload Detect(非自定义项目)
      public static void localImageDetect(String imagePath,AmazonRekognition amazonRekognition){
        ByteBuffer imageBytes = null;
        InputStream in = null;
        DetectLabelsRequest request = null;
        Image image;
        try{
          in = new FileInputStream(new File(imagePath));
          try{
            imageBytes = ByteBuffer.wrap(IOUtils.toByteArraay(in));
            request = new DetectLabelsRequest().withImage(new Image().withBytes(imageBytes))
                  .withMaxLabels(10).withMinconfidence(77F);
          }catch(IOException e){
            log.error("输入流转ByteBuffer失败!")
          }
        }catch(FileNotFoundException e){
          log.error("文件不存在!");
        }
        DetectLabelsResult result = amazonRekognition.detectLabels(request);
        List<Label> list = result.getLabels();
        for(Label label : list){
           log.info("标签名:"+label.getName+"标签Confidence:"+label.getConfidence());
        }
        if(in!=null){
          try{
            in.close();
          }catch(IOException e){
            log.error(e.getMessage());
          }
        }
      }
    
    
      // Bucket Image Detect(非自定义项目)
      public static void bucketImageDetect(String key,String bucketName,AmazonRekognition amazonRekognition){
        DetectLabelsRequest request = new DetectLabelsRequest();
        request.withImage(new Image().withS3Object(new S3Object().withName(key).withBucket(bucketName))).withMaxLabels(10).withConfidence(75F);
        try{
          DetectLabelsResult result = amazonRekognition.detectLabes(request);
          List<Label> list = result.getLabels();
          for(Label label : list){
            log.info("标签名:"+label.getName+"标签Confidence"+label.getConfidence());
          }
        }catch(IOException e){
          log.error(e.getMessage());
        }
      }
    }

    AmazonS3 File Detect

    package com.stefanie.sun.bean.AWS.Rekognition;
    
    import com.amazonaws.services.rekognition.AmazonRekognition;
    import com.amazonaws.services.rekognition.model.*;
    import com.amazonaws.services.rekognition.model.Image;
    import com.amazonaws.services.s3.AmazonS3;
    import com.amazonaws.services.s3.model.S3ObjectInputStream;
    import lombok.extern.slf4j.Slf4j;
    
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.util.List;
    
    
    @Slf4j
    public class DisplayCustomLabels extends JPanel {
    
        private final static String projectVersionArn = "your projectVersionArn";
    
        private static final long serialVersionUID = 1L;
        BufferedImage image;
        static int scale;
        DetectCustomLabelsResult result;
    
        public DisplayCustomLabels(DetectCustomLabelsResult labelsResult,
                                   BufferedImage bufImage) throws Exception {
            super();
            scale = 4; // increase to shrink image size.
            result = labelsResult;
            image = bufImage;
    
        }
    
        // Draws the bounding box around the detected faces.
        public void paintComponent(Graphics g) {
            float left = 0;
            float top = 0;
            int height = image.getHeight(this);
            int width = image.getWidth(this);
            Graphics2D g2d = (Graphics2D) g; // Create a Java2D version of g.
            // Draw the image.
            g2d.drawImage(image, 0, 0, width / scale, height / scale, this);
            g2d.setColor(new Color(0, 212, 0));
            // Iterate through faces and display bounding boxes.
            List<CustomLabel> customLabels = result.getCustomLabels();
            for (CustomLabel customLabel : customLabels) {
    
                if (customLabel.getGeometry() != null) {
                    BoundingBox box = customLabel.getGeometry().getBoundingBox();
                    left = width * box.getLeft();
                    top = height * box.getTop();
                    g2d.drawString(customLabel.getName(), left / scale, top / scale);
                    g2d.drawRect(Math.round(left / scale), Math.round(top / scale),
                            Math.round((width * box.getWidth()) / scale),
                            Math.round((height * box.getHeight())) / scale);
                }
    
            }
        }
    
        public static void main(String arg[]) throws Exception {
    
            String photo = "assets/ifree-zy-test1.0/1592904311/img_20191109_171935.png";
            String bucket = "custom-labels-console-us-east-1-5de227ce63";
            float minConfidence = 90;
            int height = 0;
            int width = 0;
            // Get the image from an S3 Bucket
    //        AmazonS3 s3client = AmazonS3ClientBuilder.defaultClient();
            AmazonS3 s3client = S3client.amazonS36(); //见:https://www.cnblogs.com/StefanieYang/p/13229128.html 客户端连接方式第6种
            com.amazonaws.services.s3.model.S3Object s3object =
                    s3client.getObject(bucket, photo);
            S3ObjectInputStream inputStream = s3object.getObjectContent();
            BufferedImage image = ImageIO.read(inputStream);
    
            DetectCustomLabelsRequest request = new DetectCustomLabelsRequest()
                    .withProjectVersionArn(projectVersionArn)
                    .withImage(new Image().withS3Object(new
                            S3Object().withName(photo).withBucket(bucket)))
                    .withMinConfidence(minConfidence);
            width = image.getWidth();
            height = image.getHeight();
            // Call DetectFaces
            AmazonRekognition amazonRekognition =
                    RelognitionClient.getRekognition();  //见上面代码中获取方式
            DetectCustomLabelsResult result =
                    amazonRekognition.detectCustomLabels(request);
    
            //Show the bounding box info for each face.
            List<CustomLabel> customLabels = result.getCustomLabels();
            log.info("----------" + request.toString() + "----------" + result.toString() + "----------" + customLabels
                    .size() + "----------" + customLabels.toString() + "----------");
            for (CustomLabel customLabel : customLabels) {
                if (customLabel.getGeometry() != null) {
                    BoundingBox box = customLabel.getGeometry().getBoundingBox();
                    float left = width * box.getLeft();
                    float top = height * box.getTop();
                    System.out.println("Custom Label:");
                    System.out.println("Left: " + String.valueOf((int) left));
                    System.out.println("Top: " + String.valueOf((int) top));
                    System.out.println("Label Width: " + String.valueOf((int) (width *
                            box.getWidth())));
                    System.out.println("Label Height: " + String.valueOf((int) (height *
                            box.getHeight())));
                    System.out.println();
                }
            }
            // Create frame and panel./download file
    //        JFrame frame = new JFrame("RotateImage");
    //        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //        DisplayCustomLabels panel = new DisplayCustomLabels(result, image);
    //        panel.setPreferredSize(new Dimension(image.getWidth() / scale,
    //                image.getHeight() / scale));
    //        frame.setContentPane(panel);
    //        frame.pack();
    //        frame.setVisible(true);
        }
    }
    往外张望的人在做梦,向内审视的人才是清醒的
  • 相关阅读:
    js相关禁止
    单例模式 俗称单例3步曲+1曲
    轮廓线重建:二维平行轮廓线重建理论和方法
    一种面向三维地质剖面的形体表面重构算法
    在不使用gluSphere()的情况下在OpenGL中绘制Sphere
    Balabolka
    jQuery学习笔记之可见性过滤选择器
    Flask学习之四 数据库
    Flask学习之三 web表单
    Flask学习之二 模板
  • 原文地址:https://www.cnblogs.com/StefanieYang/p/13230671.html
Copyright © 2020-2023  润新知