我正在尝试使用JSON文件对Google Vision API进行身份验证。通常,我使用GOOGLE_APPLICATION_CREDENTIALS
环境变量来指定JSON文件本身的路径。
但是,我需要在我的应用程序本身中指定它并使用JSON文件内容进行身份验证。
现在,我尝试指定CallSettings
,然后将其作为参数传递给ImageAnnotatorClient.Create
方法。果然,可以通过从JSON文件中读取身份验证信息来完美地创建CallSettings
对象,但是将其作为参数传递给ImageAnnotatorClient
似乎与ImageAnnotatorClient.Create
方法没有区别仍在查找环境变量并抛出InvalidOperation
异常,指定无法找到环境变量。
知道如何才能获得理想的行为吗?
答案 0 :(得分:2)
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);
}
}
}
}
答案 1 :(得分:0)
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}");
}