The syntax for grabCut() is:
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, iterCount[, mode])
Here are the descriptions on the parameters
We create a mask image similar to the loaded image:
mask = np.zeros(img.shape[:2],np.uint8)
Then, we create foregroundModel and backgroundModel. Then, we run the grabcut algorithm for 5 iterations with cv2.GC_INIT_WITH_RECT mode since we are using rectangle. It modifies the mask image:
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
In this new mask image, pixels will be marked with four flags denoting background/foreground as specified above. So we modify the mask such that all 0-pixels and 2-pixels are put to 0 (ie background) and all 1-pixels and 3-pixels are put to 1(ie foreground pixels):
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
Now our final mask is ready, and we can just multiply it with input image to get the segmented image:
img_cut = img*mask2[:,:,np.newaxis]
#Grabcut Algorithm
import numpy as np
import cv2
from matplotlib import pyplot as plt
image = cv2.imread('foreground.jpg')
mask = np.zeros(image.shape[:2], np.uint8)
backgroundModel = np.zeros((1, 65), np.float64)
foregroundModel = np.zeros((1, 65), np.float64)
rectangle = (20, 100, 150, 150)
cv2.grabCut(image, mask, rectangle,
backgroundModel, foregroundModel,
3, cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask == 2)|(mask == 0), 0, 1).astype('uint8')
image = image * mask2[:, :, np.newaxis]
plt.imshow(image)
plt.colorbar()
plt.show()