首页 > 解决方案 > 将 Java 与 Google 的 Vision API 结合使用时,如何解决“错误:指定的 GCS 路径无效”?

问题描述

我目前在 Vision API 文档上关注此示例:在此处找到


import com.google.cloud.vision.v1.*;
import com.google.cloud.vision.v1.Feature.Type;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

public class VisionApiTest {
    public static void main(String... args) throws Exception {

        PrintStream stream = new PrintStream(new File("src/test.txt"));

        detectTextGcs("https://www.w3.org/TR/SVGTiny12/examples/textArea01.png", stream);
    }

    public static void detectTextGcs(String gcsPath, PrintStream out) throws Exception, IOException {
        List<AnnotateImageRequest> requests = new ArrayList<>();

        ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
        Image img = Image.newBuilder().setSource(imgSource).build();
        Feature feat = Feature.newBuilder().setType(Type.TEXT_DETECTION).build();
        AnnotateImageRequest request =
                AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
        requests.add(request);

        try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
            BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
            List<AnnotateImageResponse> responses = response.getResponsesList();

            for (AnnotateImageResponse res : responses) {
                if (res.hasError()) {
                    out.printf("Error: %s\n", res.getError().getMessage());
                    return;
                }

                // For full list of available annotations, see http://g.co/cloud/vision/docs
                for (EntityAnnotation annotation : res.getTextAnnotationsList()) {
                    out.printf("Text: %s\n", annotation.getDescription());
                    out.printf("Position : %s\n", annotation.getBoundingPoly());
                }
            }
        }
    }
}

将 gcsPath 字符串传入示例中的 detectTextGcs 方法后,出现错误:“错误:指定的 GCS 路径无效:https ://www.w3.org/TR/SVGTiny12/examples/textArea01.png ”

我期待 PrintStream 对象将图片中保存的文本写入文件,即“明天,\n明天,和\n明天;等等等等……”。在上面提到的 Vision API 文档页面上尝试 API 后,它工作正常,但在 IntelliJ 中不行。

任何帮助是极大的赞赏。谢谢你。(如果这不是一个措辞好的问题,请原谅我,这是我第一次发帖)

标签: javagoogle-cloud-platformvision-api

解决方案


我实际上发现了问题所在。问题在于 detectGcsText() 方法的第 3 行。

 ImageSource imgSource = imageSource.newBuilder().setGcsImageUri(gcsPath).build();

如果您想使用常规 HTTP URI,则必须使用setImageUri(path)而不是setGcsImageUri(gcsPath).

谢谢大家的帮助!


推荐阅读