图像分析

ImageAnalysis 用例为您的应用提供可供 CPU 访问的图像缓冲区或可供 GPU 访问的硬件缓冲区,以便进行图像处理、计算机视觉或机器学习推断。您的应用会实现一个 ImageAnalysis.Analyzer,该接口会在每个相机帧上运行其 analyze 方法。

与在 Camera2 和 ImageReader 上构建自己的帧流水线相比,ImageAnalysis 可让您专注于分析本身。CameraX 会在同一相机拍摄会话中同时运行分析、Preview、VideoCapture和 ImageCapture,并根据您的生命周期启动和停止分析,还会在分析器落后时丢帧,以确保预览流畅。它还会以消费者预期的格式(YUV、RGBA、NV21 或 GPU 可访问的 HardwareBuffer)提供帧,并附带每帧旋转元数据,因此您无需编写在不同设备上行为不同的转换或缓冲区管理代码。

如需详细了解如何将 Google 的机器学习套件与 CameraX 集成,请参阅机器学习套件分析器。

操作模式

当分析流水线无法满足 CameraX 的帧速率要求时,CameraX 会使用通过 setBackpressureStrategy 配置的两种背压策略之一来丢帧:

模式 策略常量 行为 适用场景
非阻塞(默认) STRATEGY_KEEP_ONLY_LATEST 仅在单帧缓冲区中缓存最新图片。新帧会覆盖未处理的帧。 setImageQueueDepth 不会产生任何影响。 高延迟或可变时间分析器,其中 Preview 和其他用例必须保持流畅,例如实时文本翻译、产品识别或大声描述场景的无障碍应用。
屏蔽 STRATEGY_BLOCK_PRODUCER 在丢弃帧之前,最多可缓冲 setImageQueueDepth 个图片。当队列已满时,会使相机设备上的所有绑定用例(包括 Preview)停止运行。 必须处理每一帧且运行速度快于帧间隔(具有短暂的抖动容差)的流水线,例如移动侦测、物品计数或通过镜头上的指尖估算心率。

如果分析器速度较快,总处理时间低于一个相机帧间隔(例如,在 60 fps 时低于 16 毫秒),那么无论采用哪种模式,都能获得流畅的结果。采用更深队列的阻塞模式有助于吸收短暂的调度抖动,而不会丢帧。如果分析器耗时超过帧间隔,请使用默认的非阻塞模式,以便 ImageAnalysis 丢弃过时的帧,而不会导致 Preview 或 VideoCapture 停滞。如需详细了解执行器交互,请参阅 STRATEGY_KEEP_ONLY_LATEST 和 STRATEGY_BLOCK_PRODUCER。

配置图片分析

使用 ImageAnalysis.Builder 配置帧格式、分辨率、旋转和流控制。

输出图片格式

根据流水线中消耗帧的内容,选择采用 setOutputImageFormat 的像素格式。默认格式为 OUTPUT_IMAGE_FORMAT_YUV_420_888。下表列出了支持的输出图片格式及其典型用例:

格式常量 ImageProxy.getFormat 数据访问权限和备注 典型使用场景
OUTPUT_IMAGE_FORMAT_YUV_420_888 ImageFormat.YUV_420_888 getPlanes 中的三个 Y、U 和 V 平面。提供最低的转换开销。 零售、票务和支付应用中的条形码和二维码扫描,这些应用仅使用 Y(亮度)平面。可检测页面边缘的文件扫描器和可测量亮度的曝光计。
OUTPUT_IMAGE_FORMAT_RGBA_8888 PixelFormat.RGBA_8888 planes[0].buffer 中的单个平面,按红、绿、蓝、Alpha 顺序打包。不使用其他平面。 需要 RGB 输入张量的图片分类和对象检测模型,例如 LiteRT 模型。基于颜色的任务,例如颜色选择器和油漆匹配应用。
OUTPUT_IMAGE_FORMAT_NV21 ImageFormat.YUV_420_888 三个平面(Y、U 和 V),其中 U 和 V 平面的像素步幅为 2,存储可从 planes[2] 读取的交错 VU 字节。需要 CameraX 1.5.0 及更高版本。如果您调用 getImage,则底层 android.media.Image 在平面布局或尺寸方面可能与 ImageProxy 不同。 原生 C 或 C++ 流水线,例如 OpenCV 或 FFmpeg、人脸检测 SDK,以及需要从旧版 Camera API 获取 NV21 帧的视频通话或安全编码器。
OUTPUT_IMAGE_FORMAT_PRIVATE ImageFormat.PRIVATE 在 CameraX 1.7.0 及更高版本中,使用 getHardwareBuffer 的零拷贝 GPU 可访问 HardwareBuffer。需要进行功能检查。getPlanes 返回空数组。 GPU 委托的机器学习推理,例如姿势估计、手部追踪和背景分割,其中避免 CPU 回读可使延迟时间保持在足够低的水平,从而获得实时结果。

