Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use manual focus in Android CameraX?

I am trying to do manual focus on CameraX the same as I do in Camera2 API

in Camera2 API I use the following code

final CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); 

captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_OFF); 

captureBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, mLensFocusDistance);

Can manual focus be done in android camera X? If so how

Thanks in advance

like image 364
moLand Avatar asked Dec 02 '19 10:12

moLand


People also ask

How do I auto focus my CameraX Android?

Tap-To-Focus Autofocus is provided by default when using CameraX, but you can also manually specify the region the camera should focus on.


1 Answers

There is a way to use manual focus in cameraX by accessing low-level camera2 API with Camera2Interop.Extender. You should set two extra options to preview builder like this:

void setFocusDistance(ExtendableBuilder<?> builder, float distance) {
    Camera2Interop.Extender extender = new Camera2Interop.Extender(builder);
    extender.setCaptureRequestOption(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_OFF);
    extender.setCaptureRequestOption(CaptureRequest.LENS_FOCUS_DISTANCE, distance);
}

And use it when building your cameraX preview request:

float focusDistance = 0F; // example: infinite focus
Preview.Builder previewBuilder = new Preview.Builder();
setFocusDistance(previewBuilder, focusDistance);
preview = previewBuilder.build();
preview.setSurfaceProvider(viewFinder.getSurfaceProvider());

Note that you may also set other camera2 CaptureRequest options in this manner.


Here's how to find the LENS_INFO_MINIMUM_FOCUS_DISTANCE (often a value around 10f):

theCamera = cameraProvider.bindToLifecycle(...
CameraCharacteristics camChars = Camera2CameraInfo
   .extractCameraCharacteristics(theCamera.getCameraInfo());
float discoveredMinFocusDistance = camChars
   .get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE);
Log.i("dev", "found it! " + discoveredMinFocusDistance);
like image 161
Mikhail Avatar answered Sep 21 '22 00:09

Mikhail