Ask Your Question

Revision history [back]

Use it. After using grabcut, the result background is transparent.

public Bitmap removeBackground(Bitmap bitmap) {
    //GrabCut part
    Mat img = new Mat();
    Utils.bitmapToMat(bitmap, img);

    int r = img.rows();
    int c = img.cols();
    Point p1 = new Point(c / 100, r / 100);
    Point p2 = new Point(c - c / 100, r - r / 100);
    Rect rect = new Rect(p1, p2);

    Mat mask = new Mat();
    Mat fgdModel = new Mat();
    Mat bgdModel = new Mat();

    Mat imgC3 = new Mat();
    Imgproc.cvtColor(img, imgC3, Imgproc.COLOR_RGBA2RGB);

    Imgproc.grabCut(imgC3, mask, rect, bgdModel, fgdModel, 5, Imgproc.
            GC_INIT_WITH_RECT);

    Mat source = new Mat(1, 1, CvType.CV_8U, new Scalar(3.0));
    Core.compare(mask, source/* GC_PR_FGD */, mask, Core.CMP_EQ);

    //This is important. You must use Scalar(255,255, 255,255), not Scalar(255,255,255)
    Mat foreground = new Mat(img.size(), CvType.CV_8UC3, new Scalar(255,
            255, 255,255));
    img.copyTo(foreground, mask);

    // convert matrix to output bitmap
    bitmap = Bitmap.createBitmap((int) foreground.size().width,
            (int) foreground.size().height,
            Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(foreground, bitmap);
    return bitmap;
}