使用机器学习套件给图片加标签 (Android)

您可以使用机器学习套件给图片中识别出的对象加标签。提供的 机器学习套件支持 400 多种不同标签。

功能不分类显示捆绑
实现模型通过 Google Play 服务动态下载。模型在构建时静态关联到您的模型。
应用大小大小增加约 200 KB。大小增加约 5.7 MB。
初始化时间可能需要等到模型下载完毕后才能首次使用。模型可立即使用

试试看

  • 您可以试用示例应用, 请查看此 API 的用法示例。

准备工作

  1. 请务必在您的项目级 build.gradle 文件中添加 Google 的 buildscriptallprojects 部分中的 Maven 制品库。

  2. 将 Android 版机器学习套件库的依赖项添加到模块的 应用级 Gradle 文件,通常为 app/build.gradle。请选择以下其中一项: 以下依赖项:

    如需将模型与应用捆绑,请执行以下操作

    dependencies {
      // ...
      // Use this dependency to bundle the model with your app
      implementation 'com.google.mlkit:image-labeling:17.0.8'
    }
    

    对于在 Google Play 服务中使用模型的情况

    dependencies {
      // ...
      // Use this dependency to use the dynamically downloaded model in Google Play Services
      implementation 'com.google.android.gms:play-services-mlkit-image-labeling:16.0.8'
    }
    
  3. 如果您选择在 Google Play 服务中使用该模型,则可以配置 在应用下载完毕后,自动将模型下载到设备上 从 Play 商店安装的应用。为此,请将以下声明添加到 应用的 AndroidManifest.xml 文件:

    <application ...>
          ...
          <meta-data
              android:name="com.google.mlkit.vision.DEPENDENCIES"
              android:value="ica" >
          <!-- To use multiple models: android:value="ica,model2,model3" -->
    </application>
    

    您还可以明确检查模型可用性,并请求通过 Google Play 服务 ModuleInstallClient API

    如果您不启用安装时模型下载或请求明确下载, 系统会在您首次运行标签添加器时下载模型。您提出的请求 在下载完成之前未产生任何结果。

现在,您可以给图片加标签了。

1. 准备输入图片

基于图片创建 InputImage 对象。 使用 Bitmap 时,图片标记器的运行速度最快;或者,如果您使用 Camera2 API、YUV_420_888 media.Image

您可以创建 InputImage 对象,下文对每种方法进行了说明。

使用 media.Image

如需创建 InputImage,请执行以下操作: 对象(例如从 media.Image 对象中捕获图片时) 请传递 media.Image 对象和图片的 旋转为 InputImage.fromMediaImage()

如果您使用 CameraX 库、OnImageCapturedListenerImageAnalysis.Analyzer 类计算旋转角度值 。

Kotlin

private class YourImageAnalyzer : ImageAnalysis.Analyzer {

    override fun analyze(imageProxy: ImageProxy) {
        val mediaImage = imageProxy.image
        if (mediaImage != null) {
            val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
            // Pass image to an ML Kit Vision API
            // ...
        }
    }
}

Java

private class YourAnalyzer implements ImageAnalysis.Analyzer {

    @Override
    public void analyze(ImageProxy imageProxy) {
        Image mediaImage = imageProxy.getImage();
        if (mediaImage != null) {
          InputImage image =
                InputImage.fromMediaImage(mediaImage, imageProxy.getImageInfo().getRotationDegrees());
          // Pass image to an ML Kit Vision API
          // ...
        }
    }
}

如果您不使用可提供图片旋转角度的相机库, 可以根据设备的旋转角度和镜头方向来计算 设备传感器:

Kotlin

private val ORIENTATIONS = SparseIntArray()

init {
    ORIENTATIONS.append(Surface.ROTATION_0, 0)
    ORIENTATIONS.append(Surface.ROTATION_90, 90)
    ORIENTATIONS.append(Surface.ROTATION_180, 180)
    ORIENTATIONS.append(Surface.ROTATION_270, 270)
}