选择 OUTPUT_IMAGE_FORMAT_RGBA_8888 时,CameraX 会将图片从 YUV 转换为 RGBA,并按照以下重复顺序将字节打包到第一个平面的 ByteBuffer 中:

ImageProxy.getPlanes()[0].buffer[0]: red
ImageProxy.getPlanes()[0].buffer[1]: green
ImageProxy.getPlanes()[0].buffer[2]: blue
ImageProxy.getPlanes()[0].buffer[3]: alpha

分辨率和宽高比

使用 setResolutionSelector 指定首选尺寸和宽高比。默认情况下,ImageAnalysis 的目标分辨率为 640x480。当您的机器学习模型需要固定的输入大小,或者您希望在低端硬件(例如自助服务终端扫描器)上限制每帧处理费用时,请请求特定分辨率,例如 1280x720,并采用 16:9 宽高比策略。确切的输出分辨率取决于设备硬件功能。如需详细了解如何配置分辨率,请参阅相机分辨率。

图片旋转角度

默认情况下,CameraX 会以传感器方向将缓冲区传递给分析器,并在 imageProxy.imageInfo.rotationDegrees 中报告使图片竖直所需的顺时针旋转角度。如果您的分析器在 Android 6.0(API 级别 23)及更高版本上需要已旋转的像素缓冲区,请调用 setOutputImageRotationEnabled(true)。该选项会增加每帧旋转开销,并且 OUTPUT_IMAGE_FORMAT_PRIVATE 不支持该选项。

创建并设置分析器

实现 ImageAnalysis.Analyzer 并替换 analyze(ImageProxy)。使用 setAnalyzer 注册分析器,并在分析完成后使用 clearAnalyzer 取消注册。调用 setAnalyzer 会替换之前注册的所有分析器,您可以在绑定用例之前或之后调用该方法。

在 analyze(ImageProxy) 中,执行以下操作:

  1. 在帧预算内处理帧(例如,在 30 fps 时低于 32 毫秒),或使用 STRATEGY_KEEP_ONLY_LATEST。
  2. 对于 CPU 可访问的格式(OUTPUT_IMAGE_FORMAT_YUV_420_888、OUTPUT_IMAGE_FORMAT_RGBA_8888 和 OUTPUT_IMAGE_FORMAT_NV21),请使用 imageProxy.getFormat 验证格式,然后通过 imageProxy.getPlanes 读取像素平面,或使用 imageProxy.toBitmap 转换为 Bitmap。
  3. 在 finally 代码块中使用 imageProxy.close 关闭 ImageProxy,以便 CameraX 可以传送后续帧。如果您使用 imageProxy.getImage 访问封装的 android.media.Image,请勿直接将其关闭,因为关闭 ImageProxy 会安全地释放底层图片。

将图片分析绑定到生命周期

使用 SessionConfig 和 ProcessCameraProvider.bindToLifecycle 将 ImageAnalysis 和 Preview 绑定在一起。您可以向同一 SessionConfig 添加其他用例,例如,对于同时显示预览、运行分割和录制视频的应用,可以添加 VideoCapture。支持的组合和分辨率因设备而异;请参阅并发用例。如需详细了解生命周期绑定和相机控件,请参阅 CameraX API 模型和控制相机输出。

Kotlin

