【问题标题】:How to set transparent background to grabcut output image with open cv?如何使用opencv设置透明背景以抓取输出图像?
【发布时间】:2016-11-27 03:40:30
【问题描述】:

>嗨,我正在使用OpenCV android库grabcut()方法从背景中提取图像,但问题是输出位图包含背景与原始图像相同并且对象变为白色。我需要对象作为其与原图相同,背景透明

我正在使用此代码

private static Bitmap makeBlackTransparent(Bitmap image) {
    // convert image to matrix
    Mat src = new Mat(image.getWidth(), image.getHeight(), CvType.CV_8UC4);
    Utils.bitmapToMat(image, src);

    // init new matrices
    Mat dst = new Mat(image.getWidth(), image.getHeight(), CvType.CV_8UC4);
    Mat tmp = new Mat(image.getWidth(), image.getHeight(), CvType.CV_8UC4);
    Mat alpha = new Mat(image.getWidth(), image.getHeight(), CvType.CV_8UC4);

    // convert image to grayscale
    Imgproc.cvtColor(src, tmp, Imgproc.COLOR_BGR2GRAY);

    // threshold the image to create alpha channel with complete transparency in black background region and zero transparency in foreground object region.
    Imgproc.threshold(tmp, alpha, 100, 255, Imgproc.THRESH_BINARY);

    // split the original image into three single channel.
    List<Mat> rgb = new ArrayList<Mat>(3);
    Core.split(src, rgb);

    // Create the final result by merging three single channel and alpha(BGRA order)
    List<Mat> rgba = new ArrayList<Mat>(4);
    rgba.add(rgb.get(0));
    rgba.add(rgb.get(1));
    rgba.add(rgb.get(2));
    rgba.add(alpha);
    Core.merge(rgba, dst);

    // convert matrix to output bitmap
    Bitmap output = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(dst, output);
    return output;
}

【问题讨论】:

  • 可以分享一下源图吗?
  • @Zdar 请在顶部查看我已添加源图像
  • 所以你想要那个圆形的东西在前景和白色部分作为背景,我也没有在你的 sn-p 中看到任何与 grabCut 相关的代码?
  • 是的,我想要图像中的男孩,因为它在源图像中和背景为白色,实际上我使用的是 open cv sdk

标签: android opencv


【解决方案1】:

你的代码有两个问题:

首先您需要分割出白色背景,因此将您的阈值调整为接近 220 - 240 并使用 THRESH_BINARY_INV 而不是 THRESH_BINARY

Imgproc.threshold(tmp, alpha, 230, 255, Imgproc.THRESH_BINARY_INV);

其次,您必须预乘 ARGB 层,因为 Android ImageView 在没有预乘的情况下会表现得很奇怪,因为您需要使用 cvtColorCOLOR_RGBA2mRGBA 标志:

// Create the final result by merging three single channel and alpha(BGRA order)
List<Mat> rgba = new ArrayList<Mat>(4);
rgba.add(rgb.get(0));
rgba.add(rgb.get(1));
rgba.add(rgb.get(2));
rgba.add(alpha);
Core.merge(rgba, dst);

Imgproc.cvtColor(dst, dst, Imgproc.COLOR_RGBA2mRGBA);

【讨论】:

  • 感谢您的帮助,但我仍然遇到麻烦,因为使用此代码,我的圆形图像与源图像相同,并且图像视图背景变为黑色
  • 你能使用上面的代码分享输出吗?我猜你需要设置图像视图的背景颜色,否则默认的 Android imageView 将 alpha 视为黑色
  • 嗨。我在 OpenCV 中遇到一些问题,无法使背景清晰
猜你喜欢
  • 2014-11-30
  • 2021-12-31
  • 1970-01-01
  • 2013-02-03
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
相关资源
最近更新 更多