如何使用camera2 api获取帧

时间:2017-11-15 14:27:57

标签: java android

我使用camera2 api来获取相机帧,这是我写的代码

private void startPreview() {
    SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
    surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    Surface previewSurface = new Surface(surfaceTexture);

    try {
        mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mCaptureRequestBuilder.addTarget(previewSurface);

        mCameraDevice.createCaptureSession(Arrays.asList(previewSurface),
                new CameraCaptureSession.StateCallback() {
                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession session) {
                        try {
                            session.setRepeatingRequest(mCaptureRequestBuilder.build(),
                                    new CameraCaptureSession.CaptureCallback() {

                                        @Override
                                        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                                            super.onCaptureCompleted(session, request, result);
                                            Log.i("State preview", "process: frame");

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

                    @Override
                    public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                        Toast.makeText(getApplicationContext(),
                                "Unable to setup camera preview", Toast.LENGTH_SHORT).show();
                    }
                }, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

}

我能够通过这一行看到帧日志:

session.setRepeatingRequest(mCaptureRequestBuilder.build(),
                                    new CameraCaptureSession.CaptureCallback() {

                                        @Override
                                        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                                            super.onCaptureCompleted(session, request, result);
                                            Log.i("State preview", "process: frame");

                                        }
                                    }, mBackgoundThreadHandler);

所以从这个函数我怎么得到框架。 我对camera2 api完全不熟悉所以有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

您的代码目前正在为您的TextureView绘制相机预览;如果您想要应用程序代码可以读取的第二个输出,则需要创建第二个输出并将其提供给相机。

根据您要执行的处理类型,您需要ImageReader用于Java级访问,SurfaceTexture(用于在OpenGL中读取)或Allocation(对于RenderScript)。从这些中,您可以将Surface包含在会话创建和创建捕获请求中。

每个回调都会在新帧可用时触发。 onCaptureCompleted仅提供捕获元数据。