Android Camera2 API 同时使用前后摄像头预览

发表于 1年以前  | 总阅读数:1601 次

不久前,我承担了从运行Android的设备的前后摄像头获取同步提要的任务。 像往常一样,我去了Stack Overflow,然后去了GitHub,然后去了其他博客,才意识到我可能独自一人。 难过的感觉吧?

在能够解决问题之后,我花了一些时间来帮助可能会陷入同样困境的人们。

我已经为本教程制作了一个示例应用程序。本教程中共享的所有代码段均来自应用程序本身。如果您在任何时候都不了解代码段,则可以引用整个合并文件。您可以在GitHub上找到本教程的示例应用程序:

如果您是Android相机的新手,则android / camera-samples存储库将是一个很好的起点。

注意:Java实现已从android / camera-samples中删除。对于Java实现,您可以参考此分叉存储库 。

在本教程中,假定您能够自己实现相机供稿。 如果不是这种情况,请访问上述存储库。 本教程将更加有意义。 否则,您可能会发现自己迷路了。

设置预览视图 (Set Up Views for Preview)

We will require two separate views to present the preview from two cameras. We will start small by creating views to show the previews:

我们将需要两个单独的视图来展示两个摄像机的预览。我们将首先创建视图以显示预览:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <!--This is a custom TextureView, generic TextureView can be used as well-->
    <com.ananth.frontrearcamera.view.AutoFitTextureView
        android:layout_weight="1"
        android:id="@+id/texture1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


    <com.ananth.frontrearcamera.view.AutoFitTextureView
        android:layout_weight="1"
        android:id="@+id/texture2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


</LinearLayout>

Now, before opening our cameras, we need to make sure both of their TextureViews are available for rendering using TextureView.SurfaceTextureListener.

现在,在打开相机之前,我们需要确保它们的两个TextureViews都可以使用TextureView.SurfaceTextureListener进行渲染。

We will be following a complete separation of concerns. Both TextureViews will have their own listeners. Listeners will open concerned cameras asynchronously without depending on the other. The separation of concerns is to such an extent that even if one camera is not able to show a preview for some reason, the other might function flawlessly.

我们将完全消除关注点。两个TextureViews都有自己的侦听器。侦听器将异步打开相关的摄像机,而不会彼此依赖。关注点分离的程度是,即使一台摄像机由于某种原因无法显示预览,另一台摄像机也可能会正常工作。

The listeners will open their respective camera when the views become available using onSurfaceTextureAvailable(SurfaceTexture, Int, Int):

当使用onSurfaceTextureAvailable(SurfaceTexture, Int, Int)提供视图时,侦听器将打开各自的摄像头:

private val surfaceTextureListenerFront = object : TextureView.SurfaceTextureListener {
        override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) {
            openCameraFront(width, height)
        }
        override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) {
            configureTransformFront(width, height)
        }
        override fun onSurfaceTextureDestroyed(texture: SurfaceTexture) = true
        override fun onSurfaceTextureUpdated(texture: SurfaceTexture) = Unit
    }


    private val surfaceTextureListenerRear = object : TextureView.SurfaceTextureListener {
        override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) {
            openCameraRear(width, height)
        }
        override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) {
            configureTransformRear(width, height)
        }
        override fun onSurfaceTextureDestroyed(texture: SurfaceTexture) = true
        override fun onSurfaceTextureUpdated(texture: SurfaceTexture) = Unit
    }

打开两个摄像头 (Open Both Cameras)

Our openCameraFront(int, int) and openCameraRear(int, int) functions will set up front and rear camera parameters before actually opening the camera. These parameters are different for different cameras. Therefore, they need to be set separately. What parameters are we talking about? Parameters like:

我们的openCameraFront(int, int)openCameraRear(int, int)函数将在实际打开相机之前设置前后相机参数。对于不同的相机,这些参数是不同的。因此,它们需要单独设置。我们在说什么参数?参数如下:

  1. Camera ID 相机编号
  2. Sensor orientation 传感器方向
  3. Width and height of the image required from the camera 相机所需图像的宽度和高度

This is achieved in the function below. The code concerning only the front camera is attached (it is similar for the rear camera):

这是通过以下功能实现的。随附仅涉及前置摄像头的代码(对于后置摄像头类似):

