0

I was trying to use the cv2.grabcut function with python 3.5 - I'm using cv2.GC_INIT_WITH_MASK as initiation method, but the results seems weird, and the output mask is not what I was expecting.

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) ax2.imshow(out_mask) plt.show()

Example

Despite the mask initiated to the center of the given circle, it does not capture the full shape but sticks to the original mask shape. Increasing the number of iterations didn't help.

p.s I used this as an exmpale, I'm getting similar results with real images.

shahar_m
  • 3,461
  • 5
  • 41
  • 61

1 Answers1

0

I needed to initiate the mask as grabcut enums. The following fix works.

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)
shahar_m
  • 3,461
  • 5
  • 41
  • 61