Image analysis

The ImageAnalysis use case provides your app with CPU-accessible image buffers or GPU-accessible hardware buffers for image processing, computer vision, or machine learning inference. Your app implements an ImageAnalysis.Analyzer that runs its analyze method on each camera frame.

Compared with building your own frame pipeline on Camera2 and ImageReader, ImageAnalysis lets you focus on the analysis itself. CameraX runs analysis alongside Preview, VideoCapture, and ImageCapture in the same camera session, starts and stops it with your lifecycle, and drops frames when your analyzer falls behind so the preview stays smooth. It also delivers frames in the format your consumer expects (YUV, RGBA, NV21, or a GPU-accessible HardwareBuffer) with per-frame rotation metadata, so you don't write conversion or buffer-management code that behaves differently across devices.

For more information about integrating Google's ML Kit with CameraX, see ML Kit Analyzer.

Operating modes

When your analysis pipeline can't keep up with CameraX's frame rate, CameraX drops frames using one of two backpressure strategies configured with setBackpressureStrategy:

Mode Strategy constant Behavior Best for
Non-blocking (default) STRATEGY_KEEP_ONLY_LATEST Caches only the latest image in a single-frame buffer. New frames overwrite unprocessed ones. setImageQueueDepth has no effect. High-latency or variable-time analyzers where Preview and other use cases must stay smooth, such as live text translation, product recognition, or accessibility apps that describe a scene aloud.
Blocking STRATEGY_BLOCK_PRODUCER Buffers multiple images up to setImageQueueDepth before dropping frames. Stalls all bound use cases on the camera device, including Preview, when the queue is full. Pipelines that must process every frame and run faster than the frame interval, with brief jitter tolerance, such as motion detection, item counting, or heart-rate estimation from a fingertip over the lens.

With a fast analyzer whose total processing time stays under one camera frame interval (such as less than 16 ms at 60 fps), either mode delivers smooth results. Blocking mode with a deeper queue helps absorb brief scheduling jitter without dropping frames. If your analyzer takes longer than the frame interval, use the default non-blocking mode so ImageAnalysis drops stale frames without stalling Preview or VideoCapture. For details on executor interactions, see STRATEGY_KEEP_ONLY_LATEST and STRATEGY_BLOCK_PRODUCER.

Configure image analysis

Use ImageAnalysis.Builder to configure the frame format, resolution, rotation, and flow control.

Output image format

Choose the pixel format with setOutputImageFormat based on what consumes the frames in your pipeline. The default format is OUTPUT_IMAGE_FORMAT_YUV_420_888. The following table lists the supported output image formats and their typical use cases:

Format constant ImageProxy.getFormat Data access and notes Typical use cases
OUTPUT_IMAGE_FORMAT_YUV_420_888 ImageFormat.YUV_420_888 Three Y, U, and V planes in getPlanes. Offers the lowest conversion overhead. Barcode and QR code scanning in retail, ticketing, and payment apps, which use only the Y (luma) plane. Document scanners that detect page edges and exposure meters that measure luminance.
OUTPUT_IMAGE_FORMAT_RGBA_8888 PixelFormat.RGBA_8888 Single plane in planes[0].buffer packed in red, green, blue, alpha order. Other planes aren't used. Image classification and object detection models, such as LiteRT models, that expect RGB input tensors. Color-based tasks such as color pickers and paint-matching apps.
OUTPUT_IMAGE_FORMAT_NV21 ImageFormat.YUV_420_888 Three planes (Y, U, and V) where the U and V planes have pixel stride 2, storing interleaved VU bytes readable from planes[2]. Requires CameraX 1.5.0 and later. If you call getImage, the underlying android.media.Image can differ in plane layout or dimensions from ImageProxy. Native C or C++ pipelines, such as OpenCV or FFmpeg, face-detection SDKs, and video-calling or security encoders that expect NV21 frames from the legacy Camera API.
OUTPUT_IMAGE_FORMAT_PRIVATE ImageFormat.PRIVATE Zero-copy GPU-accessible HardwareBuffer using getHardwareBuffer in CameraX 1.7.0 and later. Requires a capability check. getPlanes returns an empty array. GPU-delegated ML inference, such as pose estimation, hand tracking, and background segmentation, where avoiding CPU readback keeps latency low enough for real-time results.

