Using GrabCut with OpenCv 3.1.0

asked 2018-06-20 00:38:03 -0600

Dawn4 gravatar image

I'm using opencv3 grabcut function with initial mask guessing (cv2.GC_INIT_WITH_MASK), but for some reason I'm always getting the same output as the original mask. I'm running with python 3.5 and opencv 3.1.0.

I've attached some sample code below. The results are attached as image.

Instead of getting the full shape as grabcut output, I'm getting just the original mask, no matter which number of iterations or if I'm using real images instead of synthetic ones.

What can be the cause for those strange results?

image description

import cv2
import numpy as np
import matplotlib.pyplot as plt

img  = np.zeros((200,200, 3), 'uint8')
mask = np.zeros((200,200),    'uint8')
cv2.circle(img,  (100,100), 50, (255,255,255), -1);
cv2.circle(mask, (100,100),  5,  1,          -1)

bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
out_mask, out_bgdModel, out_fgdModel = cv2.grabCut(img, mask, None, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_MASK)

print('opencv', cv2.__version__) # opencv 3.1.0

fig,ax = plt.subplots(1,3)
ax[0].imshow(img)
ax[1].imshow(mask)
ax[2].imshow(out_mask)
ax[0].set_title('original')
ax[1].set_title('mask')
ax[2].set_title('output')

plt.show()
edit retag flag offensive close merge delete

Comments

Use grabcut constant. What does it mean 1 in cv2.circle(mask, (100,100), 5, 1, -1)? I I think 1 is cv.GC_FGD. You must fill mask withcv. GC_PR_BGD or cv.GC_PR_FGD for unknown pixels and cv.GC_BGD for pixels belong to background (it is not necessary but it helps) .Algorithm will process all pixels with GC_PR.

You can find an example here

Please update your code to master or opencv 3.4.1

LBerger gravatar imageLBerger ( 2018-06-20 01:45:40 -0600 )edit

Thanks, LBerger. The problem was indeed with the inititation of the mask. The code below fix that.

mask = np.full((200,200),cv2.GC_PR_BGD,np.uint8)
cv2.circle(mask, (100,100),  5,  int(cv2.GC_PR_FGD),  -1)
out_mask, _, _ = cv2.grabCut(img, mask, None, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_MASK)
Dawn4 gravatar imageDawn4 ( 2018-06-20 02:19:19 -0600 )edit