Search code examples
c#.netgrpcgoogle-cloud-vision

Detecting content in Google Cloud Vision for .NET does nothing/hangs app


I just started playing around with Google Cloud Vision a bit. I wanted to detect text in an image. Inspired by the official docs (e.g. https://cloud.google.com/vision/docs/detecting-text and https://cloud.google.com/docs/authentication/production) I

  • created a new project,
  • attached the Vision API to it,
  • created a service account and downloaded the credentials/key-JSON file,
  • set up an VS project and got all relevant packages from NuGET.

My code looks like this:

using System;
using System.Windows;
using Google.Apis.Auth.OAuth2;
using Google.Cloud.Vision.V1;
using Grpc.Auth;

//...

private void Button_Click(object sender, RoutedEventArgs e)
{
    // Load an image from a local file.
    var image = Image.FromFile(@"C:\!\myimage.png");
    var credential = GoogleCredential.FromFile(@"C:\!\credentials.json");

    var channel = new Grpc.Core.Channel(@"https://vision.googleapis.com/v1/images:annotate",credential.ToChannelCredentials());

    var client = ImageAnnotatorClient.Create(channel);

    var response = client.DetectText(image); // <-- Nothing happens, app hangs, why?
    foreach (var annotation in response)
    {
        if (annotation.Description != null)
            Console.WriteLine(annotation.Description);
    }
}

//...

While stepping through the code, the app hangs at var response = client.DetectText(image); (no exception or anything). The same happens, if I use other methods (e.g. DetectLogos(image) or DetectLabels(image)). When checking CPU usage and network traffic nothing important happens (before or after the relevant line of code).

What am I doing wrong here?

Thanks!


Solution

  • The url target provided seems to be related to Vision REST API but you are creating a GRPC channel. You should change the target to:

    var channel = new Grpc.Core.Channel(@"http://vision.googleapis.com",credential.ToChannelCredentials());
    var client = ImageAnnotatorClient.Create(channel);
    

    Or:

    var channel = new Grpc.Core.Channel(ImageAnnotatorClient.DefaultEndpoint.Host, credential.ToChannelCredentials());
    var client = ImageAnnotatorClient.Create(channel);
    

    The endpoint information can be found under the ImageAnnotatorClient class.

    Hope this is helpful.