When you select OUTPUT_IMAGE_FORMAT_RGBA_8888, CameraX converts images from YUV to RGBA and packs bytes into the first plane's ByteBuffer in this repeating order:

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

Resolution and aspect ratio

Specify preferred dimensions and aspect ratios using setResolutionSelector. By default, ImageAnalysis targets 640x480. Request a specific resolution, such as 1280x720 with a 16:9 aspect ratio strategy, when your ML model expects a fixed input size or when you want to bound per-frame processing cost on low-end hardware, such as kiosk scanners. The exact output resolution depends on device hardware capabilities. For more information about configuring resolutions, see Camera resolution.

Image rotation

By default, CameraX passes buffers to your analyzer in sensor orientation and reports the clockwise rotation needed to make the image upright in imageProxy.imageInfo.rotationDegrees. If your analyzer requires already-rotated pixel buffers on Android 6.0 (API level 23) and higher, call setOutputImageRotationEnabled(true). That option adds per-frame rotation overhead and isn't supported with OUTPUT_IMAGE_FORMAT_PRIVATE.

Create and set an analyzer

Implement ImageAnalysis.Analyzer and override analyze(ImageProxy). Register your analyzer with setAnalyzer and unregister it with clearAnalyzer when analysis is finished. Calling setAnalyzer replaces any previously registered analyzer, and you can call it before or after binding the use case.

Inside analyze(ImageProxy), do the following:

  1. Process the frame within your frame budget (such as under 32 ms at 30 fps) or use STRATEGY_KEEP_ONLY_LATEST.
  2. For CPU-accessible formats (OUTPUT_IMAGE_FORMAT_YUV_420_888, OUTPUT_IMAGE_FORMAT_RGBA_8888, and OUTPUT_IMAGE_FORMAT_NV21), verify the format with imageProxy.getFormat, then read pixel planes through imageProxy.getPlanes or convert to a Bitmap with imageProxy.toBitmap.
  3. Close the ImageProxy with imageProxy.close in a finally block so CameraX can deliver subsequent frames. If you access the wrapped android.media.Image with imageProxy.getImage, never close it directly because closing ImageProxy releases the underlying image safely.

Bind image analysis to a lifecycle

Bind ImageAnalysis and Preview together using a SessionConfig and ProcessCameraProvider.bindToLifecycle. You can add other use cases to the same SessionConfig, such as VideoCapture for an app that shows a preview, runs segmentation, and records video at the same time. Supported combinations and resolutions vary by device; see Concurrent use cases. For more information about lifecycle binding and camera controls, see the CameraX API model and Control camera output.

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);
}

Analyze frames on the GPU

In CameraX 1.7.0 and later on Android 10 (API level 29) and higher, you can configure ImageAnalysis to output OUTPUT_IMAGE_FORMAT_PRIVATE frames backed by a GPU-sampled HardwareBuffer for zero-copy OpenGL or Vulkan inference pipelines, such as GPU-delegated pose estimation, hand tracking, or background segmentation.

First, check whether the camera supports OUTPUT_IMAGE_FORMAT_PRIVATE using getImageAnalysisCapabilities on ImageAnalysis and isOutputFormatSupported. When OUTPUT_IMAGE_FORMAT_PRIVATE is active, keep these requirements in mind:

  • ImageProxy.getPlanes returns an empty array. Read frames through ImageProxy.getHardwareBuffer, which requires Android 9 (API level 28) and higher (OUTPUT_IMAGE_FORMAT_PRIVATE itself requires Android 10 (API level 29) and higher).
  • You must close each HardwareBuffer returned by getHardwareBuffer before calling imageProxy.close.
  • setOutputImageRotationEnabled(true) is unsupported and throws IllegalArgumentException when you call build.
  • ImageProxy.toBitmap is unsupported and throws 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();
    }
});

Additional resources

For more information about CameraX, see the following resources.

Codelab

  • Getting Started with CameraX
  • Code sample

    Camera Samples catalog (see the Luminosity, Image Labeling, and QR Scanner samples)