无法在覆盖的Surfaceview上获得正确位置的条形码边界框。

问题描述 投票:1回答:1

我正在使用带有Firebase MLKit条形码阅读器的CameraX来检测条形码。应用程序识别条形码没有问题。但是我想在CameraX的预览中添加边界框,实时显示条形码的区域。边界框的信息是从条形码检测器功能中获取的。但如下图所示,它既没有正确的位置,也没有正确的大小。

enter image description here

这是我的活动布局。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/camera_capture_button"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginBottom="50dp"
        android:scaleType="fitCenter"
        android:text="Take Photo"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:elevation="2dp" />

    <SurfaceView
        android:id="@+id/overlayView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <androidx.camera.view.PreviewView
        android:id="@+id/previewView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

SurfaceView 是用来绘制这个矩形的。

条码检测发生在 BarcodeAnalyzer 类,它实现了 ImageAnalysis.Analyzer内侧被覆盖 analyze 函数,我检索条码数据,如下图所示。

@SuppressLint("UnsafeExperimentalUsageError")
    override fun analyze(imageProxy: ImageProxy) {

        val mediaImage = imageProxy.image

        val rotationDegrees = degreesToFirebaseRotation(imageProxy.imageInfo.rotationDegrees)

        if (mediaImage != null) {

            val analyzedImageHeight = mediaImage.height
            val analyzedImageWidth = mediaImage.width

            val image = FirebaseVisionImage
                .fromMediaImage(mediaImage,rotationDegrees)

            detector.detectInImage(image)
                .addOnSuccessListener { barcodes ->

                    for (barcode in barcodes) {
                        val bounds = barcode.boundingBox
                        val corners = barcode.cornerPoints
                        val rawValue = barcode.rawValue

                        if(::barcodeDetectListener.isInitialized && rawValue != null && bounds != null){
                            barcodeDetectListener.onBarcodeDetect(
                                rawValue,
                                bounds,
                                analyzedImageWidth,
                                analyzedImageHeight
                            )
                        }
                    }

                    imageProxy.close()

                }
                .addOnFailureListener {
                    Log.e(tag,"Barcode Reading Exception: ${it.localizedMessage}")
                    imageProxy.close()
                }
                .addOnCanceledListener {
                    Log.e(tag,"Barcode Reading Canceled")
                    imageProxy.close()
                }

        }
    }  

barcodeDetectListener 是对我创建的一个接口的引用,以便将这些数据传回我的活动中。

interface BarcodeDetectListener {
    fun onBarcodeDetect(code: String, codeBound: Rect, imageWidth: Int, imageHeight: Int)
}

在我的主活动中,我把这些数据发送到了 OverlaySurfaceHolder 其中实现了 SurfaceHolder.Callback. 该类负责在叠加的 SurfaceView.

override fun onBarcodeDetect(code: String, codeBound: Rect, analyzedImageWidth: Int,
                                 analyzedImageHeight: Int) {

        Log.i(TAG,"barcode : $code")
        overlaySurfaceHolder.repositionBound(codeBound,previewView.width,previewView.height,
            analyzedImageWidth,analyzedImageHeight)
        overlayView.invalidate()

    }

正如你所看到的,我正在发送叠加的。SurfaceView 中计算的宽度和高度。OverlaySurfaceHolder 类。

OverlaySurfaceHolder.kt

class OverlaySurfaceHolder: SurfaceHolder.Callback {

    var previewViewWidth: Int = 0
    var previewViewHeight: Int = 0
    var analyzedImageWidth: Int = 0
    var analyzedImageHeight: Int = 0

    private lateinit var drawingThread: DrawingThread
    private lateinit var barcodeBound :Rect

    private  val tag = OverlaySurfaceHolder::class.java.simpleName

    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {

        var retry = true
        drawingThread.running = false

        while (retry){
            try {
                drawingThread.join()
                retry = false
            } catch (e: InterruptedException) {
            }
        }
    }

    override fun surfaceCreated(holder: SurfaceHolder?) {
        drawingThread = DrawingThread(holder)
        drawingThread.running = true
        drawingThread.start()
    }

    fun repositionBound(codeBound: Rect, previewViewWidth: Int, previewViewHeight: Int,
                        analyzedImageWidth: Int, analyzedImageHeight: Int){

        this.barcodeBound = codeBound
        this.previewViewWidth = previewViewWidth
        this.previewViewHeight = previewViewHeight
        this.analyzedImageWidth = analyzedImageWidth
        this.analyzedImageHeight = analyzedImageHeight
    }

    inner class DrawingThread(private val holder: SurfaceHolder?): Thread() {

        var running = false

        private fun adjustXCoordinates(valueX: Int): Float{

            return if(previewViewWidth != 0){
                (valueX / analyzedImageWidth.toFloat()) * previewViewWidth.toFloat()
            }else{
                valueX.toFloat()
            }
        }

        private fun adjustYCoordinates(valueY: Int): Float{

            return if(previewViewHeight != 0){
                (valueY / analyzedImageHeight.toFloat()) * previewViewHeight.toFloat()
            }else{
                valueY.toFloat()
            }
        }

        override fun run() {

            while(running){

                if(::barcodeBound.isInitialized){

                    val canvas = holder!!.lockCanvas()

                    if (canvas != null) {

                        synchronized(holder) {

                            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)

                            val myPaint = Paint()
                            myPaint.color = Color.rgb(20, 100, 50)
                            myPaint.strokeWidth = 6f
                            myPaint.style = Paint.Style.STROKE

                            val refinedRect = RectF()
                            refinedRect.left = adjustXCoordinates(barcodeBound.left)
                            refinedRect.right = adjustXCoordinates(barcodeBound.right)
                            refinedRect.top = adjustYCoordinates(barcodeBound.top)
                            refinedRect.bottom = adjustYCoordinates(barcodeBound.bottom)

                            canvas.drawRect(refinedRect,myPaint)
                        }

                        holder.unlockCanvasAndPost(canvas)

                    }else{
                        Log.e(tag, "Cannot draw onto the canvas as it's null")
                    }

                    try {
                        sleep(30)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }

                }
            }
        }

    }
}

谁能告诉我,我到底做错了什么?

android barcode-scanner firebase-mlkit android-camerax
1个回答
1
投票

我没有很清楚的线索,但这里有一些你可以尝试的东西。

  1. 当你调整XCoordinates的时候 如果预览宽度为0,你就直接返回valueX.toFloat(). 你能不能增加一些日志,看看它是否真的属于这种情况? 另外增加一些日志打印分析和预览维度也会有帮助。

  2. 另一个值得注意的是,你发送给检测器的图像可能与预览View区域的长宽比不同。例如,如果您的相机拍摄了一张4:3的照片,它将把它发送到检测器。但是,如果您的视图区域是1:1,它将裁剪照片的某些部分来显示它。在这种情况下,你在调整坐标时也需要考虑到这一点。根据我的测试,图片会根据CENTER_CROP来适应View区域。如果你想非常小心,可能值得检查一下相机开发网站上是否有这方面的记录。

希望对你有所帮助,或多或少。

© www.soinside.com 2019 - 2024. All rights reserved.