Using GrabCut with OpenCv 3.1.0
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?
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()
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
Thanks, LBerger. The problem was indeed with the inititation of the mask. The code below fix that.