python - 批量注释的 Google Vision API 问题
问题描述
我想使用 Cloud Vision API 来检测来自 ca 的标签。40K 照片并将结果下载为 CSV 文件。我将照片上传到云存储并使用以下代码,但出现错误。我问过一个在工作中使用 python 的人,但他无法处理这个错误。你能帮我修一下吗?
TypeError: Invalid constructor input for BatchAnnotateImagesRequest: [{'image': source {
image_uri: "gs://bucket/image-path.jpg"
}
, 'features': [{'type': <Type.LABEL_DETECTION: 4>}]}]
我使用的代码:
from google.cloud import
from google.cloud import storage
from google.cloud.vision_v1 import ImageAnnotatorClient
from google.cloud.vision_v1 import types
import os
import json
import numpy as np
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]='C://file-path.json'
#(created in step 1)
# Get GCS bucket
storage_client = storage.Client()
bucket = storage_client.bucket('bucket_name')
image_paths = []
for blob in list(bucket.list_blobs()):
image_paths.append("gs://bucket_name/"+blob.name)
# We can send a maximum of 16 images per request.
start = 0
end = 16
label_output = []
for i in range(int(np.floor(len(image_paths)/16))+1):
requests = []
client = vision.ImageAnnotatorClient()
for image_path in image_paths[start:end]:
image = types.Image()
image.source.image_uri = image_path
requests.append({'image': image,'features': [{'type': vision.Feature.Type.LABEL_DETECTION}]})
response = client.batch_annotate_images(requests)
for image_path, i in zip(image_paths[start:end], response.responses):
labels = [{label.description: label.score} for label in i.label_annotations]
labels = {k: v for d in labels for k, v in d.items()}
filename = os.path.basename(image_path)
l = {'filename': filename, 'labels': labels}
label_output.append(l)
start = start+16
end = end+16
#export results to CSV file
for l in label_output:
print('"' + label_output[l]['filename'] + '";', end = '')
for label in label_output[l]["labels"]:
print('"' + label + '";"' + label_output[l][label] + '";', end = '')
print("")
解决方案
batch_annotate_images()
没有requests
正确获取内容。要解决此问题,只需将变量requests
显式requests
分配给batch_annotate_images()
.
response = client.batch_annotate_images(requests=requests)
请参阅batch_annotate_images()以供参考。此外,如果您计划将 Vision API 更新到 2.3.1,您可能会在features:
查看此参考以了解其参数的更新用法时遇到错误。
推荐阅读
- php - 在 symfony 2.8 中,这两个命令都不能在 app/console 上运行
- javascript - xhttp.onreadystatechange setInterval 函数中未捕获的 TypeError innerHTML of null
- asp.net-core - 在 asp.net core blazor 应用程序中使用 JWT 身份验证 API
- node.js - 如何修复 yarn.lock 和 package-lock json mix
- reactjs - Okta 重定向因 React HashRouter 而失败
- java - tikxml 没有类型适配器
- triggers - 忽略或关闭zabbix问题一段时间
- angular - 使用外部数组展平嵌套的 Observables 而无需内部订阅 (RxJS)
- django - 使用 docker compose 获取 Mysql 连接错误
- node.js - 如何将自定义 SQL 查询传递到 app.js 之外的 MySQL 数据库?(Express、Node、Pug 架构)