欢迎访问宙启技术站
智能推送

使用apiclient.discoverybuild()在Python中构建GoogleCloudVisionAPI连接

发布时间:2024-01-11 02:27:44

Google Cloud Vision API 是 Google 提供的一种强大的视觉分析工具,可以通过对图像进行分析,实现识别物体、人脸、文本等功能。在 Python 中使用 Google Cloud Vision API,我们可以使用 apiclient.discovery.build() 方法来构建 API 的连接。

首先,我们需要在 Google Cloud Console 上启用 Vision API 并创建一个服务账户。然后,我们需要下载我们的服务账户密钥(json 格式)文件,它将包含我们的认证信息。

以下是使用 apiclient.discovery.build() 方法构建 Google Cloud Vision API 连接的示例代码:

from googleapiclient.discovery import build
import base64

# 载入服务账户密钥(json 文件)
key_file = 'path/to/service_account_key.json'

# 从服务账户密钥中获取认证信息
creds = None
with open(key_file, 'r') as f:
    creds = f.read()

# 创建 Vision API 客户端
service = build('vision', 'v1', credentials=creds)

# 定义用于识别的图像
image_file = 'path/to/image.jpg'
with open(image_file, 'rb') as f:
    image_base64 = base64.b64encode(f.read()).decode('utf-8')

# 构建 Vision API 请求
request = service.images().annotate(body={
  'requests': [{
    'image': {
      'content': image_base64
    },
    'features': [{
      'type': 'LABEL_DETECTION',
      'maxResults': 5
    }]
  }]
})

# 发送 Vision API 请求并获取响应
response = request.execute()

# 解析响应并打印结果
if 'responses' in response:
    labels = response['responses'][0]['labelAnnotations']
    for label in labels:
        print('Label:', label['description'])
        print('Confidence:', label['score'])

在上述示例中,我们首先导入了必要的依赖项 googleapiclient.discovery.buildbase64。然后,我们从指定路径加载了我们的服务账户密钥,并存储在 creds 变量中。

接下来,我们使用 build() 方法创建了 Google Cloud Vision API 的客户端,并传递了我们的认证信息。

然后,我们定义了我们要识别的图像,并使用 base64 库将图像转换为 Base64 字符串。

接下来,我们通过创建一个 Vision API 请求,并指定我们要使用的功能和参数。在此示例中,我们使用 LABEL_DETECTION 功能,并指定了最大结果数为 5。

最后,我们发送 Vision API 请求,并通过解析响应来提取和打印结果信息。

请确保将 path/to/service_account_key.json 替换为实际的服务账户密钥文件路径,将 path/to/image.jpg 替换为实际的图像文件路径。

这只是使用 apiclient.discovery.build() 方法在 Python 中构建 Google Cloud Vision API 连接的一个简单示例。你可以根据自己的需求调整代码,并使用不同的功能和参数来实现更丰富的图像分析功能。