简体   繁体   English

性能不佳的 ML Kit 条码扫描

[英]Bad performance ML Kit barcode scanning

I'm using Googles ML Kit for barcode scanning, and gathered the code below from the examples and tutorials provided by Google.我正在使用 Google 的 ML Kit 进行条形码扫描,并从 Google 提供的示例和教程中收集了以下代码。 However, the performance is dramatic;然而,表演是戏剧性的。 it takes several seconds, can be 10, 15 seconds, to recognize a barcode.识别条码需要几秒钟,可以是 10、15 秒。 Is there any way to improve this?有什么办法可以改善这一点吗?

Also, how can this be used with inverted bar codes?此外,这如何与倒置条形码一起使用? I found that I need to invert the image, however, if in the Analyzer I try to get image.bitmapInternal or image.byteBuffer, it is always null.我发现我需要反转图像,但是,如果在分析器中我尝试获取 image.bitmapInternal 或 image.byteBuffer,它总是 null。

Build.gradle Build.gradle

 implementation 'com.google.mlkit:barcode-scanning:17.0.0'
 // CameraX core library using camera2 implementation
implementation "androidx.camera:camera-camera2:1.0.2"
// CameraX Lifecycle Library
implementation "androidx.camera:camera-lifecycle:1.0.2"
// CameraX View class
implementation "androidx.camera:camera-view:1.0.0-alpha31"

Then, in a fragment:然后,在一个片段中:

typealias BarCodeListener = (barCode: String) -> Unit
const val TAG = "ConnectorScanner"
[...]

override fun onResume() {
    super.onResume()
    cameraExecutor = Executors.newSingleThreadExecutor()
    startCamera()
}

private fun startCamera() {
    val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())
    val resolution = Size(720, 1280)
    cameraProviderFuture.addListener({
        // Used to bind the lifecycle of cameras to the lifecycle owner
        val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

        // Preview
        val preview = Preview.Builder()
            .setTargetResolution(resolution)
            .build()
            .also {
                it.setSurfaceProvider(binding.viewFinder.surfaceProvider)
            }

        imageCapture = ImageCapture.Builder()
            .setTargetResolution(resolution)
            .setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY)
            .build()

        val imageAnalyzer = ImageAnalysis.Builder()
            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
            .build()
            .also {
                it.setAnalyzer(cameraExecutor, BarCodeAnalyzer { barCode ->
                    if (BuildConfig.DEBUG) {
                        Toast.makeText(context, "Code: $barCode", Toast.LENGTH_LONG).show()
                    }
                    viewModel.onConnectorCodeScanned(barCode)
                    cameraProvider.unbindAll()
                })
            }

        // 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, imageCapture, imageAnalyzer
            )

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

    }, ContextCompat.getMainExecutor(requireContext()))
}

Image analyzer图像分析仪

private class BarCodeAnalyzer(private val listener: BarCodeListener) : ImageAnalysis.Analyzer {
    val options = BarcodeScannerOptions.Builder()
        .setBarcodeFormats(
            Barcode.FORMAT_DATA_MATRIX
        )
        .build()

    @SuppressLint("UnsafeOptInUsageError")
    override fun analyze(imageProxy: ImageProxy) {
        val mediaImage = imageProxy.image
        mediaImage?.let {
            val image =
                InputImage.fromMediaImage(it, imageProxy.imageInfo.rotationDegrees)
                val scanner = BarcodeScanning.getClient(options)

            scanner.process(image)
                .addOnSuccessListener { barcodes ->
                    if (barcodes.isNotEmpty()) {
                        barcodes.firstOrNull()?.rawValue?.let { barcode ->
                            Log.d(TAG, barcode)
                            listener(barcode)
                        }
                        imageProxy.close()
                    }
                }
        }
        imageProxy.close()
    }
}

With some luck, I found the solution to the performance issue, it's adding an OnCompleteListener and closing the images there.幸运的是,我找到了性能问题的解决方案,它添加了一个 OnCompleteListener 并在那里关闭图像。 So the analyzer will be所以分析仪将是

scanner.process(image)
                .addOnSuccessListener { barcodes ->
                    if (barcodes.isNotEmpty()) {
                        barcodes.firstOrNull()?.rawValue?.let { barcode ->
                            Log.d(TAG, barcode)
                                listener(barcode)
                        }
                    }
                }
                .addOnCompleteListener {
                    imageProxy.close()
                }
        }

Now the scanning of the barcode is lightning fast!现在条码的扫描速度快如闪电!

Whatever @Bruce Wayne suggest works !!!无论@Bruce Wayne 建议什么都行!!!

.addOnCompleteListener {
    imageProxy.close()
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ML Kit条形码扫描:无效的图像数据大小 - ML Kit Barcode scanning: Invalid image data size 如何在 Firebase ML KIT 中使用前置摄像头进行条码扫描 - How to use Front Camera for Barcode Scanning in Firebase ML KIT 如何使用Firebase ML Kit创建用于条形码扫描的模块化类 - How to create a modular class for barcode scanning using Firebase ML Kit ML Kit 条码扫描未检测到显示器屏幕照片中的二维码 - ML Kit Barcode Scanning doesn't detect QR codes in the photo of the monitor screen 如何在android JAVA CODE中集成camerax和google ML套件以进行条码扫描? - How to Integrate camerax and google ML kit for barcode scanning in android JAVA CODE? "使用 SurfaceView 中的 ByteBuffer 时如何在 android ML-kit 中暂停条形码扫描" - How to pause barcode scanning in android ML-kit when using ByteBuffer from SurfaceView 用于二维码扫描的 Android ML Kit 库:如何通过降低图像分辨率来提高检测性能 - Android ML Kit library for QR code scanning: How to increase detection performance by reducing image resolution ML Kit条形码扫描仪提供空输出 - ML Kit Barcode Scanner gives empty output 使用ML套件从位图读取条形码信息 - Read barcode info from bitmap using ML kit Google ML Kit, BarcodeScannerOptions 动态添加条码读取类型 - Google ML Kit, BarcodeScannerOptions Adding barcode reading type dynamically
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM