目标
在本示例中,您将使用 Google Vision API 检测图片中的人脸。为了证明自己已正确检测到人脸,您将借助相应数据在每个人脸周围画一个方框。
费用
在本文档中,您将使用 Google Cloud 的以下收费组件:
- Cloud Vision
准备工作
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Google Cloud Vision API.
- 设置您的环境以便使用应用默认凭据。
-
设置语言特定的任务和工具:
- 安装 Google 客户端库。
- 安装 Visual Studio 2012/2015。
- 安装 Java。
- API 参考文档。
下载并安装 Apache Maven 构建系统。构建项目时,Maven 会确保安装 Google API 客户端库和 Vision API 客户端库,因为我们已将它们包含在
pom.xml
中。...
- 安装 Google 客户端库。
- 安装 node.js。
- API 参考。
安装 npm 和 node-canvas。示例代码包含
package.json
,用于使用npm install
命令安装所有依赖项。请注意,您可能还需要安装 node-canvas 的其他依赖项;如需了解详情,请参阅 node-canvas 安装文档。
- 安装 Google 客户端库。
- 安装 PHP 和 Composer。
- API 参考。
- 安装并启用 PHP 版 GD。
- 安装 Google 客户端库。
- 安装 Python。
- API 参考。
- 安装 pillow。
- 安装 Google 客户端库。
- 安装 Ruby 和 Bundler。
- API 参考。
- 安装 ImageMagick。
创建服务对象
要使用官方客户端 SDK 访问 Google API,请根据相应 API 的发现文档(用于向 SDK 描述 API)来创建服务对象。您需要使用自己的凭据从 Vision API 的发现服务中获取该文档。
发送人脸检测请求
要构建发送至 Vision API 的请求,请先查阅 API 文档。在本示例中,您将要求 images
资源对图片执行 annotate
操作。对此 API 的请求采用具有 requests
列表的对象形式。此列表中的每项均包含两种信息:
- Base64 编码的图片数据
- 要在该图片中注释的一列特征。
在本示例中,您只需针对一张图片请求 FACE_DETECTION
注释,然后返回相关的响应部分:
处理响应
恭喜!您已检测到图片中的人脸。对人脸注释请求的响应包含有关检测到的人脸的一些元数据,其中包括环绕人脸的多边形的坐标。不过目前,这只是一列数字。接下来,我们用这些数字来确认您确实已找到图片中的人脸。我们将使用 Vision API 返回的坐标在图片的副本上绘制多边形。
我们使用 node-canvas 库在图片上绘制多边形。
总结
...
要构建并运行该示例,请从示例代码目录运行以下命令:
mvn clean compile assembly:single java -cp target/vision-face-detection-1.0-SNAPSHOT-jar-with-dependencies.jar \ com.google.cloud.vision.samples.facedetect.FaceDetectApp \ data/face.jpg \ output.jpg
要运行该示例,请从示例代码目录运行以下命令:
node faceDetection resources/face.png
清理
为避免因本教程中使用的资源导致您的 Google Cloud 账号产生费用,请删除包含这些资源的项目,或者保留项目但删除各个资源。
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.