import cv2
import numpy as np
import matplotlib.pylab as pylab
from skimage.segmentation import (morphological_chan_vese,morphological_geodesic_active_contour,inverse_gaussian_gradient, checkerboard_level_set)
img=cv2.imread('C:/Users/xpp/Desktop/Lena.png')#原始图像
newmask=cv2.imread('C:/Users/xpp/Desktop/mask.png')#原始图像
mask=2*np.ones(img.shape[:2],np.uint8)
mask[(newmask[...,0]<=76)&(newmask[...,1]<=76)&(newmask[...,2]>=76)]=0
mask[(newmask[...,0]<=76)&(newmask[...,1]>=76)&(newmask[...,2]<=76)]=1
mask,bg_model,fg_model=cv2.grabCut(img,mask,None,bg_model,fg_model,5,cv2.GC_INIT_WITH_MASK)#grabcut图像分割
mask=np.where((mask==2)|(mask==0),0,1).astype('uint8')
img=img*mask[:,:,np.newaxis]
pylab.imshow(img)
pylab.colorbar()
pylab.show()
算法:Grabcut初始化图像分割是通过输入掩模为算法提供一些提示,掩模上有一些绿色和红色的标记,给算法提供了一些提示,这些像素分别属于前景像素和背景像素,使用该算法对图像进行迭代分割,得到最佳结果。基于图论的方法还有Graphcut、Random Walk等。
采用max flow算法,一次全局求解最小能量割边,能量定义如下:
E(L)=aR(L)+B(L)
其中,系数a是一个权重系数,R(L)是S与各个像素点之间的虚线,B(L)是各像素点之间的实线。

文献:Rother, C. . (2004). Grabcut : interactive foreground extraction using iterated graph cut. Acm Trans Graph, 23.
网址:https://cgl.ethz.ch/teaching/former/imagesynthesis_06/miniprojects/p2/index.html
本文分享自 图像处理与模式识别研究所 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!