Android 结合Opencv检测画面中的圆

发布于:2024-09-17 ⋅ 阅读:(64) ⋅ 点赞:(0)

记下来不用找

Opencv资源https://download.csdn.net/download/qq_37324563/89729678

版本可能比较老,凑合用吧

     mBinding.cameraview.setCvCameraViewListener(object : CameraBridgeViewBase.CvCameraViewListener2 {
            /**
             *  当摄像机预览开始时,这个方法就会被调用。在调用该方法之后,框架将通过onCameraFrame()回调向客户端发送。
             *
             * @param width  - 帧的宽度
             * @param height - 帧的高度
             */
            override fun onCameraViewStarted(width: Int, height: Int) {
                //定义Mat对象
                rgba = Mat(width, height, CvType.CV_8UC4)
            }

            /**
             * 当摄像机预览由于某种原因被停止时,这个方法就会被调用。
             *在调用这个方法之后,不会通过onCameraFrame()回调来传递任何帧。
             */
            override fun onCameraViewStopped() {
     
            }

            /**
             * 当需要完成框架的交付时,将调用此方法。
             *返回值-是一个修改后的帧,需要在屏幕上显示。
             * @param inputFrame
             */
            override fun onCameraFrame(inputFrame: CameraBridgeViewBase.CvCameraViewFrame): Mat? {

                val input = inputFrame.gray()
                val circles = Mat()
              
                Imgproc.blur(input, input, Size(7.0, 7.0), Point(2.0, 2.0))
                Imgproc.HoughCircles(input, circles, Imgproc.CV_HOUGH_GRADIENT, 2.0, 100.0, 100.0, 90.0, 0, 1000)
                if (circles.cols() > 0) {

                    var maxRadius = 0
                    var maxIndex = 0

                    for (x in 0 until circles.cols()) {
                        val circleVec = circles[0, x]
                        val radius = circleVec[2].toInt()
                        if (radius > maxRadius) {
                            maxRadius = radius
                            maxIndex = x
                        }
                    }
                 
                    val center = Point(circles[0, maxIndex][0].toInt().toDouble(), circles[0, maxIndex][1].toInt().toDouble())
                    //  Imgproc.circle(input, center, 3, Scalar(255.0, 255.0, 255.0), 5)
                    Imgproc.circle(input, center, maxRadius, Scalar(255.0, 0.0, 0.0), 2) // 使用不同的颜色突出显示最大半径的圆
                }
                circles.release()
                input.release()
                
                
val frame = inputFrame.rgba()

if (mBinding.cameraview.getCameraId() == CameraBridgeViewBase.CAMERA_ID_FRONT) {
    Core.flip(frame,frame,0);                //当前版本修改后的Opencv使用前置摄像头需要镜像
}
return frame
            }

        })

网站公告

今日签到

点亮在社区的每一天
去签到