I'm trying to make a barcode scanner using ML kit Barcode detector, camera2 API and Kotlin. Concerning camera2 I'm starting from Google sample camera2basic Concerning ML kit Barcode detector, I'm starting from doc : Scan Barcodes with ML Kit on Android
In Camera2BasicFragment / createCameraPreviewSession method, I added
previewRequestBuilder.addTarget(imageReader!!.surface)
so, onImageAvailableListener is called each time an image is available.
In Camera2BasicFragment / setUpCameraOutputs method, i changed ImageReader's ImageFormat.JPEG
to ImageFormat YUV420_888
, so in onImageAvailableListener, ImageReader gives a YUV image
Then here is my onImageAvailableListener :
private val onImageAvailableListener = ImageReader.OnImageAvailableListener {
val metadata = FirebaseVisionImageMetadata.Builder()
.setWidth(480) // 480x360 is typically sufficient for
.setHeight(360) // image recognition
.setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_YV12)
.setRotation(getRotationCompensation(cameraId, activity as Activity, context!!))
.build()
BarcodeReader(it.acquireNextImage(), detector, metadata, mListener).run()
}
In metadata, 'width' and 'heigth' are as suggested in ML kit doc, 'format' is YV12 to handle YUV format
and Barcode Reader is :
class BarcodeReader (private val image: Image,
private val detector: FirebaseVisionBarcodeDetector,
private val metadata: FirebaseVisionImageMetadata,
private val mListener: IBarcodeScanner) : Runnable {
override fun run() {
val visionImage = FirebaseVisionImage.fromByteBuffer(image.planes[0].buffer, metadata)
detector.detectInImage(visionImage)
.addOnSuccessListener { barcodes ->
// Task completed successfully
// [START_EXCLUDE]
// [START get_barcodes]
for (barcode in barcodes) {
val bounds = barcode.boundingBox
val corners = barcode.cornerPoints
val rawValue = barcode.rawValue
if (rawValue!=null)
mListener.onBarcode(rawValue)
}
// [END get_barcodes]
// [END_EXCLUDE]
}
.addOnFailureListener {
// Task failed with an exception
// ...
Log.d("barcode", "null")
}
image.close()
}
The detector.detectInImage enters onSuccessListener but NO BARCODE are detected : barcodes
array is always empty.
Can somebody help me please ?