如何使用Android CameraX自动对焦

时间:2019-09-29 23:05:38

标签: android android-studio kotlin android-camerax

Android在最近几个月发布了新的API camerax。我正在尝试了解如何使相机自动对焦。

https://groups.google.com/a/android.com/forum/#!searchin/camerax-developers/auto $ 20focus | sort:date / camerax-developers / IQ3KZd8iOIY / LIbrRIqEBgAJ

这里是关于该主题的讨论,但是几乎没有特定的文档。

https://github.com/android/camera-samples/tree/master/CameraXBasic/app/src/main/java/com/android/example/cameraxbasic

这也是基本的camerax应用,但是我找不到任何与自动对焦有关的文件。

任何有关文档的提示或技巧都是有帮助的。另外,我对android还是很陌生,所以很可能会丢失一些使上面的链接更有用的东西。

6 个答案:

答案 0 :(得分:18)

使用当前的CameraX 1.0.0-beta03 & 1.0.0-alpha10工件,您可以通过以下两种方式进行操作:

  1. 每X秒自动对焦:

     previewView.afterMeasured {
         val factory: MeteringPointFactory = SurfaceOrientedMeteringPointFactory(
             previewView.width.toFloat(), previewView.height.toFloat())
         val centerWidth = previewView.width.toFloat() / 2
         val centerHeight = previewView.height.toFloat() / 2
         //create a point on the center of the view
         val autoFocusPoint = factory.createPoint(centerWidth, centerHeight)
         try {
             camera.cameraControl.startFocusAndMetering(
                 FocusMeteringAction.Builder(
                     autoFocusPoint,
                     FocusMeteringAction.FLAG_AF
                 ).apply {
                     //auto-focus every 2 seconds
                     setAutoCancelDuration(2, TimeUnit.SECONDS)
                 }.build()
             )
         } catch (e: CameraInfoUnavailableException) {
             Log.d("ERROR", "cannot access camera", e)
         }
     }
    
  2. 轻按一下即可

     previewView.afterMeasured {
         previewView.setOnTouchListener { _, event ->
             return@setOnTouchListener when (event.action) {
                 MotionEvent.ACTION_DOWN -> {
                     true
                 }
                 MotionEvent.ACTION_UP -> {
                     val factory: MeteringPointFactory = SurfaceOrientedMeteringPointFactory(
                         previewView.width.toFloat(), previewView.height.toFloat()
                     )
                     val autoFocusPoint = factory.createPoint(event.x, event.y)
                     try {
                         camera.cameraControl.startFocusAndMetering(
                             FocusMeteringAction.Builder(
                                 autoFocusPoint,
                                 FocusMeteringAction.FLAG_AF
                             ).apply {
                                 //focus only when the user tap the preview
                                 disableAutoCancel()
                             }.build()
                         )
                     } catch (e: CameraInfoUnavailableException) {
                         Log.d("ERROR", "cannot access camera", e)
                     }
                     true
                 }
                 else -> false // Unhandled event.
             }
         }
     }
    

afterMeasured 扩展功能是一个简单的实用程序:

inline fun View.afterMeasured(crossinline block: () -> Unit) {
    viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            if (measuredWidth > 0 && measuredHeight > 0) {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
                block()
            }
        }
    })
}

Camera对象可以通过

获得
val camera = cameraProvider.bindToLifecycle(
    this@Activity, cameraSelector, previewView //this is a PreviewView
)

答案 1 :(得分:1)

某些android设备存在一个问题,即相机无法使用CameraX自动对焦。 CameraX团队已意识到这一点,并正在使用内部票证对其进行跟踪,希望很快会得到修复。

答案 2 :(得分:1)

使用当前的 1.0.0-rc031.0.0-alpha22 工件

此解决方案假定相机已设置,包括 bindToLifecycle。之后我们需要在尝试聚焦相机之前检查 previewView streamState 是否为 STREAMING

 previewView.getPreviewStreamState().observe(getActivity(), value -> {
        if (value.equals(STREAMING)) {
            setUpCameraAutoFocus();
        }
    });

