ML Kit OCR в Фотоаппарате возвращает ерунду - PullRequest
0 голосов
/ 02 марта 2019

Я пытаюсь выполнить пользовательскую обработку кадров, чтобы создать приложение для распознавания текста ML-Kit.Сначала я использовал FotoApparat для создания простого приложения для камеры.

Затем я добавил пользовательскую анонимную функцию обработки кадров в m инициализации FotoApparat.

   private fun createFotoapparat(){
        val cameraView = findViewById<CameraView>(R.id.camera_view)
        fotoapparat = Fotoapparat
            .with(this)
            .into(cameraView)
            .previewScaleType(ScaleType.CenterCrop)
            .lensPosition(back())
            .logger(loggers(logcat()))
            .cameraErrorCallback({error -> println("Recorder errors: $error")})
            .frameProcessor { frame ->
                Log.d("Frameprocessor", "Fired")
                val rotation = getRotationCompensation("0", this, baseContext)
                val BAimage = frame.image
                val metadata = FirebaseVisionImageMetadata.Builder()
                    .setWidth(480)   // 480x360 is typically sufficient for
                    .setHeight(360)  // image recognition
                    .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
                    .setRotation(rotation)
                    .build()
                var FBimage = FirebaseVisionImage.fromByteArray(BAimage, metadata)
                val detector = FirebaseVision.getInstance()
                    .onDeviceTextRecognizer
                val result = detector.processImage(FBimage)
                    .addOnSuccessListener { firebaseVisionText ->
                        Log.d("OnSuccess", "Triggered")
                        for (block in firebaseVisionText.textBlocks){
                            val blockText = block.text
                            val blockConfidence = block.confidence
                            Log.d("newframe", blockText)
                            Log.d(blockText, blockConfidence.toString())
                        }
                    }
                    .addOnFailureListener {
                        Log.e("err", "line 114", it)
                    }
            }.build()
    }

Моя проблема в том, что он возвращает глупость снулевое значение для уверенности.Вот некоторые из выводов logcat, когда он смотрит на простое изображение с небольшим количеством напечатанного текста.

2019-03-01 14:24:56.735 16117-16117/me.paxana.myapplication D/newframe: 111
2019-03-01 14:24:56.735 16117-16117/me.paxana.myapplication D/111: null

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

1 Ответ

0 голосов
/ 03 марта 2019

Я частично понял это.Мой алгоритм поворота неправильный, я должен сделать снимок под углом 90 градусов, и тогда он отлично работает.Это мой алгоритм ротации, я обновлю его, когда он заработает.

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Throws(CameraAccessException::class)
    private fun getRotationCompensation(cameraId: String, activity: Activity, context: Context): Int {
        // Get the device's current rotation relative to its "native" orientation.
        // Then, from the ORIENTATIONS table, look up the angle the image must be
        // rotated to compensate for the device's rotation.
        val deviceRotation = activity.windowManager.defaultDisplay.rotation
        var rotationCompensation = ORIENTATIONS.get(deviceRotation)

        // On most devices, the sensor orientation is 90 degrees, but for some
        // devices it is 270 degrees. For devices with a sensor orientation of
        // 270, rotate the image an additional 180 ((270 + 270) % 360) degrees.
        val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
        val sensorOrientation = cameraManager
            .getCameraCharacteristics(cameraId)
            .get(CameraCharacteristics.SENSOR_ORIENTATION)!!
        rotationCompensation = (rotationCompensation + sensorOrientation + 270) % 360

        // Return the corresponding FirebaseVisionImageMetadata rotation value.
        val result: Int
        when (rotationCompensation) {
            0 -> result = FirebaseVisionImageMetadata.ROTATION_0
            90 -> result = FirebaseVisionImageMetadata.ROTATION_90
            180 -> result = FirebaseVisionImageMetadata.ROTATION_180
            270 -> result = FirebaseVisionImageMetadata.ROTATION_270
            else -> {
                result = FirebaseVisionImageMetadata.ROTATION_0
                Log.e("Err", "Bad rotation value: $rotationCompensation")
            }
        }
        return result
    }

}
...