>嗨,我正在使用OpenCV android库grabcut()方法从背景中提取图像,但问题是输出位图包含背景与原始图像相同而且对象变为白色。我需要Object与原始图像相同且背景透明
我正在使用此代码
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;
}
答案 0 :(得分:1)
您的代码中存在两个问题:
首先,您需要将白色背景分段,因此请将阈值调整为接近220 - 240,并使用sourceCpp
代替THRESH_BINARY_INV
:
THRESH_BINARY
其次,您必须预先乘以ARGB图层,因为Android ImageView在没有预乘的情况下表现得很奇怪,因为您需要将Imgproc.threshold(tmp, alpha, 230, 255, Imgproc.THRESH_BINARY_INV);
与cvtColor
标志一起使用:
COLOR_RGBA2mRGBA