【问题标题】:Google Vision API specify JSON fileGoogle Vision API 指定 JSON 文件
【发布时间】:2017-07-28 11:57:53
【问题描述】:

我正在尝试使用 JSON 文件对 Google Vision API 进行身份验证。通常,我使用 GOOGLE_APPLICATION_CREDENTIALS 环境变量来指定 JSON 文件本身的路径。

但是,我需要在我的应用程序本身中指定这一点并使用 JSON 文件内容进行身份验证。

现在,我尝试指定CallSettings,然后将其作为参数传递给ImageAnnotatorClient.Create 方法。果然,CallSettings 对象可以通过从 JSON 文件中读取身份验证信息来完美创建,但将其作为参数传递给 ImageAnnotatorClient 似乎没有什么区别,因为 ImageAnnotatorClient.Create 方法仍在寻找环境变量并抛出InvalidOperation异常,指定找不到环境变量。

知道如何获得所需的行为吗?

Google Vision Docs

【问题讨论】:

    标签: c# google-cloud-vision google-vision


    【解决方案1】:
    using System;
    using Google.Apis.Auth.OAuth2;
    using Google.Cloud.Vision.V1;
    using Grpc.Auth;
    
    namespace GoogleVision
    {
        class Program
        {
            static void Main(string[] args)
            {
                string jsonPath = @"<path to .json credential file>";
    
                var credential = GoogleCredential.FromFile(jsonPath).CreateScoped(ImageAnnotatorClient.DefaultScopes);
    
                var channel = new Grpc.Core.Channel(ImageAnnotatorClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());
    
                var client = ImageAnnotatorClient.Create(channel);
    
                var image = Image.FromFile(@"<path to your image file>");
    
                var response = client.DetectLabels(image);
    
                foreach (var annotation in response)
                {
                    if (annotation.Description != null)
                        Console.WriteLine(annotation.Description);
                }
            }
        }
    }
    

    【讨论】:

    • 我意识到这是一篇旧帖子,但我设法弄清楚了,所以我认为这可能对其他人有所帮助。
    【解决方案2】:
    var jsonPath = "<YOUR PATH>";
    
    var imageAnnotatorClientBuilder = new ImageAnnotatorClientBuilder
    {
        CredentialsPath = jsonPath
    };
    
    var client = imageAnnotatorClientBuilder.Build();
    
    IReadOnlyList<EntityAnnotation> textAnnotations = client.DetectText(image);
    foreach (EntityAnnotation text in textAnnotations)
    {
        Console.WriteLine($"Description: {text.Description}");
    }
    

    【讨论】:

    • 您好,欢迎您。您应该避免仅使用代码的答案:您可以添加一些解释吗?
    猜你喜欢
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多