iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
Mobile Development

Kotlin Android 30天,從 0 到 ML (Machine Learning)系列 第 23

Kotlin Android 第23天,從 0 到 ML - CameraX

前言:

   今天來介紹如何創建使用 CameraX 來顯示預覽
    

大綱 :

build.gradle(app)

plugins{
    id 'kotlin-android-extensions'
}

dependencies {
    implementation "androidx.camera:camera-camera2:1.1.0-alpha08"
    implementation "androidx.camera:camera-lifecycle:1.1.0-alpha08"
    implementation 'androidx.camera:camera-view:1.0.0-alpha28'
}

**AndroidManifet.xml 宣告 CAMERA 權限 **

<uses-feature android:name="android.hardware.camera.any" />
<uses-permission android:name="android.permission.CAMERA" />

xml

…..
<androidx.camera.view.PreviewView
    android:id="@+id/previewView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent" />

<ImageButton
    android:id="@+id/capture_button"
    android:layout_width="72dp"
    android:layout_height="72dp"
    android:layout_margin="24dp"
    app:srcCompat="@android:drawable/ic_menu_camera"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />
…..

Activity:

typealias LumaListener = (luma: Double) -> Unit

class Day23Activity : AppCompatActivity() {

private var imageCapture: ImageCapture? = null

private lateinit var outputDirectory: File
private lateinit var cameraExecutor: ExecutorService

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_day23)

    // Request camera permissions
    if (allPermissionsGranted()) {
        startCamera()
    } else {
        ActivityCompat.requestPermissions(
            this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
    }

    // Set up the listener for take photo button
    capture_button.setOnClickListener { takePhoto() }

    outputDirectory = getOutputDirectory()

    cameraExecutor = Executors.newSingleThreadExecutor()

}


private fun startCamera() {
    
    val cameraProviderFuture = ProcessCameraProvider.getInstance(this)

    cameraProviderFuture.addListener(Runnable {
        
        // Used to bind the lifecycle of cameras to the lifecycle owner
        val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

        //初始化Preview
        // Preview
        val preview = Preview.Builder()
            .build()
            .also {
                it.setSurfaceProvider(previewView.surfaceProvider)
            }

        imageCapture = ImageCapture.Builder()
            .build()

        val imageAnalyzer = ImageAnalysis.Builder()
            .build()
            .also {
                it.setAnalyzer(cameraExecutor, LuminosityAnalyzer { luma ->
                    Log.d(TAG, "Average luminosity: $luma")
                })
            }

       
        // Select back camera as a default
        val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

        try {
            // Unbind use cases before rebinding
            cameraProvider.unbindAll()

            // Bind use cases to camera
            cameraProvider.bindToLifecycle(
                this, cameraSelector, preview)

        } catch(exc: Exception) {
           
            Log.e(TAG, "Use case binding failed", exc)
        }

    }, ContextCompat.getMainExecutor(this))
}

執行結果:
https://ithelp.ithome.com.tw/upload/images/20210928/2012164332ScSH6S3o.png

參考:

https://developer.android.com/codelabs/camerax-getting-started


上一篇
Kotlin Android 第22天,從 0 到 ML - Canvas
下一篇
Kotlin Android 第24天,從 0 到 ML - TensorFlow Lite
系列文
Kotlin Android 30天,從 0 到 ML (Machine Learning)30

尚未有邦友留言

立即登入留言