首页 > 解决方案 > 如何使用opencv填充图像中标记区域的外部区域?

问题描述

我正在使用 kotlin 和 opencv 开发应用程序。该应用程序有一个图像分割步骤,其中用户标记一个感兴趣的区域,我需要用黑色填充该区域的整个外部。我正在获取标记区域的坐标并使用 floodFill 填充图像。但是,使用下面的代码,它最终会填充整个图像,而不仅仅是标记的外部区域。

代码:

private fun extractBackground(coordinates: Coordinates, currentPhotoPath: String): String {
    // TODO: Provide complex object that has both path and extension

    val width: Int
    val height: Int
    width = bitmap.getWidth()
    height = bitmap.getHeight()
    val rect = Rect(coordinates.first, coordinates.second)
    val rgba = Mat()
    val gray_mat = Mat()
    val threeChannel = Mat()

    Utils.bitmapToMat(bitmap, gray_mat)

    Imgproc.cvtColor(gray_mat, rgba, Imgproc.COLOR_RGBA2RGB)

    Imgproc.cvtColor(rgba, threeChannel, Imgproc.COLOR_RGB2GRAY)
    val mask = Mat.zeros(rgba.rows() + 2, rgba.cols() + 2, CvType.CV_8UC1)

    Imgproc.floodFill(rgba, mask, Point(0.0, 0.0), Scalar(255.0), rect, Scalar(0.0), Scalar(0.0), 4 + (255 shl 8) + Imgproc.FLOODFILL_MASK_ONLY)
    Core.subtract(mask, Scalar.all(0.0), mask)
    val roi = Rect(1, 1, rgba.cols() - 2, rgba.rows() - 2)

    val temp = Mat()
    mask.submat(roi).copyTo(temp)
    Imgcodecs.imwrite(currentPhotoPath + "_tmp.png", temp)

    return currentPhotoPath
}

输入:

输出:

预期输出:

有人可以帮我解决这个问题吗?

标签: javaandroidimageopencvkotlin

解决方案


推荐阅读