/**
     * Sets up member variables related to front camera.
     * @param width  The width of available size for camera preview
     * @param height The height of available size for camera preview
     */
    private fun setUpCameraOutputsFront(width: Int, height: Int) {
        val manager = activity?.getSystemService(Context.CAMERA_SERVICE) as CameraManager
        try {
            for (cameraId in manager.cameraIdList) {
                val characteristics = manager.getCameraCharacteristics(cameraId)


                // We need front facing camera.
                val cameraDirection = characteristics.get(CameraCharacteristics.LENS_FACING)
                if (cameraDirection != null &&
                    cameraDirection == CameraCharacteristics.LENS_FACING_BACK) {
                    continue
                }
                val map = characteristics.get(
                    CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) ?: continue


                // For still image captures, we use the largest available size.
                val aspectRatio = Collections.max(Arrays.asList(*map.getOutputSizes(ImageFormat.JPEG)), CompareSizesByViewAspectRatio(textureViewFront.height, textureViewFront.width))

                imageReaderFront = ImageReader.newInstance(aspectRatio.width, aspectRatio.height, ImageFormat.JPEG, /*maxImages*/ 2).apply {
                    setOnImageAvailableListener(onImageAvailableListenerFront, backgroundHandler)
                }
                // Find out if we need to swap dimension to get the preview size relative to sensor
                // coordinate.
                val displayRotation = activity!!.windowManager.defaultDisplay.rotation


                sensorOrientationFront = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!!
                val swappedDimensions = areDimensionsSwappedFront(displayRotation)


                val displaySize = Point()
                activity!!.windowManager.defaultDisplay.getSize(displaySize)
                val rotatedPreviewWidth = if (swappedDimensions) height else width
                val rotatedPreviewHeight = if (swappedDimensions) width else height
                var maxPreviewWidth = if (swappedDimensions) displaySize.y else displaySize.x
                var maxPreviewHeight = if (swappedDimensions) displaySize.x else displaySize.y


                if (maxPreviewWidth > MAX_PREVIEW_WIDTH) maxPreviewWidth = MAX_PREVIEW_WIDTH
                if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) maxPreviewHeight = MAX_PREVIEW_HEIGHT


                previewSizeFront = chooseOptimalSize(map.getOutputSizes(SurfaceTexture::class.java),
                    rotatedPreviewWidth, rotatedPreviewHeight,
                    maxPreviewWidth, maxPreviewHeight,
                    aspectRatio)


                this.cameraIdFront = cameraId
                // We've found a viable camera and finished setting up member variables,
                // so we don't need to iterate through other available cameras.
                return
            }
        } catch (e: CameraAccessException) {
            Log.e(TAG, e.toString())
        } catch (e: NullPointerException) {
            // Currently an NPE is thrown when the Camera2API is used but not supported on the
            // device this code runs.
            ErrorDialog.newInstance(getString(R.string.camera_error))
                .show(childFragmentManager, FRAGMENT_DIALOG)
        }
    }

Now that we have set up our parameters for the front and rear cameras, we are set to open both of them.

现在我们已经设置了前置摄像头和后置摄像头的参数,现在可以将它们都打开。

private fun openCameraFront(width: Int, height: Int) {
        setUpCameraOutputsFront(width, height)
        configureTransformFront(width, height)
        val manager = activity?.getSystemService(Context.CAMERA_SERVICE) as CameraManager
        try {
            manager.openCamera(cameraIdFront, stateCallbackFront, backgroundHandler)
        } catch (e: CameraAccessException) {
            Log.e(TAG, e.toString())
        } 
    }


    private fun openCameraRear(width: Int, height: Int) {
        setUpCameraOutputsRear(width, height)
        configureTransformRear(width, height)
        val manager = activity?.getSystemService(Context.CAMERA_SERVICE) as CameraManager
        try {
            manager.openCamera(cameraIdRear, stateCallbackRear, backgroundHandler)
        } catch (e: CameraAccessException) {
            Log.e(TAG, e.toString())
        }
    }

Opening the camera is an asynchronous process. The success or failure is reported and handled using CameraDevice.StateCallback, which is passed as an argument while opening the camera and is not nullable.

打开相机是一个异步过程。使用CameraDevice.StateCallback报告和处理成功或失败,它在打开相机时作为参数传递,并且不能为空。

Make sure that the camera’s permissions are given to the application and no other higher-priority application is using any of the camera. Otherwise, the camera-opening request will fail. This will be reported by throwing a CameraAccessException in the CameraDevice.StateCallback#onError by the respective camera device.

