Google Cloud Vision API中的BatchAnnotatedImagesResponse是否保留bat



给定一个图像URL列表,我想对每个图像进行注释,即从每个图像中提取文本。为此,我想在Java中使用Google Cloud Vision API客户端库。这是我的伪代码:

List<String> imageUrls = ...;
List<AnnotateImageRequest> requests = imageUrls.stream()
.map(convertToRequest)
.collect(Collectors::toList);
BatchAnnotateImagesResponse batchResponse = imageAnnotatorClient.batchAnnotateImages(requests);

现在从batchResponse我可以得到一个AnnotateImageResponse的列表。问题是,AnnotateImageResponse的数量是否与请求的数量相对应?回复的顺序是否与请求的顺序相对应?我可以放心地假设这样做吗

for (int i = 0 ; i < imageUrls.size(); i++) {
var url = imageUrls.get(i);
var annotations = batchResponse.getResponses(i).getTextAnnotationsList();
}

我将在for循环的每次迭代中获得正确图像的注释?这是我从文件中不清楚的。

如果你查看DetectText.java的一个官方片段,你会发现这个有趣的评论:

//初始化将用于发送请求的客户端。该客户端只需要创建一次,并且可以对多个请求重复使用。完成所有请求后,请致电";关闭";方法,以安全地清理任何剩余的后台资源。

这意味着一旦你设置了客户端,你就可以打电话,但正如你所说,它没有提到任何关于订单的内容。有关ImageAnnotatorClient的更多信息,请点击此处。

经过测试,我发现该批次是您提供的请求列表中的same sizesame order。您可以在此处找到BatchAnnotateImagesResponse的详细信息。

最后,我将在下面的代码中留下官方云视觉注释示例中函数asyncBatchAnnotateImages的更新版本,它可以进一步扩展图像注释的处理,并检查它如何处理请求。(可能超出了目前的范围,但我认为它可能有用(

public static void asyncBatchAnnotateImages(List<String> uris, String outputUri)
throws IOException, ExecutionException, InterruptedException {
try (ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create()) {
List<AnnotateImageRequest> imageRequests = new ArrayList<AnnotateImageRequest>();
for (String inputImageUri : uris) {
ImageSource source = ImageSource.newBuilder().setImageUri(inputImageUri).build();
Image image = Image.newBuilder().setSource(source).build();
Feature feature = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build();
AnnotateImageRequest imageRequest = AnnotateImageRequest.newBuilder().setImage(image).addFeatures(feature).build();
imageRequests.add(imageRequest);
} 

GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(outputUri).build();
OutputConfig outputConfig = OutputConfig.newBuilder()
.setGcsDestination(gcsDestination)
.setBatchSize(1) // The max number of responses to output in each JSON file
.build();
AsyncBatchAnnotateImagesRequest request = AsyncBatchAnnotateImagesRequest.newBuilder()
.addAllRequests(imageRequests)
.setOutputConfig(outputConfig)
.build();

AsyncBatchAnnotateImagesResponse response = imageAnnotatorClient.asyncBatchAnnotateImagesAsync(request).get();
String gcsOutputUri = response.getOutputConfig().getGcsDestination().getUri();
System.out.format("Output written to GCS with prefix: %s%n", gcsOutputUri);
}
}

最新更新