Необходимо сделать неподвижное изображение во время распознавания лица с помощью MLKit и Camera2 - PullRequest
1 голос
/ 24 апреля 2020

Я разрабатываю функцию распознавания лиц с Camera2 и MLKit .

В Руководстве разработчика в Советы по повышению производительности часть, они говорят, что для захвата изображений в формате ImageFormat.YUV_420_888 при использовании Camera2 API, что в моем случае.

Затем, в части Face Detector , они рекомендуют использовать изображение размером не менее 480x360 пикселей для распознавания лиц в реальном времени, что опять-таки мой случай.

Хорошо, давайте go! Вот мой код, хорошо работающий

private fun initializeCamera() = lifecycleScope.launch(Dispatchers.Main) {

    // Open the selected camera
    cameraDevice = openCamera(cameraManager, getCameraId(), cameraHandler)

    val previewSize = if (isPortrait) {
        Size(RECOMMANDED_CAPTURE_SIZE.width, RECOMMANDED_CAPTURE_SIZE.height)
    } else {
        Size(RECOMMANDED_CAPTURE_SIZE.height, RECOMMANDED_CAPTURE_SIZE.width)
    }

    // Initialize an image reader which will be used to display a preview
    imageReader = ImageReader.newInstance(
            previewSize.width, previewSize.height, ImageFormat.YUV_420_888, IMAGE_BUFFER_SIZE)

    // Retrieve preview's frame and run detector
    imageReader.setOnImageAvailableListener({ reader ->
        lifecycleScope.launch(Dispatchers.Main) {
            val image = reader.acquireNextImage()
            logD { "Image available: ${image.timestamp}" }
            faceDetector.runFaceDetection(image, getRotationCompensation())
            image.close()
        }
    }, imageReaderHandler)

    // Creates list of Surfaces where the camera will output frames
    val targets = listOf(viewfinder.holder.surface, imageReader.surface)

    // Start a capture session using our open camera and list of Surfaces where frames will go
    session = createCaptureSession(cameraDevice, targets, cameraHandler)
    val captureRequest = cameraDevice.createCaptureRequest(
            CameraDevice.TEMPLATE_PREVIEW).apply {
        addTarget(viewfinder.holder.surface)
        addTarget(imageReader.surface)
    }

    // This will keep sending the capture request as frequently as possible until the
    // session is torn down or session.stopRepeating() is called
    session.setRepeatingRequest(captureRequest.build(), null, cameraHandler)
}

Теперь я хочу сделать неподвижное изображение ... и это моя проблема, потому что в идеале я хочу:

  • a Изображение в полном разрешении или, как минимум, больше, чем 480x360
  • в формате JPEG, чтобы его можно было сохранить

Camera2Basi c семпл демонстрирует, как захватить изображение (сбои образцов для Video и SlowMotion) и образец MLKit использует столь старый Camera Camera !! К счастью, мне удалось смешать эти образцы для разработки своей функции, но мне не удалось получить неподвижное изображение с другим разрешением.

Я думаю, что мне нужно остановить сеанс предварительного просмотра воссоздать один для захвата изображения, но я не уверен ...

Я сделал следующее, но он захватывает изображения в разрешении 480x360:

session.stopRepeating()

 // Unset the image reader listener
 imageReader.setOnImageAvailableListener(null, null)
 // Initialize an new image reader which will be used to capture still photos
 // imageReader = ImageReader.newInstance(768, 1024, ImageFormat.JPEG, IMAGE_BUFFER_SIZE)

 // Start a new image queue
 val imageQueue = ArrayBlockingQueue<Image>(IMAGE_BUFFER_SIZE)
 imageReader.setOnImageAvailableListener({ reader - >
    val image = reader.acquireNextImage()
    logD {"[Still] Image available in queue: ${image.timestamp}"}
    if (imageQueue.size >= IMAGE_BUFFER_SIZE - 1) {
        imageQueue.take().close()
    }
    imageQueue.add(image)
}, imageReaderHandler)

 // Creates list of Surfaces where the camera will output frames
 val targets = listOf(viewfinder.holder.surface, imageReader.surface)
 val captureRequest = createStillCaptureRequest(cameraDevice, targets)
 session.capture(captureRequest, object: CameraCaptureSession.CaptureCallback() {
    override fun onCaptureCompleted(
        session: CameraCaptureSession,
        request: CaptureRequest,
        result: TotalCaptureResult) {
        super.onCaptureCompleted(session, request, result)
        val resultTimestamp = result.get(CaptureResult.SENSOR_TIMESTAMP)
        logD {"Capture result received: $resultTimestamp"}
        // Set a timeout in case image captured is dropped from the pipeline
        val exc = TimeoutException("Image dequeuing took too long")
        val timeoutRunnable = Runnable {
            continuation.resumeWithException(exc)
        }
        imageReaderHandler.postDelayed(timeoutRunnable, IMAGE_CAPTURE_TIMEOUT_MILLIS)
        // Loop in the coroutine's context until an image with matching timestamp comes
        // We need to launch the coroutine context again because the callback is done in
        //  the handler provided to the `capture` method, not in our coroutine context
        @ Suppress("BlockingMethodInNonBlockingContext")
        lifecycleScope.launch(continuation.context) {
            while (true) {
                // Dequeue images while timestamps don't match
                val image = imageQueue.take()
                if (image.timestamp != resultTimestamp)
                  continue
                logD {"Matching image dequeued: ${image.timestamp}"}

                // Unset the image reader listener
                imageReaderHandler.removeCallbacks(timeoutRunnable)
                imageReader.setOnImageAvailableListener(null, null)

                // Clear the queue of images, if there are left
                while (imageQueue.size > 0) {
                    imageQueue.take()
                        .close()
                }
                // Compute EXIF orientation metadata
                val rotation = getRotationCompensation()
                val mirrored = cameraFacing == CameraCharacteristics.LENS_FACING_FRONT
                val exifOrientation = computeExifOrientation(rotation, mirrored)
                logE {"captured image size (w/h): ${image.width} / ${image.height}"}
                // Build the result and resume progress
                continuation.resume(CombinedCaptureResult(
                    image, result, exifOrientation, imageReader.imageFormat))
                // There is no need to break out of the loop, this coroutine will suspend
            }
        }
    }
}, cameraHandler)
}

Если я раскомментирую новый ImageReader Например, у меня есть исключение:

java .lang.IllegalArgumentException: CaptureRequest содержит ненастроенную поверхность ввода / вывода!

Может кто-нибудь мне помочь?

1 Ответ

0 голосов
/ 27 апреля 2020

Это IllegalArgumentException:

java .lang.IllegalArgumentException: CaptureRequest содержит ненастроенную поверхность ввода / вывода!

... очевидно относится к imageReader.surface.


Среднее (с CameraX) это работает по-другому, см. CameraFragment.kt ...

Выпуск № 197: API обнаружения лица Firebase проблема при использовании cameraX API ;

, возможно, скоро появится образец приложения, соответствующий вашему варианту использования.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...