Google Cloud Vision returns 空响应

Google Cloud Vision returns empty response

我正在尝试构建一个 C# 库,它将充当一组 Google API 的包装器。在使用 Google Vision API 时,我发现 API returns 某些查询的响应集为空。例如,当我在 car.png 上尝试 运行 FACE_ANNOTATION 时,我得到的响应是:

{
  "responses": [
    {}
  ]
}

我已经消除了所有基本问题,例如将图像存储在 Google 云存储桶中,public 访问图像,有效 API 密钥,启用 API 来自 Google API 仪表板。

下面是我提出请求的一段代码:

httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

// The API address to which we will make the HTTP POST query
String request_query = "v1/images:annotate?" + $"key={APIKey}";
HttpResponseMessage response = await httpClient.PostAsJsonAsync(request_query, imageRequests);

Stream stream = await response.Content.ReadAsStreamAsync();
StreamReader streamReader = new StreamReader(stream);
String response_str = streamReader.ReadToEnd();        
Console.WriteLine(response_str);

if (response.IsSuccessStatusCode) {
    try {
        imageResponseList = JsonConvert.DeserializeObject<AnnotateImageResponseList>(response_str);

     } catch (JsonSerializationException e) {
         Debug.WriteLine(e.StackTrace);
     }
}

这是发送到 API:

的请求正文(在我上面的代码中调用的 imageRequests)
{
  "requests": [
    {
      "image":
       {
         "content":"",
         "source":
         {
           "imageUri":"gs://<google_cloud_bucket>/car.png"
         }
       },
       "features":[
         {
           "type":0,
           "maxResults":100,
           "model":"builtin/stable"
         } 
       ],
       "imageContext":null
    }
  ]
}

现在,我知道已经有一个可以直接使用的C#客户端,但是我正在做的项目需要我通过HTTP请求访问RESTAPI。

如有任何帮助,我们将不胜感激。

API 请求格式不正确,无法满足您的要求。

您正在指定 contentsource 字段。 Vision API images.annotate documentation 指定:

If both content and source are provided for an image, content takes precedence and is used to perform the image annotation request.

您指定的 content 是空的,API 没有任何作用,所以响应也是空的。删除 content 以避免此问题。

type 字段也有问题。在 images.annotate documentation 中尝试 API 时,它建议以下类型字段:

Expected one of ["TYPE_UNSPECIFIED", "FACE_DETECTION", "LANDMARK_DETECTION", "LOGO_DETECTION", "LABEL_DETECTION", "TEXT_DETECTION", "DOCUMENT_TEXT_DETECTION", "SAFE_SEARCH_DETECTION", "IMAGE_PROPERTIES", "CROP_HINTS", "WEB_DETECTION"].

您还可以将字段设置为 "type": "0""type": 0 之类的内容以指向预期值数组中的特定位置,但我认为其他选项更具描述性。 0 值等同于 "TYPE_UNESPECIFIED",它也会产生一个空答案。

这个请求对我有效:

{
  "requests": [
    {
      "image": {
        "source": {
          "imageUri": "gs://<google_cloud_bucket>/car.png"
        }
      },
      "features": [
        {
          "type": "FACE_DETECTION",
          "maxResults": 100,
          "model": "builtin/stable"
        }
      ],
      "imageContext": null
    }
  ]
}

请求 json 可以从 BatchAnnotateImagesRequest 对象序列化(一个 .ToString() 就足够了)。

至于响应,你最好使用内置的

BatchAnnotateImagesResponse.Parser.ParseJson(response_str)

希望对您有所帮助。