java - Google Vision Java 客户端批量请求响应识别

标签 java google-cloud-platform bulk google-cloud-vision

我正在尝试向 Google Vision 文本检测 API 发出批量请求。到目前为止,我将图像的路径放入列表中,发出批量请求并获取响应。但是,我无法确定哪个结果属于哪个图像。为此,我尝试将 ID 放入请求中,当我收到结果时,我会比较这些 ID。但是,我无法将任何自定义字段放入请求中。我的做法有问题吗?我如何知道哪个响应属于哪个图像?

这是我用于这些请求的代码:

private Vision vision;
private static final String APPLICATION_NAME = "ProjectName";

public static Vision getVisionService() throws IOException, GeneralSecurityException {

    GoogleCredential credential = GoogleCredential.fromStream
            (new FileInputStream("/project-key.json"))
            .createScoped(VisionScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
}
/**
 * Gets up to {@code maxResults} text annotations for images stored at {@code paths}.
 */
public List<String> detectText(List<Path> paths) {
    ImmutableList.Builder<AnnotateImageRequest> requests = ImmutableList.builder();

    try {
        for (Path path : paths) {
            byte[] data;
            data = Files.readAllBytes(path);
            requests.add(
                    new AnnotateImageRequest()
                    .setImage(new Image().encodeContent(data))
                    .setFeatures(ImmutableList.of(
                            new Feature()
                            .setType("TEXT_DETECTION")
                            .setMaxResults(10))));
        }

        Vision.Images.Annotate annotate =
                vision.images()
                .annotate(new BatchAnnotateImagesRequest().setRequests(requests.build()));
        // Due to a bug: requests to Vision API containing large images fail when GZipped.
        annotate.setDisableGZipContent(true);
        BatchAnnotateImagesResponse batchResponse = annotate.execute();
        assert batchResponse.getResponses().size() == paths.size();

        List<String> output = new ArrayList();

        for (int i = 0; i < paths.size(); i++) {
            AnnotateImageResponse response = batchResponse.getResponses().get(i);
            if(response != null && response.getTextAnnotations() != null){
                System.out.println(response.toString());
                String result = getDescriptionFromJson(response.getTextAnnotations().toString());
                System.out.println(response.get("customField"));
                output.add(result);
            }
        }
        return output;
    } catch (IOException ex) {
        System.out.println("Exception occured: " + ex);
        return null;
    }
}

public String getDescriptionFromJson(String json){
    JSONArray results = new JSONArray(json);
    JSONObject result = (JSONObject) results.get(0);
    return result.getString("description");
}

public static void main(String[] args) {
    GoogleVisionQueryHelper g = new GoogleVisionQueryHelper();

    try {
        g.vision = getVisionService();
        List<Path> paths = new ArrayList<>();

        String directory = "/images";

        File[] files = new File(directory).listFiles();
        for(File file : files){
          if(file.isFile() && !file.getName().contains("DS_Store") && !file.getName().startsWith(".")){
            System.out.println(file.getAbsolutePath());
            paths.add(Paths.get(file.getAbsolutePath()));
          }
        }           
        System.out.println("Starting...");

        for(String s: g.detectText(paths)){
            System.out.println(s);
        }
    } catch (IOException | GeneralSecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

最佳答案

BatchAnnotateImageResponse 以与 BatchAnnotateImageRequest 中的请求列表相同的顺序保存响应列表。

关于java - Google Vision Java 客户端批量请求响应识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39478404/

相关文章:

google-cloud-platform - Google Cloud 功能成本

java - 如何在 RAD 7.0 上使用 WAS 8.5?

javascript - 尝试上传到使用多个元数据生成的 GCP 签名网址时收到 403

java - 如何在 MongoDb 中更喜欢读取辅助文件

google-cloud-platform - Google Cloud Functions - 多区域设置

TFS 2010 - 这次只批量 checkout .html 文件......如何?

sql-server - 带有额外列的批量插入

php - 使用 PHP 对 mysql 条目进行批量操作

java - 如何将值从处理程序传递到方法

java - 如何在数组中排列 firebase 检索?