java - 从 Google Vision API 获取空响应

标签 java image-recognition google-cloud-vision

我正在测试 Google Vision API 的一些功能,并从我的相机(5MP 相机)中单击的图像得到空响应。然而,当我从网络上下载任何图像时,例如送货员的图像(具有纯色背景,例如白色),我会得到带有标签的有意义的响应。两组图像都存在于我的本地磁盘上。下面是我引用谷歌文档编写的代码,

public class ImageAnalyzer {

final static String APPLICATION_NAME ="My_APP/1.0";
final static String IMAGE_PATH = "E:/Vision/SampleImages/IMAG0013.jpg";
final static int maxResults =3;

private Vision vision;

public ImageAnalyzer(Vision vision){
    this.vision=vision;
}
  /**
   * Connects to the Vision API using Application Default Credentials.
   */
  public static Vision getVisionService() throws IOException, GeneralSecurityException {
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault().createScoped(VisionScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
  }

  public Map<String, List<String>> labelImage(String imagePath){

      final Map<String,List<String>> labels = new HashMap<String, List<String>>();

      final Path path = Paths.get(imagePath);  

      try {

        final byte[] raw = Files.readAllBytes(path);

        /*final AnnotateImageRequest request =new AnnotateImageRequest().setImage(new Image().encodeContent(raw))
        .setFeatures(ImmutableList.of(new Feature().setType("LABEL_DETECTION").setMaxResults(3)
                , new Feature().setType("LOGO_DETECTION").setMaxResults(3)));*/

        AnnotateImageRequest request =
                new AnnotateImageRequest()
                    .setImage(new Image().encodeContent(raw)).setFeatures(ImmutableList.of(
                new Feature()
                    .setType("LABEL_DETECTION")
                    .setMaxResults(maxResults),
                new Feature()
                    .setType("LOGO_DETECTION")
                    .setMaxResults(1),
                new Feature()
                    .setType("TEXT_DETECTION")
                    .setMaxResults(maxResults),
                new Feature()
                    .setType("LANDMARK_DETECTION")
                    .setMaxResults(1)));


        final Vision.Images.Annotate annotate = vision.images().annotate(
                new BatchAnnotateImagesRequest().
                setRequests(ImmutableList.of(request)));

        final BatchAnnotateImagesResponse batchResponse = annotate.execute();
        //assert batchResponse.getResponses().size() == 1;

        System.out.println("Size of searches"+batchResponse.getResponses().size());

        //final AnnotateImageResponse response = batchResponse.getResponses().get(0);
        if (batchResponse.getResponses().get(0).getLabelAnnotations() != null) {

            final List<String> label = new ArrayList<String>();
            for (EntityAnnotation ea: batchResponse.getResponses().get(0).getLabelAnnotations()) {
                label.add(ea.getDescription());
            }
            labels.put("LABEL_ANNOTATION", label);
        }

        if (batchResponse.getResponses().get(0).getLandmarkAnnotations() != null) {
            final List<String> landMark = new ArrayList<String>();
            for (EntityAnnotation ea : batchResponse.getResponses().get(0).getLandmarkAnnotations()) {
                landMark.add(ea.getDescription());
            }
            labels.put("LANDMARK_ANNOTATION", landMark);
        }

        if (batchResponse.getResponses().get(0).getLogoAnnotations() != null) {
            final List<String> logo = new ArrayList<String>();
            for (EntityAnnotation ea : batchResponse.getResponses().get(0).getLogoAnnotations()) {
                logo.add(ea.getDescription());
            }
            labels.put("LOGO_ANNOTATION", logo);
        }

        if (batchResponse.getResponses().get(0).getTextAnnotations() != null) {

            List<String> text = new ArrayList<String>();
            for (EntityAnnotation ea : batchResponse.getResponses().get(0).getTextAnnotations()) {
                text.add(ea.getDescription());
            }
            labels.put("TEXT_ANNOTATION", text);
        }


        return labels;

    } catch (IOException e) {
        e.printStackTrace();
    }
      return null;

  }

  public static void printAnnotations(final List<EntityAnnotation> entityAnnotations) {

      if(entityAnnotations!=null && !entityAnnotations.isEmpty()) {
          for (final EntityAnnotation entityAnnotation : entityAnnotations) {
              final String desc = entityAnnotation.getDescription();
              final Float score = entityAnnotation.getScore();
              System.out.println(desc+"     "+score);
          }

      }
  }

  public static void main(String[] args) throws IOException, GeneralSecurityException {
        // TODO Auto-generated method stub
        final ImageAnalyzer analyzer = new ImageAnalyzer(getVisionService());
        final Map<String, List<String>> labels = analyzer.labelImage(IMAGE_PATH);

        for (Entry<String, List<String>> entry : labels.entrySet()) {

             final String key = entry.getKey();
             final List<String> value = entry.getValue();
             if(value!=null && !value.isEmpty()) {

             System.out.println("Printing for key"+key);
             for (final String myLebel : value) {

                 System.out.println(" "+myLebel);
               }

             }
        }

       //System.out.println(System.getenv("GOOGLE_APPLICATION_CREDENTIALS"))            
    }

}

谁能帮帮我吗?

最佳答案

关于java - 从 Google Vision API 获取空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38417738/

相关文章:

python - 类型错误 : Expected binary or unicode string, 得到了项目 {

algorithm - 服装识别算法

ios - iOS 应用中的 Vize.ai 图像识别

machine-learning - Google Cloud Vision API(标签),有多少种可能的标签?

c# - 方法 'ImageAnnotatorClient.Create' 没有重载需要 1 个参数

java - ArrayList 的 IndexOutOfBoundException

java - 为什么构造函数中 getHeight() 和 getWidth() 返回 0?我该如何避免这种情况?

java - MPAndroidChart 分组条形图 : Group title not showed above group

python - 如何从图像 url (jpeg) 读取字节并在 Python 2.7 上以 base64 编码?

java - 使用异常映射器的 JAX-RS