opencv python 基于GrabCut算法的交互式前景提取

Interactive Foreground Extraction using GrabCut Algorithm

mask, bgdModel, fgdModel = cv2.grabCut(img, mask, rect, bgdModel, fgdModel, iterCount[, mode])

  • img:输入图像
  • mask :蒙版图像,指定哪些区域是背景,前景或可能的背景/前景等.它是由下面的标志,cv2.GC_BGD,cv2.GC_FGD,cv2.GC_PR_BGD,cv2.GC_PR_FGD,或简单地将0,1,2,3传递给图像。
  • rect :矩形的坐标,包含了前景对象的格式(x,y,w,h)
  • bdgModel, fgdModel :算法内部使用的数组,只需要创建两个大小为(1,65)的np.float64类型的0数组.
  • iterCount :算法运行的迭代次数.
  • mode :cv2.GC_INIT_WITH_RECT或cv2.GC_INIT_WITH_MASK,或者组合起来决定我们是画矩形还是最后的触点.
import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('messi5.jpg')
mask = np.zeros(img.shape[:2],np.uint8)

bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

rect = (50,50,450,290)
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()

《opencv python 基于GrabCut算法的交互式前景提取》

梅西少了头发,我们会有1像素的修补(确定前景),与此同时,有些地方的地面已经出现了我们不想要的画面,还有一些标志,我们需要移除它们.在那里我们提供了0像素的修补(当然是背景).

# newmask is the mask image I manually labelled
newmask = cv2.imread('newmask.png',0)

# wherever it is marked white (sure foreground), change mask=1
# wherever 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()

《opencv python 基于GrabCut算法的交互式前景提取》

    原文作者:sakurala
    原文地址: https://segmentfault.com/a/1190000015691796
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