/**
 * Get the angle by which an image must be rotated given the device's current
 * orientation.
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Throws(CameraAccessException::class)
private fun getRotationCompensation(cameraId: String, activity: Activity, isFrontFacing: Boolean): Int {
    // Get the device's current rotation relative to its "native" orientation.
    // Then, from the ORIENTATIONS table, look up the angle the image must be
    // rotated to compensate for the device's rotation.
    val deviceRotation = activity.windowManager.defaultDisplay.rotation
    var rotationCompensation = ORIENTATIONS.get(deviceRotation)

    // Get the device's sensor orientation.
    val cameraManager = activity.getSystemService(CAMERA_SERVICE) as CameraManager
    val sensorOrientation = cameraManager
            .getCameraCharacteristics(cameraId)
            .get(CameraCharacteristics.SENSOR_ORIENTATION)!!

    if (isFrontFacing) {
        rotationCompensation = (sensorOrientation + rotationCompensation) % 360
    } else { // back-facing
        rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360
    }
    return rotationCompensation
}

Java

private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
    ORIENTATIONS.append(Surface.ROTATION_0, 0);
    ORIENTATIONS.append(Surface.ROTATION_90, 90);
    ORIENTATIONS.append(Surface.ROTATION_180, 180);
    ORIENTATIONS.append(Surface.ROTATION_270, 270);
}

/**
 * Get the angle by which an image must be rotated given the device's current
 * orientation.
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private int getRotationCompensation(String cameraId, Activity activity, boolean isFrontFacing)
        throws CameraAccessException {
    // Get the device's current rotation relative to its "native" orientation.
    // Then, from the ORIENTATIONS table, look up the angle the image must be
    // rotated to compensate for the device's rotation.
    int deviceRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
    int rotationCompensation = ORIENTATIONS.get(deviceRotation);

    // Get the device's sensor orientation.
    CameraManager cameraManager = (CameraManager) activity.getSystemService(CAMERA_SERVICE);
    int sensorOrientation = cameraManager
            .getCameraCharacteristics(cameraId)
            .get(CameraCharacteristics.SENSOR_ORIENTATION);

    if (isFrontFacing) {
        rotationCompensation = (sensorOrientation + rotationCompensation) % 360;
    } else { // back-facing
        rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360;
    }
    return rotationCompensation;
}

然后,传递 media.Image 对象和 将旋转角度值设为 InputImage.fromMediaImage()

Kotlin

val image = InputImage.fromMediaImage(mediaImage, rotation)

Java

InputImage image = InputImage.fromMediaImage(mediaImage, rotation);

使用文件 URI

如需创建 InputImage,请执行以下操作: 对象时,请将应用上下文和文件 URI 传递给 InputImage.fromFilePath()。在需要满足特定条件时 使用 ACTION_GET_CONTENT intent 提示用户进行选择 从图库应用中获取图片

Kotlin

val image: InputImage
try {
    image = InputImage.fromFilePath(context, uri)
} catch (e: IOException) {
    e.printStackTrace()
}

Java

InputImage image;
try {
    image = InputImage.fromFilePath(context, uri);
} catch (IOException e) {
    e.printStackTrace();
}

使用 ByteBufferByteArray

如需创建 InputImage,请执行以下操作: 对象ByteBufferByteArray时,首先计算图像 旋转角度。media.Image 然后,创建带有缓冲区或数组的 InputImage 对象以及图片的 高度、宽度、颜色编码格式和旋转角度:

Kotlin

val image = InputImage.fromByteBuffer(
        byteBuffer,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
)
// Or:
val image = InputImage.fromByteArray(
        byteArray,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
)

Java

InputImage image = InputImage.fromByteBuffer(byteBuffer,
        /* image width */ 480,
        /* image height */ 360,
        rotationDegrees,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
);
// Or:
InputImage image = InputImage.fromByteArray(
        byteArray,
        /* image width */480,
        /* image height */360,
        rotation,
        InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12
);

使用 Bitmap

如需创建 InputImage,请执行以下操作: 对象时,请进行以下声明:Bitmap

Kotlin

val image = InputImage.fromBitmap(bitmap, 0)

Java

InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);

图片由 Bitmap 对象和旋转角度表示。

2. 配置并运行图片标记器

如需给图片中的对象加标签,请将 InputImage 对象传递给 ImageLabelerprocess 方法。

  1. 首先,获取 ImageLabeler

    如果要使用设备端图片标记器,请执行以下操作: 声明:

Kotlin

// To use default options:
val labeler = ImageLabeling.getClient(ImageLabelerOptions.DEFAULT_OPTIONS)

// Or, to set the minimum confidence required:
// val options = ImageLabelerOptions.Builder()
//     .setConfidenceThreshold(0.7f)
//     .build()
// val labeler = ImageLabeling.getClient(options)

Java

// To use default options:
ImageLabeler labeler = ImageLabeling.getClient(ImageLabelerOptions.DEFAULT_OPTIONS);

// Or, to set the minimum confidence required:
// ImageLabelerOptions options =
//     new ImageLabelerOptions.Builder()
//         .setConfidenceThreshold(0.7f)
//         .build();
// ImageLabeler labeler = ImageLabeling.getClient(options);
  1. 然后,将图片传递给 process() 方法:

Kotlin

labeler.process(image)
        .addOnSuccessListener { labels ->
            // Task completed successfully
            // ...
        }
        .addOnFailureListener { e ->
            // Task failed with an exception
            // ...
        }

Java

labeler.process(image)
        .addOnSuccessListener(new OnSuccessListener<List<ImageLabel>>() {
            @Override
            public void onSuccess(List<ImageLabel> labels) {
                // Task completed successfully
                // ...
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Task failed with an exception
                // ...
            }
        });

3. 获取已加标签的对象的相关信息

如果为图片加标签操作成功,系统将会显示一个列表, 将 ImageLabel 对象传递给成功监听器。每个 ImageLabel 对象表示在图片中加了标签的内容。基本 模型支持 400 多个不同的标签。 您可以获取每个标签的文本说明,以及 模型和匹配的置信度分数。例如:

Kotlin

for (label in labels) {
    val text = label.text
    val confidence = label.confidence
    val index = label.index
}

Java

for (ImageLabel label : labels) {
    String text = label.getText();
    float confidence = label.getConfidence();
    int index = label.getIndex();
}

提高实时性能的相关提示

如果要在实时应用中给图片加标签,请按照这些说明操作 实现最佳帧速率的准则:

  • 如果您使用 Cameracamera2 API、 限制对图片标记器的调用。如果新视频 当图片标记器运行时,如果有帧可用,请丢弃该帧。请参阅 VisionProcessorBase 类。
  • 如果您使用 CameraX API, 确保 Backpressure 策略设置为默认值 ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST。 这可保证一次仅传送一张图片进行分析。如果有更多图片 在分析器繁忙时生成,它们会被自动丢弃,不会排队等待 。通过调用 ImageProxy.close(),将传递下一张图片。
  • 如果您使用图像标记器的输出在 输入图片,首先从机器学习套件获取结果, 和叠加层。这会渲染到 每个输入帧只执行一次。请参阅 CameraSourcePreview GraphicOverlay 类。
  • 如果您使用 Camera2 API,请以 ImageFormat.YUV_420_888 格式。如果您使用的是旧版 Camera API,请使用 ImageFormat.NV21 格式。