opencv从轮廓绘制矩形

时间:2019-01-18 10:30:44

标签: java android opencv kotlin

我正在尝试通过在BackgroundSubtractorMOG2对象的Android App中使用openCV在移动对象周围绘制矩形来检测移动对象。

我已经提取了前景蒙版并找到了轮廓,但是Imgproc.rectangle()似乎没有绘制矩形。

override fun onCameraFrame(inputFrame: CvCameraViewFrame?): Mat? {
        val minContourWidth = 35
        val minContourHeight = 35
        val threshold = 100.0
        val kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, Size(5.0, 5.0))

        frame = inputFrame?.rgba()
        backSub?.apply(frame, fgMask)
        Imgproc.morphologyEx(fgMask, fgMask, Imgproc.MORPH_CLOSE, kernel) // fill holes
        Imgproc.morphologyEx(fgMask, fgMask, Imgproc.MORPH_OPEN, kernel) //remove noise
        Imgproc.dilate(fgMask, fgMask, kernel)

        val cannyOutput = Mat()
        Imgproc.Canny(fgMask, cannyOutput, threshold, threshold * 2)
        val contours = ArrayList<MatOfPoint>()
        val hierarchy = Mat()
        Imgproc.findContours(cannyOutput, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_TC89_L1)
        hierarchy.release()
        Log.i(TAG, "contours size: " + contours.size)

        for(contour in contours) {

            val approxCurve = MatOfPoint2f()
            val contour2f = MatOfPoint2f()
            contour.convertTo(contour2f, CvType.CV_32FC2)
            val approxDistance = Imgproc.arcLength(contour2f, true) * 0.02
            Imgproc.approxPolyDP(contour2f, approxCurve, approxDistance, true)
            val points = MatOfPoint()
            approxCurve.convertTo(points, CvType.CV_8UC4)
            val rect = Imgproc.boundingRect(points)

            Imgproc.rectangle(frame, Point(rect.x.toDouble(), rect.y.toDouble()),
                Point((rect.x + rect.width).toDouble(), (rect.y + rect.height).toDouble()), Scalar(255.0, 0.0, 0.0, 255.0), 3)
        }

        return frame
    }

Link to my repository

1 个答案:

答案 0 :(得分:0)

我终于成功了,原来我不得不在opencv问答论坛上根据this answercontour.convertTo(contour2f, CvType.CV_32FC2)更改为approxCurve.convertTo(points, CvType.CV_32SC2)