suspend fun bindAnalysis(
    context: Context,
    lifecycleOwner: LifecycleOwner,
    analysisExecutor: Executor,
    surfaceProvider: Preview.SurfaceProvider,
) {
    val cameraProvider = ProcessCameraProvider.awaitInstance(context)

    // Pair 1280x720 with a 16:9 AspectRatioStrategy so CameraX selects
    // 16:9 candidates before applying ResolutionStrategy.
    val resolutionSelector = ResolutionSelector.Builder()
        .setAspectRatioStrategy(
            AspectRatioStrategy.RATIO_16_9_FALLBACK_AUTO_STRATEGY
        )
        .setResolutionStrategy(
            ResolutionStrategy(
                Size(1280, 720),
                ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER,
            )
        )
        .build()

    val imageAnalysis = ImageAnalysis.Builder()
        .setResolutionSelector(resolutionSelector)
        // Non-blocking mode drops stale frames so Preview stays smooth
        // when frame processing takes longer than the frame interval.
        .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
        .build()

    imageAnalysis.setAnalyzer(analysisExecutor) { imageProxy ->
        try {
            // Apply rotationDegrees so coordinates stay upright without
            // spending CPU cycles rotating the pixel buffer.
            val rotationDegrees = imageProxy.imageInfo.rotationDegrees
            processFrame(imageProxy, rotationDegrees)
        } finally {
            // Closing ImageProxy returns the buffer to CameraX so new
            // frames keep arriving. Never close imageProxy.image directly.
            imageProxy.close()
        }
    }

    val preview = Preview.Builder().build()
    preview.setSurfaceProvider(surfaceProvider)

    // Bundling both use cases in one SessionConfig keeps preview and
    // analysis synchronized within the same camera capture session.
    val sessionConfig = SessionConfig(preview, imageAnalysis)
    cameraProvider.bindToLifecycle(
        lifecycleOwner,
        CameraSelector.DEFAULT_BACK_CAMERA,
        sessionConfig,
    )
}

Java

void bindAnalysis(Context context, LifecycleOwner lifecycleOwner,
        Executor analysisExecutor,
        Preview.SurfaceProvider surfaceProvider) {
    Executor mainExecutor = ContextCompat.getMainExecutor(context);
    ListenableFuture<ProcessCameraProvider> providerFuture =
            ProcessCameraProvider.getInstance(context);

    // Initialize asynchronously to avoid blocking the UI thread, and
    // run bindToLifecycle on mainExecutor as required by CameraX.
    providerFuture.addListener(() -> {
        try {
            ProcessCameraProvider cameraProvider = providerFuture.get();
            bindAnalysisUseCases(cameraProvider, lifecycleOwner,
                    analysisExecutor, surfaceProvider);
        } catch (ExecutionException | InterruptedException e) {
            Log.e(TAG, "Failed to get the camera provider", e);
        }
    }, mainExecutor);
}

