分析图像数据功能
智能门铃应该能够在将图像发送到随播应用程序之前自动从图像中提取有用数据。
有用的数据可能包括您门口有多少人(可能是零...这是一个恶作剧!)和他们的情绪状态。在本课程中,您将利用 Google Cloud Vision API 的力量进行图像分析。
设置 Cloud Vision API
为您的项目启用Google Cloud Vision:
- 创建Google Cloud项目并启用API,如“ 云端视觉快速入门指南”中所述。
 - 针对您的项目生成一个新的Android API密钥,如“ 验证到云API服务”指南中所述。
 - 
将Cloud Vision Java客户端库依赖关系添加到应用级
build.gradle文件中:dependencies { ... compile 'com.google.api-client:google-api-client-android:1.22.0' exclude module: 'httpclient' compile 'com.google.http-client:google-http-client-gson:1.22.0' exclude module: 'httpclient' compile 'com.google.apis:google-api-services-vision:v1-rev22-1.22.0' } - 
将所需的权限添加到应用的清单文件中:
<uses-permission android:name="android.permission.INTERNET" /> 
上传图像进行处理
Cloud Vision API 使用图像中检测到的对象,发现对象的坐标以及指示算法在该对象发现中的自信程度的分数对图像数据进行注释。
将数据发送到Cloud Vision进行处理:
- 使用您的云项目的API密钥创建一个新的 
VisionRequestInitializer。 - 
使用
Vision.Builder构建新的Vision实例,并为Android平台配置适当的HTTP和JSON实例。</li>
 - 作为 
BatchAnnotateImagesRequest的一部分执行请求并处理响应。这是一个阻塞方法调用,需要一些时间来完成,具体取决于网络条件。 
</ol>
 
将图像数据编码为Image实例。将其传递给 AnnotateImageRequest 并激活 LABEL_DETECTION 请求功能。
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.vision.v1.Vision;
import com.google.api.services.vision.v1.VisionRequestInitializer;
import com.google.api.services.vision.v1.model.AnnotateImageRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesResponse;
import com.google.api.services.vision.v1.model.EntityAnnotation;
import com.google.api.services.vision.v1.model.Feature;
import com.google.api.services.vision.v1.model.Image;
...
private static final String CLOUD_VISION_API_KEY = "...";
...
public Map<String, Float> annotateImage(byte[] imageBytes) throws IOException {
    // Construct the Vision API instance
    HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
    VisionRequestInitializer initializer = new VisionRequestInitializer(CLOUD_VISION_API_KEY);
    Vision vision = new Vision.Builder(httpTransport, jsonFactory, null)
            .setVisionRequestInitializer(initializer)
            .build();
    // Create the image request
    AnnotateImageRequest imageRequest = new AnnotateImageRequest();
    Image image = new Image();
    image.encodeContent(imageBytes);
    imageRequest.setImage(image);
    // Add the features we want
    Feature labelDetection = new Feature();
    labelDetection.setType("LABEL_DETECTION");
    labelDetection.setMaxResults(10);
    imageRequest.setFeatures(Collections.singletonList(labelDetection));
    // Batch and execute the request
    BatchAnnotateImagesRequest requestBatch = new BatchAnnotateImagesRequest();
    requestBatch.setRequests(Collections.singletonList(imageRequest));
    BatchAnnotateImagesResponse response = vision.images()
            .annotate(requestBatch)
            .setDisableGZipContent(true)
            .execute();
    return convertResponseToMap(response);
}
从API返回的 BatchAnnotateImagesResponse 会将注释数据包裹在几层中。您可能希望通过将注释标签和分数提取为更简单的集合来简化结果。
private Map<String, Float> convertResponseToMap(BatchAnnotateImagesResponse response) {
    Map<String, Float> annotations = new HashMap<>();
    // Convert response into a readable collection of annotations
    List<EntityAnnotation> labels = response.getResponses().get(0).getLabelAnnotations();
    if (labels != null) {
        for (EntityAnnotation label : labels) {
            annotations.put(label.getDescription(), label.getScore());
        }
    }
    return annotations;
}
您现在可以从相机上传图像数据,并检查Cloud Vision API 返回的注释。
public class DoorbellActivity extends Activity {
    ...
    private void onPictureTaken(byte[] imageBytes) {
        if (imageBytes != null) {
            try {
                // Process the image using Cloud Vision
                Map<String, Float> annotations = annotateImage(imageBytes);
                Log.d(TAG, "annotations:" + annotations);
            } catch (IOException e) {
                Log.w(TAG, "Unable to annotate image", e);
            }
        }
    }
}