Recently I have been given a project, where I have to extract face (face+hair) from a given image.

I am solving this problem in the following ways.

1. I am extracting face locations from given image. [I am getting a rectangle]
2. I am extracting that rectangle and placing it in another image of same dimensions as input image.[face\_image]
3. I am applying **grabCut** algorithm on the face\_image of step 2.

When the face\_image contains smooth background then the algorithm **grabCut** it working well but when the background of face\_image is complex then the algorithm **grabCut** extracts some part of background too in the processed image.

Here is a snapshot of the results that I am getting.

![results of each step](https://i.stack.imgur.com/VfMbR.jpg)

Here is my code of **grabCut**:

```
public void extractFace(Mat image, String fileNameWithCompletePath, 
                       int xOne, int xTwo, int yOne, int yTwo) throws CvException {

    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    Rect rectangle = new Rect(xOne, yOne, xTwo, yTwo);
    Mat result = new Mat();
    Mat bgdModel = new Mat();
    Mat fgdModel = new Mat();
    Mat source = new Mat(1, 1, CvType.CV_8U, new Scalar(3));
    Imgproc.grabCut(image, result, rectangle, bgdModel, fgdModel, 8, Imgproc.GC_INIT_WITH_RECT);
    Core.compare(result, source, result, Core.CMP_EQ);
    Mat foreground = new Mat(image.size(), CvType.CV_8UC3, new Scalar(255, 255, 255));
    image.copyTo(foreground, result);
    Imgcodecs.imwrite(fileNameWithCompletePath, foreground);
}

```

**How can I improve performance of grabCut algorithm so that it will detect only face and hair from given image?**