I want to find the foreground of a picture using Grabcut, below is the code
import cv2
import numpy as np
from matplotlib import pyplot as plt
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
img=cv2.imread(r'D:\Python Code\Grabcut\fqx.jpg')
cv2.imshow('src',img)
mask = np.zeros(img.shape[:2],np.uint8)
rect=(155,1,367,640)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]
plt.imshow(img),plt.colorbar(),plt.show()
cv2.imshow('img',img)
cv2.waitKey(0)
but the result is not perfect:
so i imitate the 'Interactive Foreground Extraction using GrabCut Algorithm' from the official website of Opencv, the code is below
import cv2
import numpy as np
from matplotlib import pyplot as plt
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
img=cv2.imread(r'D:\Python Code\Grabcut\fqx.jpg')
cv2.imshow('src',img)
mask = np.zeros(img.shape[:2],np.uint8)
rect=(155,1,367,640)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]
#plt.imshow(img),plt.colorbar(),plt.show()
cv2.imshow('img',img)
# newmask is the mask image I manually labelled
newmask = cv2.imread(r'D:\Python Code\Grabcut\newmark.jpg',0)
# whereever it is marked white (sure foreground), change mask=1
# whereever it is marked black (sure background), change mask=0
mask[newmask == 0] = 0
mask[newmask == 255] = 1
mask, bgdModel, fgdModel =
cv2.grabCut(img,mask,None,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_MASK)
mask = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask[:,:,np.newaxis]
plt.imshow(img),plt.colorbar(),plt.show()
cv2.waitKey(0)
and the newmask is that
and the there is a problem, after run the code, it comes TypeError: 'NoneType' object is not iterable. I change the parameter of 'None' but it still can not work.