如何使用camera2 API将焦距强制为固定值?

时间:2019-05-17 12:47:06

标签: android android-camera2

我已经为Android创建了一个计算机视觉应用。我使用前置摄像头捕捉应用了算法的图像。在我的Samsung Galaxy S8上,我观察到当我将物体放在相机前面时,焦距会随着自动对焦而变化(它会不断放大和缩小)。这是一个问题,因为它会在图像中产生不必要的变化,这些变化会随着我的算法而改变。如何确定焦距的合理值,然后在不禁用自动对焦的情况下迫使传感器保持固定不变?

这是我用于设置摄像头采集的代码。

private void createCameraPreviewSession() throws CameraAccessException {
    mCameraDevice.createCaptureSession(Arrays.asList(mImageReader.getSurface()),
            new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(CameraCaptureSession cameraCaptureSession) {
                    if (null == mCameraDevice) {
                        return;
                    }
                    mCaptureSession = cameraCaptureSession;
                    try {
                        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                                CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
                                CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);

                        mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler);
                    } catch (Exception e) {
                        Log.e(Config.tag, "createCaptureSession failed", e);
                    }
                }

                @Override
                public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {
                    Log.e(Config.tag, "createCameraPreviewSession failed");
                }
            },
            null
    );
}

private void createImageReader() throws CameraAccessException
{
    mImageReader = ImageReader.newInstance(mFrameSize.getWidth(), mFrameSize.getHeight(),
            mPreviewFormat, 2);
    mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
        @Override
        public void onImageAvailable(ImageReader reader) {
            if (mCaptureSession == null) {
                return;
            }
            Image image = reader.acquireLatestImage();
            if (image == null) {
                return;
            }

            //do something with the image

            image.close();
        }
    }, mBackgroundHandler);
    Surface surface = mImageReader.getSurface();

    mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
    mPreviewRequestBuilder.addTarget(surface);
}

1 个答案:

答案 0 :(得分:0)

我发现使用CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE是试图不断保持图像聚焦的模式。以我为例,在某些带有多个前置镜头的高端设备上,这可能会导致镜头之间的切换。我只是将自动对焦模式更改为CaptureRequest.CONTROL_AF_MODE_AUTO,自动对焦停止不断更改焦点。另外,我使用CaptureRequest.CONTROL_AE_LOCK选项在关键时刻锁定和解锁自动曝光,以避免不必要的曝光变化。