Skip to content

Instantly share code, notes, and snippets.

@dayerdl
Last active November 1, 2022 12:28
Show Gist options
  • Save dayerdl/1e6320c7b4f95d5b70a417250c3368bb to your computer and use it in GitHub Desktop.
Save dayerdl/1e6320c7b4f95d5b70a417250c3368bb to your computer and use it in GitHub Desktop.
fun drawBoxesOnTheImage2(img: Mat) {
val gray = Mat()
val blur = Mat()
val thresh = Mat()
Imgproc.cvtColor(img, gray, Imgproc.COLOR_BGR2GRAY)
Imgproc.medianBlur(gray, blur, 11)
Imgproc.threshold(blur, thresh, 0.0, 255.0, Imgproc.THRESH_BINARY + Imgproc.THRESH_OTSU)
val opening = Mat()
val kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, Size(5.0,5.0))
Imgproc.morphologyEx(thresh, kernel, Imgproc.MORPH_OPEN, opening)
val hierarchy = Mat()
val contours = arrayListOf<MatOfPoint>()
Imgproc.findContours(
opening,
contours,
hierarchy,
Imgproc.RETR_EXTERNAL,
Imgproc.CHAIN_APPROX_SIMPLE
)
if(contours.size == 0) return
var cnts = contours[0].toArray()
if (contours.size > 2) {
cnts = contours[1].toArray()
}
for (c in cnts) {
val matOfPoint = MatOfPoint2f(c)
val peri = Imgproc.arcLength(matOfPoint, true)
if (peri > 0) {
println("peri $peri")
}
val approx = MatOfPoint2f()
val area = Imgproc.contourArea(matOfPoint)
Imgproc.approxPolyDP(matOfPoint, approx, 0.04 * peri, true)
if (approx.toArray().size > 5 && area > 1000 && area < 500000) {
val center = Point()
val radius = FloatArray(1)
Imgproc.minEnclosingCircle(matOfPoint, center, radius)
Imgproc.circle(img, center, radius[0].toInt(), Scalar(0.0, 0.0, 255.0), 1)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment