I am trying to detect moving objects by drawing rectangle around them using openCV in Android App with BackgroundSubtractorMOG2
object.
I have already extracted foreground mask and found contours but It seems like that Imgproc.rectangle()
doesn't draw rectangles
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
}