确保已将相机的权限授予该应用程序,并且没有其他更高优先级的应用程序在使用任何相机。否则,打开摄像机的请求将失败。这将通过由相应的相机设备在CameraDevice.StateCallback#onError中抛出CameraAccessException来报告。

At this point, the device will attempt to open both cameras simultaneously. If we get the CameraDevice.StateCallback#onOpened callback for both cameras, we have successfully opened them. We can check the success or failure using logs and can debug in case of any challenges. For reference, this is how I have implemented CameraDevice.StateCallback for the front camera in this project (it is similar for the rear camera):

此时,设备将尝试同时打开两个摄像机。如果我们同时获得两个摄像机的CameraDevice.StateCallback#onOpened回调,则我们已成功打开它们。我们可以使用日志检查成功或失败,并可以在遇到任何挑战时进行调试。供参考,这是我实现CameraDevice.StateCallback 该项目中的前置摄像头(与后置摄像头类似):

private val stateCallbackFront = object : CameraDevice.StateCallback() {
  override fun onOpened(cameraDevice: CameraDevice) {
    this@CameraFragment.cameraDeviceFront = cameraDevie
    createCameraPreviewSessionFront()
  }
override fun onDisconnected(cameraDevice: CameraDevice) {
  cameraDevice.close()
  this@CameraFragment.cameraDeviceFront = null
  }
override fun onError(cameraDevice: CameraDevice, error: Int) {
  onDisconnected(cameraDevice)
  this@CameraFragment.activity?.finish()
  }
}

从两个相机获取预览 (Get Preview From Both Cameras)

We have done most of the heavy lifting. We are only left with directing a feed from the cameras to the respective views. For this, we will have to create a Surface and hand it over to our CameraDevice. Now, according to the Surface, CameraDevice adjusts its hardware processing pipelines to give outputs at requested sizes.

我们已经完成了大部分繁重的工作。我们仅需将摄影机的提要定向到各个视图。为此,我们将必须创建一个Surface并将其移交给我们的CameraDevice 。现在,根据Surface,CameraDevice调整其硬件处理管道以提供所需大小的输出。

Since we only need to get previews from the cameras for now, our TextureViews will serve as our Surfaces. We will be creating a CameraCaptureSession for both the front and rear cameras separately, passing respective Surfaces to get a preview:

由于我们现在仅需要从摄像机获取预览,因此我们的TextureViews将用作Surface。我们将分别为前置和后置摄像头创建一个CameraCaptureSession,并传递各自的Surface以获得预览:

private fun createCameraPreviewSessionFront() {
  try {
    val texture = textureViewFront.surfaceTexture


    texture.setDefaultBufferSize(previewSizeFront.width, previewSizeFront.height)
    val surface = Surface(texture)
    previewRequestBuilderFront = cameraDeviceFront!!.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
    previewRequestBuilderFront.addTarget(surface)


    // Here, we create a CameraCaptureSession for camera preview.
    cameraDeviceFront?.createCaptureSession(Arrays.asList(surface, imageReaderFront?.surface), object : CameraCaptureSession.StateCallback() {
      override fun onConfigured(cameraCaptureSession: CameraCaptureSession) {
                        // The camera is already closed
        if (cameraDeviceFront == null) return
        // When the session is ready, we start displaying the preview.
        captureSessionFront = cameraCaptureSession
        try {
          // Auto focus should be continuous for camera preview.
          previewRequestBuilderFront.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
          // Finally, we start displaying the camera preview.
          previewRequestFront = previewRequestBuilderFront.build()
          captureSessionFront?.setRepeatingRequest(previewRequestFront, captureCallback, backgroundHandler)
        } catch (e: CameraAccessException) {
          Log.e(TAG, e.toString())
        }
      }
      override fun onConfigureFailed(session: CameraCaptureSession) {
      }
    }, null)
  } catch (e: CameraAccessException) {
    Log.e(TAG, e.toString())
  }
}

That’s all. You can visit CameraFragment.kt to see all this consolidated working code. The Camera2 API is like a DSLR if the Camera API was a point-and-shoot camera. It might seem overwhelming, but its beauty is the fine controls it provides over the camera feed.

就这样。您可以访问CameraFragment.kt来查看所有这些合并的工作代码。如果Camera API是傻瓜相机,则Camera2 API就像DSLR。它看起来似乎不知所措,但是它的优点在于它可以很好地控制摄像机的提要。