private void setUpCameraAutoFocus() {
    final float x =  previewView.getX() + previewView.getWidth() / 2f;
    final float y =  previewView.getY() + previewView.getHeight() / 2f;

  MeteringPointFactory pointFactory = previewView.getMeteringPointFactory();
  float afPointWidth = 1.0f / 6.0f;  // 1/6 total area
  float aePointWidth = afPointWidth * 1.5f;
  MeteringPoint afPoint = pointFactory.createPoint(x, y, afPointWidth);
  MeteringPoint aePoint = pointFactory.createPoint(x, y, aePointWidth);
  ListenableFuture<FocusMeteringResult> future = cameraControl.startFocusAndMetering(
          new FocusMeteringAction.Builder(afPoint,
                  FocusMeteringAction.FLAG_AF).addPoint(aePoint,
                  FocusMeteringAction.FLAG_AE).build());
  Futures.addCallback(future, new FutureCallback<FocusMeteringResult>() {
    @Override
    public void onSuccess(@Nullable FocusMeteringResult result) {
    }

    @Override
    public void onFailure(Throwable t) {
      // Throw the unexpected error.
      throw new RuntimeException(t);
    }
  }, CameraXExecutors.directExecutor());
}

答案 3 :(得分:0)

您可以在此处找到有关Focus的文档,因为它是在“ 1.0.0-alpha05”中添加的 https://developer.android.com/jetpack/androidx/releases/camera#camera2-core-1.0.0-alpha05

基本上,您必须在视图上设置一个触摸侦听器并抓住单击位置

private boolean onTouchToFocus(View viewA, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_UP:
                    return focus(event);
                break;
            default:
                // Unhandled event.
                return false;
        }
        return true;
    }

将此位置转换为点

private boolean focus(MotionEvent event) {
        final float x = (event != null) ? event.getX() : getView().getX() + getView().getWidth() / 2f;
        final float y = (event != null) ? event.getY() : getView().getY() + getView().getHeight() / 2f;

        TextureViewMeteringPointFactory pointFactory = new TextureViewMeteringPointFactory(textureView);
        float afPointWidth = 1.0f / 6.0f;  // 1/6 total area
        float aePointWidth = afPointWidth * 1.5f;
        MeteringPoint afPoint = pointFactory.createPoint(x, y, afPointWidth, 1.0f);
        MeteringPoint aePoint = pointFactory.createPoint(x, y, aePointWidth, 1.0f);

           try {
            CameraX.getCameraControl(lensFacing).startFocusAndMetering(
                FocusMeteringAction.Builder.from(afPoint, FocusMeteringAction.MeteringMode.AF_ONLY)
                                           .addPoint(aePoint, FocusMeteringAction.MeteringMode.AE_ONLY)
                                           .build());
        } catch (CameraInfoUnavailableException e) {
            Log.d(TAG, "cannot access camera", e);
        }

        return true;
    }

答案 4 :(得分:0)

只需指出,要使用PreviewView进行“轻按以聚焦”,您需要使用 DisplayOrientedMeteringPointFactory 。否则您会弄乱坐标。

val factory = DisplayOrientedMeteringPointFactory(activity.display, camera.cameraInfo, previewView.width.toFloat(), previewView.height.toFloat())

其余的请使用MatPag的答案。

答案 5 :(得分:0)

我遇到了同样的问题,我设置了这个解决方案(即使它看起来很愚蠢)。

val displayMetrics = resources.displayMetrics
val factory = SurfaceOrientedMeteringPointFactory(
    displayMetrics.widthPixels.toFloat(),
    displayMetrics.heightPixels.toFloat()
)
val point = factory.createPoint(
    displayMetrics.widthPixels / 2f,
    displayMetrics.heightPixels / 2f
)
val action = FocusMeteringAction
            .Builder(point, FocusMeteringAction.FLAG_AF)
            .build()

try {
    camera = cameraProvider.bindToLifecycle(
        lifecycleOwner,
        cameraSelector,
        preview,
        imageAnalyzer
    )
    GlobalScope.launch(Dispatchers.Default) {
        while (workflowModel.isCameraLive) {
            camera?.cameraControl?.startFocusAndMetering(action)?
            delay(3000)
        }
    }
} catch (e: Exception) {
    Log.e(mTag, "Use case binding failed", e)
}

基本上,我在 while 循环中每 3 秒重新启动一次聚焦操作。

isCameraLive 是一个布尔变量,我存储在我的 viewModel 中,我在启动相机时设置 true,当我通过调用 false 停止它时设置 cameraProvider.unbindAll()