Ask Your Question

GrabCut output shown in greyscale

asked 2015-01-08 12:38:29 -0600

jravi96 gravatar image

Hi all ,

I am practicing JavaCV grabcut example given here.

The example given here is in Scala but I have managed to write in Java. On running the example two windows open up , first one containing the input image and second one containing output image in greyscale mode. The problem is would want the output image in color mode with transparent background. I am using OpenCV 2.4.10 and JavaCV 0.10. Below is the code in using and the images shown in output.

import opencv2_cookbook.OpenCVUtils;
import org.bytedeco.javacpp.opencv_core.Mat;
import org.bytedeco.javacpp.opencv_core.Rect;
import static org.bytedeco.javacpp.opencv_highgui.CV_LOAD_IMAGE_COLOR;
import org.bytedeco.javacpp.opencv_imgproc;
import static org.bytedeco.javacpp.opencv_imgproc.*;
public class GrabCut
    public static void main(String[] arg)
        Mat  image = OpenCVUtils.loadMatAndShowOrExit(new File("F:\\images\\set2.jpg"), CV_LOAD_IMAGE_COLOR);

        Rect rectangle = new Rect(0, 0 , 224 , 224);

        Mat result = new Mat();
        int iterCount = 5;
        int mode = GC_INIT_WITH_RECT;

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

        opencv_imgproc.grabCut(image, result, rectangle, bgdModel, fgdModel, iterCount, mode);
        //opencv_core.cvCmpS(result, GC_PR_FGD, result, CV_CMP_EQ);
        opencv_imgproc.threshold(result, result, GC_PR_FGD - 0.5, GC_PR_FGD + 0.5, THRESH_BINARY); , true), "Result foreground mask");

image description

Kindly need ur help.Thanks.

edit retag flag offensive close merge delete



I am practicing JavaCV grabcut example --> keep in mind that this is NOT an official supported package of OpenCV and thus we cannot guarantee that all functionality available in OpenCV has actually a wrapper in the JavaCV package. It is also better to direct JavaCV based questions towards the proper forum.

StevenPuttemans gravatar imageStevenPuttemans ( 2015-01-09 03:23:45 -0600 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2015-01-08 21:46:58 -0600

Haris gravatar image

So you already got the mask for foreground,


  • Create alpha channel with above mask.
  • Split the original image in to three single channel.
  • Create the final result by merging three single channel and alpha(BGRA order).

See similar thread with example code here.

edit flag offensive delete link more


Hi, I tried your solution provided in above thread , but I am not getting output as expected. Here is the output and here is the source code.Kindly let me know my mistake. Thanks.

jravi96 gravatar imagejravi96 ( 2015-01-17 07:49:41 -0600 )edit

As far as I know OpenCV window does not supported alpha, may be you could try by saving image as png.

Haris gravatar imageHaris ( 2015-01-19 21:54:49 -0600 )edit

Question Tools

1 follower


Asked: 2015-01-08 12:38:29 -0600

Seen: 1,223 times

Last updated: Jan 08 '15