void bindAnalysisUseCases(ProcessCameraProvider cameraProvider,
        LifecycleOwner lifecycleOwner, Executor analysisExecutor,
        Preview.SurfaceProvider surfaceProvider) {
    // Pair 1280x720 with a 16:9 AspectRatioStrategy so CameraX selects
    // 16:9 candidates before applying ResolutionStrategy.
    int fallbackRule =
            ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER;
    ResolutionSelector resolutionSelector =
            new ResolutionSelector.Builder()
                    .setAspectRatioStrategy(
                            AspectRatioStrategy
                                    .RATIO_16_9_FALLBACK_AUTO_STRATEGY)
                    .setResolutionStrategy(new ResolutionStrategy(
                            new Size(1280, 720), fallbackRule))
                    .build();

    ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
            .setResolutionSelector(resolutionSelector)
            // Non-blocking mode drops stale frames so Preview stays smooth
            // when frame processing runs slower than the frame interval.
            .setBackpressureStrategy(
                    ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
            .build();

    imageAnalysis.setAnalyzer(analysisExecutor, imageProxy -> {
        try {
            // Apply rotationDegrees so coordinates stay upright without
            // spending CPU cycles rotating the pixel buffer.
            int rotationDegrees =
                    imageProxy.getImageInfo().getRotationDegrees();
            processFrame(imageProxy, rotationDegrees);
        } finally {
            // Closing ImageProxy returns the buffer to CameraX so new
            // frames keep arriving. Never close imageProxy.getImage().
            imageProxy.close();
        }
    });

    Preview preview = new Preview.Builder().build();
    preview.setSurfaceProvider(surfaceProvider);

    // Bundling both use cases in one SessionConfig keeps preview and
    // analysis synchronized within the same camera capture session.
    SessionConfig sessionConfig = new SessionConfig(preview, imageAnalysis);
    cameraProvider.bindToLifecycle(
            lifecycleOwner,
            CameraSelector.DEFAULT_BACK_CAMERA,
            sessionConfig);
}

分析 GPU 上的帧

在搭载 Android 10(API 级别 29)及更高版本的设备上,您可以在 CameraX 1.7.0 及更高版本中配置 ImageAnalysis,以输出由 GPU 采样的 HardwareBuffer 支持的 OUTPUT_IMAGE_FORMAT_PRIVATE 帧,从而实现零拷贝 OpenGL 或 Vulkan 推理流水线,例如 GPU 委托的姿势估计、手部追踪或背景分割。

首先,使用 ImageAnalysis 和 isOutputFormatSupported 上的 getImageAnalysisCapabilities 检查相机是否支持 OUTPUT_IMAGE_FORMAT_PRIVATE。OUTPUT_IMAGE_FORMAT_PRIVATE 处于有效状态时,请注意以下要求:

  • ImageProxy.getPlanes 会返回一个空数组。通过 ImageProxy.getHardwareBuffer 读取帧,这需要 Android 9(API 级别 28)及更高版本(OUTPUT_IMAGE_FORMAT_PRIVATE 本身需要 Android 10 [API 级别 29] 及更高版本)。
  • 您必须先关闭 getHardwareBuffer 返回的每个 HardwareBuffer,然后才能调用 imageProxy.close。
  • setOutputImageRotationEnabled(true) 不受支持,并且在您调用 build 时会抛出 IllegalArgumentException。
  • ImageProxy.toBitmap 不受支持,并会抛出 IllegalArgumentException。

Kotlin

val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
val cameraInfo = cameraProvider.getCameraInfo(cameraSelector)
val capabilities = ImageAnalysis.getImageAnalysisCapabilities(cameraInfo)

// PRIVATE format isn't available on every device, so check capability
// before configuring it and fall back to YUV_420_888 for CPU access.
val useGpuBuffer = capabilities.isOutputFormatSupported(
    ImageAnalysis.OUTPUT_IMAGE_FORMAT_PRIVATE
)
val outputFormat = if (useGpuBuffer) {
    ImageAnalysis.OUTPUT_IMAGE_FORMAT_PRIVATE
} else {
    ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888
}

val imageAnalysis = ImageAnalysis.Builder()
    .setOutputImageFormat(outputFormat)
    .build()

imageAnalysis.setAnalyzer(analysisExecutor) { imageProxy ->
    try {
        // Guard on useGpuBuffer because YUV_420_888 images on API 28+
        // also return a HardwareBuffer. Close HardwareBuffer before
        // ImageProxy so native memory isn't leaked.
        if (
            useGpuBuffer &&
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
        ) {
            val hardwareBuffer = imageProxy.hardwareBuffer
            if (hardwareBuffer != null) {
                try {
                    // Process on the GPU to avoid a CPU readback copy.
                    processHardwareBuffer(hardwareBuffer)
                } finally {
                    hardwareBuffer.close()
                }
            }
        } else {
            processYuvPlanes(imageProxy)
        }
    } finally {
        // Close ImageProxy after HardwareBuffer so CameraX can deliver
        // new frames even if processing throws.
        imageProxy.close()
    }
}

Java

CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
CameraInfo cameraInfo = cameraProvider.getCameraInfo(cameraSelector);
ImageAnalysisCapabilities capabilities =
        ImageAnalysis.getImageAnalysisCapabilities(cameraInfo);

// PRIVATE format isn't available on every device, so check capability
// before configuring it and fall back to YUV_420_888 for CPU access.
boolean useGpuBuffer = capabilities.isOutputFormatSupported(
        ImageAnalysis.OUTPUT_IMAGE_FORMAT_PRIVATE);
int outputFormat = useGpuBuffer
        ? ImageAnalysis.OUTPUT_IMAGE_FORMAT_PRIVATE
        : ImageAnalysis.OUTPUT_IMAGE_FORMAT_YUV_420_888;

ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
        .setOutputImageFormat(outputFormat)
        .build();

imageAnalysis.setAnalyzer(analysisExecutor, imageProxy -> {
    try {
        // Guard on useGpuBuffer because YUV_420_888 images on API 28+
        // also return a HardwareBuffer. Close HardwareBuffer before
        // ImageProxy so native memory isn't leaked.
        if (useGpuBuffer
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            try (HardwareBuffer hardwareBuffer =
                    imageProxy.getHardwareBuffer()) {
                if (hardwareBuffer != null) {
                    // Process on the GPU to avoid a CPU readback copy.
                    processHardwareBuffer(hardwareBuffer);
                }
            }
        } else {
            processYuvPlanes(imageProxy);
        }
    } finally {
        // Close ImageProxy after HardwareBuffer so CameraX can deliver
        // new frames even if processing throws.
        imageProxy.close();
    }
});

其他资源

如需详细了解 CameraX,请参阅以下资源。

Codelab

  • CameraX 使用入门
  • 代码示例

    Camera 示例目录(请参阅 Luminosity、Image Labeling 和 QR Scanner 示例)