Ken
Ken

Reputation: 529

Android Camera2 API, Best way to limit the focus distance?

I am trying to speed up barcode scanning which is slow with Google's Vision API due to the couple of seconds it takes to auto-focus. So, I want to try limiting the distance the camera tries to auto-focus so that it will always be within only a few cm instead of pulling from infinity.

However, I'm not sure how to achieve this as CaptureRequest doesn't seem to have anything for setting min/max focus distance. If I try to set a distance in the callback class CameraStateWatcher, nothing happens because AF just overrides it.

Is there somewhere I can override the focus distance value such as in CameraCaptureSession.CaptureCallback during onCaptureStarted etc?

I am using the following code:

    private class CameraCaptureWatcher extends CameraCaptureSession.CaptureCallback {

        // POSSIBLE TO OVERRIDE THE FOCUS DISTANCE IN HERE TO SET MIN/MAX?

        // oncapturestarted
        // oncapturecompleted

    }

    private class CameraStateWatcher extends CameraDevice.StateCallback {

        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {

            TestCamera.this.cameraDevice = cameraDevice;

            List<Surface> surfaces = new ArrayList<>();
            surfaces.add(previewSurface);
            surfaces.add(imageReader.getSurface());

            try {
                CaptureRequest.Builder captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

                // POSSIBLE TO SET MIN/MAX FOCUS DISTANCE WITH REQUEST?
                captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_OFF);

                for ( Surface surface : surfaces ) {
                    captureRequestBuilder.addTarget(surface);
                }

                captureRequest = captureRequestBuilder.build();

                for ( CaptureRequest.Key<?> key : captureRequest.getKeys() ) {
                    Log.d("STATE_WATCHER", "Request Key = " + key.getName());
                }

                cameraDevice.createCaptureSession(surfaces, cameraSurfaceWatcher, handler);

            } catch (CameraAccessException e) {
                e.printStackTrace();
            }

        }

    }

}

Upvotes: 1

Views: 1125

Answers (1)

Eddy Talvala
Eddy Talvala

Reputation: 18107

The only control the API has for this is selecting a MACRO autofocus mode, which isn't necessarily supported on all devices.

Your sample code doesn't seem to be using autofocus; which AF mode have you tried using? We generally recommend CONTINUOUS_FOCUS_PICTURE for most use cases, when supported by the device.

Upvotes: 1

Related Questions