在执行grabcut后删除输出中的黑色背景

时间:2018-01-11 04:07:50

标签: java android android-studio opencv3.0

我正在使用OpenCV来分割图像并删除其背景。 我试图在执行抓取后删除输出图像上的黑色背景,但它无法正常工作。我想知道我的代码有什么问题。

我正在使用此代码:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    ImageView iv;
    Scalar color = new Scalar(255, 0, 0, 255);
    Point tl, br;
    Mat dst = new Mat();

    static{

        System.loadLibrary("opencv_java3");

    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        iv = (ImageView) this.findViewById(R.id.imageView);


        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.eggtwo);
        Log.d(TAG, "bitmap: " + bitmap.getWidth() + "x" + bitmap.getHeight());

        //Grabcut part
        Mat img = new Mat(); //container
        Utils.bitmapToMat(bitmap, img); //
        Log.d(TAG, "img: " + img);

        //init new Matrices
        int r = img.rows();
        int c = img.cols();

        Point p1 = new Point(25, 25);
        Point p2 = new Point(c - 64, r - 64);

        Rect rect = new Rect(25,25,c-64, r-64);
        Log.d(TAG, "rect: " + rect);

        Mat background = new Mat(img.size(), CvType.CV_8UC3, new Scalar(255, 255, 255));
        Mat mask = new Mat();
        mask.setTo(new Scalar(125));
        Mat fgModel = new Mat();
        fgModel.setTo(new Scalar(0, 0, 0));
        Mat bgModel = new Mat();
        bgModel.setTo(new Scalar(0, 0, 0));

        Mat imgC3 = new Mat(bitmap.getWidth(), bitmap.getHeight(), CvType.CV_8UC4);
        Imgproc.cvtColor(img, imgC3, Imgproc.COLOR_RGBA2RGB);
        Log.d(TAG, "imgC3: " + imgC3);

        Log.d(TAG, "Grabcut begins");
        Imgproc.grabCut(imgC3, mask, rect, bgModel, fgModel, 5, 0);
        Mat source = new Mat(1, 1, CvType.CV_8UC3, new Scalar(Imgproc.GC_PR_FGD));

        Core.compare(mask, source, mask, Core.CMP_EQ);
        Mat foreground = new Mat(img.size(), CvType.CV_8UC3, new Scalar(255, 255, 255));
        img.copyTo(foreground, mask);
        Imgproc.rectangle(img, p1, p2, color);

        Mat tmp = new Mat();
        Imgproc.resize(background, tmp, img.size());

        background = tmp;

        Mat tempMask = new Mat(foreground.size(), CvType.CV_8UC1, new Scalar(255, 255, 255));
        Imgproc.cvtColor(foreground, tempMask, Imgproc.COLOR_BGR2GRAY);
        Imgproc.threshold(tempMask, tempMask, 254, 255, Imgproc.THRESH_BINARY_INV);
        Mat vals = new Mat(1, 1, CvType.CV_8UC3, new Scalar(0.0));
        background.copyTo(dst);
        background.setTo(vals, tempMask);
        Imgproc.resize(foreground, tmp, mask.size());
        foreground = tmp;
        Core.add(background, foreground, dst, tempMask);

        //Convert to Bitmap
        Log.d(TAG, "Convert to Bitmap");
        Utils.matToBitmap(dst, bitmap);

        iv.setImageBitmap(bitmap);

    }

}

0 个答案:

没有答案