(12)GrabCut前景提取

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

img = cv2.imread('opencv-python-foreground-extraction-tut    orial.jpg')
mask = np.zeros(img.shape[:2],np.uint8)

#指定背景和前景模型
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
#需要根据实际改变
rect=(161,79,150,150)

#grab and  cut a certain region
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()
原文地址:https://www.cnblogs.com/sunnyCx/p/8150503.html