android/camera-samples

Image Analysis results are not the same as Preview

muhrafitriandi opened this issue · 0 comments

private fun bindCameraUseCases() = with(binding.viewFinder) {
    val screenAspectRatio = AspectRatio.RATIO_16_9
    val viewPort = ViewPort.Builder(
        Rational(
            width,
            height
        ), display.rotation
    ).build()
    val cameraProvider = cameraProvider ?: throw IllegalStateException(getString(R.string.res_error_camera_start))
    val cameraSelector = CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build()

    preview = Preview.Builder()
        .setTargetAspectRatio(screenAspectRatio)
        .build()

    imageAnalyzer = ImageAnalysis.Builder()
        .setTargetAspectRatio(screenAspectRatio)
        .setTargetRotation(display.rotation)
        .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
        .setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)
        .build()

    val useCaseGroup = UseCaseGroup.Builder()
        .addUseCase(preview!!)
        .addUseCase(imageAnalyzer)
        .setViewPort(viewPort)
        .build()

    cameraProvider.unbindAll()

    if (camera != null) {
        removeCameraStateObservers(camera!!.cameraInfo)
    }

    try {
        camera = cameraProvider.bindToLifecycle(viewLifecycleOwner, cameraSelector, useCaseGroup)
        preview?.setSurfaceProvider(surfaceProvider)
    } catch (exc: Exception) {
        requireActivity().toast(getString(R.string.res_error_camera_use_case))
    }

    camera?.cameraControl?.enableTorch(viewModel.isFlashOn.value)
}