How to handle damaged barcodes in ml kit barcode scanner

187 Views Asked by At

Below is the code for the Image Analyser class which will detect camera frames. I only want to show the manual entry option (which will be triggered by the error callback) when user is not able to scan barcodes. In the current scenario even when he is not scanning, this error callback will be called as the analyze method will be called for each camera frame. How to make sure this error() method is only called when barcode is scanned and we get empty barcodes?.

`@SuppressLint("UnsafeOptInUsageError")
override fun analyze(imageProxy: ImageProxy) {
    val mediaImage = imageProxy.image
    if (mediaImage != null) {
        InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
            .let { image ->
                scanner.process(image)
                    .addOnSuccessListener { barcodes ->
                        if (barcodes.isNotEmpty()) {
                            for (barcode in barcodes) {
                                onResult(barcode.rawValue ?: "")
                            }
                        } else error()
                    }
                    .addOnFailureListener {
                        Log.e(ContentValues.TAG, "Use case binding failed $it")
                    }
                    .addOnCompleteListener {
                        CoroutineScope(Dispatchers.IO).launch {
                            delay(delayForProcessingNextImage)
                            imageProxy.close()
                        }
                    }
            }
    } else {
        Log.e(ContentValues.TAG, "Image is empty")
    }
}

}`

1

There are 1 best solutions below

0
Xi 张熹 On

"When user is not able to scan" --- sounds to me you should time out here. e.g. report error after unable to detect barcode for x seconds.

As for barcode scanning, an easier way is to use the androidx.camera:camera-mlkit-vision artifact. See: https://github.com/android/camera-samples/tree/main/CameraX-MLKit