结论 (Conclusion)

如果您了解Camera2的复杂性,他们可以弄清楚如何在策略上同时使用两台摄像机。 我鼓励您继续尝试一键同时从两个摄像机捕获图像。

如果您有任何建议,反馈或问题,我希望收到您的来信。

本文由哈喽比特于1年以前收录,如有侵权请联系我们。
文章来源:https://mp.weixin.qq.com/s/e-111i5cJ9iGyahlXFFCyw

 相关推荐

刘强东夫妇:“移民美国”传言被驳斥

京东创始人刘强东和其妻子章泽天最近成为了互联网舆论关注的焦点。有关他们“移民美国”和在美国购买豪宅的传言在互联网上广泛传播。然而,京东官方通过微博发言人发布的消息澄清了这些传言,称这些言论纯属虚假信息和蓄意捏造。

发布于:7月以前  |  808次阅读  |  详细内容 »

博主曝三大运营商,将集体采购百万台华为Mate60系列

日前,据博主“@超能数码君老周”爆料,国内三大运营商中国移动、中国电信和中国联通预计将集体采购百万台规模的华为Mate60系列手机。

发布于:7月以前  |  770次阅读  |  详细内容 »

ASML CEO警告:出口管制不是可行做法,不要“逼迫中国大陆创新”

据报道,荷兰半导体设备公司ASML正看到美国对华遏制政策的负面影响。阿斯麦(ASML)CEO彼得·温宁克在一档电视节目中分享了他对中国大陆问题以及该公司面临的出口管制和保护主义的看法。彼得曾在多个场合表达了他对出口管制以及中荷经济关系的担忧。

发布于:7月以前  |  756次阅读  |  详细内容 »

抖音中长视频App青桃更名抖音精选,字节再发力对抗B站

今年早些时候,抖音悄然上线了一款名为“青桃”的 App,Slogan 为“看见你的热爱”,根据应用介绍可知,“青桃”是一个属于年轻人的兴趣知识视频平台,由抖音官方出品的中长视频关联版本,整体风格有些类似B站。

发布于:7月以前  |  648次阅读  |  详细内容 »

威马CDO:中国每百户家庭仅17户有车

日前,威马汽车首席数据官梅松林转发了一份“世界各国地区拥车率排行榜”,同时,他发文表示:中国汽车普及率低于非洲国家尼日利亚,每百户家庭仅17户有车。意大利世界排名第一,每十户中九户有车。

发布于:7月以前  |  589次阅读  |  详细内容 »

研究发现维生素 C 等抗氧化剂会刺激癌症生长和转移

近日,一项新的研究发现,维生素 C 和 E 等抗氧化剂会激活一种机制,刺激癌症肿瘤中新血管的生长,帮助它们生长和扩散。

发布于:7月以前  |  449次阅读  |  详细内容 »

苹果据称正引入3D打印技术,用以生产智能手表的钢质底盘

据媒体援引消息人士报道,苹果公司正在测试使用3D打印技术来生产其智能手表的钢质底盘。消息传出后,3D系统一度大涨超10%,不过截至周三收盘,该股涨幅回落至2%以内。

发布于:7月以前  |  446次阅读  |  详细内容 »

千万级抖音网红秀才账号被封禁

9月2日,坐拥千万粉丝的网红主播“秀才”账号被封禁,在社交媒体平台上引发热议。平台相关负责人表示,“秀才”账号违反平台相关规定,已封禁。据知情人士透露,秀才近期被举报存在违法行为,这可能是他被封禁的部分原因。据悉,“秀才”年龄39岁,是安徽省亳州市蒙城县人,抖音网红,粉丝数量超1200万。他曾被称为“中老年...

发布于:7月以前  |  445次阅读  |  详细内容 »

亚马逊股东起诉公司和贝索斯,称其在购买卫星发射服务时忽视了 SpaceX

9月3日消息,亚马逊的一些股东,包括持有该公司股票的一家养老基金,日前对亚马逊、其创始人贝索斯和其董事会提起诉讼,指控他们在为 Project Kuiper 卫星星座项目购买发射服务时“违反了信义义务”。

发布于:7月以前  |  444次阅读  |  详细内容 »

苹果上线AppsbyApple网站,以推广自家应用程序

据消息,为推广自家应用,苹果现推出了一个名为“Apps by Apple”的网站,展示了苹果为旗下产品(如 iPhone、iPad、Apple Watch、Mac 和 Apple TV)开发的各种应用程序。

发布于:7月以前  |  442次阅读  |  详细内容 »

特斯拉美国降价引发投资者不满:“这是短期麻醉剂”

特斯拉本周在美国大幅下调Model S和X售价,引发了该公司一些最坚定支持者的不满。知名特斯拉多头、未来基金(Future Fund)管理合伙人加里·布莱克发帖称,降价是一种“短期麻醉剂”,会让潜在客户等待进一步降价。

发布于:7月以前  |  441次阅读  |  详细内容 »

光刻机巨头阿斯麦:拿到许可,继续对华出口

据外媒9月2日报道,荷兰半导体设备制造商阿斯麦称,尽管荷兰政府颁布的半导体设备出口管制新规9月正式生效,但该公司已获得在2023年底以前向中国运送受限制芯片制造机器的许可。

发布于:7月以前  |  437次阅读  |  详细内容 »

马斯克与库克首次隔空合作:为苹果提供卫星服务

近日,根据美国证券交易委员会的文件显示,苹果卫星服务提供商 Globalstar 近期向马斯克旗下的 SpaceX 支付 6400 万美元(约 4.65 亿元人民币)。用于在 2023-2025 年期间,发射卫星,进一步扩展苹果 iPhone 系列的 SOS 卫星服务。

发布于:7月以前  |  430次阅读  |  详细内容 »

𝕏(推特)调整隐私政策,可拿用户发布的信息训练 AI 模型

据报道,马斯克旗下社交平台𝕏(推特)日前调整了隐私政策,允许 𝕏 使用用户发布的信息来训练其人工智能(AI)模型。新的隐私政策将于 9 月 29 日生效。新政策规定,𝕏可能会使用所收集到的平台信息和公开可用的信息,来帮助训练 𝕏 的机器学习或人工智能模型。

发布于:7月以前  |  428次阅读  |  详细内容 »

荣耀CEO谈华为手机回归:替老同事们高兴,对行业也是好事

9月2日,荣耀CEO赵明在采访中谈及华为手机回归时表示,替老同事们高兴,觉得手机行业,由于华为的回归,让竞争充满了更多的可能性和更多的魅力,对行业来说也是件好事。

发布于:7月以前  |  423次阅读  |  详细内容 »

AI操控无人机能力超越人类冠军

《自然》30日发表的一篇论文报道了一个名为Swift的人工智能(AI)系统,该系统驾驶无人机的能力可在真实世界中一对一冠军赛里战胜人类对手。

发布于:7月以前  |  423次阅读  |  详细内容 »

AI生成的蘑菇科普书存在可致命错误

近日,非营利组织纽约真菌学会(NYMS)发出警告,表示亚马逊为代表的电商平台上,充斥着各种AI生成的蘑菇觅食科普书籍,其中存在诸多错误。

发布于:7月以前  |  420次阅读  |  详细内容 »

社交媒体平台𝕏计划收集用户生物识别数据与工作教育经历

社交媒体平台𝕏(原推特)新隐私政策提到:“在您同意的情况下,我们可能出于安全、安保和身份识别目的收集和使用您的生物识别信息。”

发布于:7月以前  |  411次阅读  |  详细内容 »

国产扫地机器人热销欧洲,国产割草机器人抢占欧洲草坪

2023年德国柏林消费电子展上,各大企业都带来了最新的理念和产品,而高端化、本土化的中国产品正在不断吸引欧洲等国际市场的目光。

发布于:7月以前  |  406次阅读  |  详细内容 »

罗永浩吐槽iPhone15和14不会有区别,除了序列号变了

罗永浩日前在直播中吐槽苹果即将推出的 iPhone 新品,具体内容为:“以我对我‘子公司’的了解,我认为 iPhone 15 跟 iPhone 14 不会有什么区别的,除了序(列)号变了,这个‘不要脸’的东西,这个‘臭厨子’。

发布于:7月以前  |  398次阅读  |  详细内容 »
 相关文章
简化Android的UI开发 4年以前  |  520700次阅读
Android 深色模式适配原理分析 3年以前  |  28625次阅读
Android阴影实现的几种方案 1年以前  |  10785次阅读
Android 样式系统 | 主题背景覆盖 3年以前  |  9586次阅读
 目录