topic description
Image segmentation using GrabCut algorithm
sources of topics and their own ideas
Source: business priority
reference article: https://www.jianshu.com/p/117.
related codes
/ / Please paste the code text below (do not replace the code with pictures)
"""
Created on 2018112
@author:
"""
""""""
import cv2
import numpy as np
import matplotlib.pyplot as plt
"""
cv2.grabCut()
img
mask cv2.GC_BGD,cv2.GC_FGD,cv2.GC_PR_BGD,cv2.GC_PR_FGD0,1,2,3
rect x,y,w,h
bdgModel, fgdModel (1,65np.float64
iterCount
mode cv2.GC_INIT_WITH_RECT cv2.GC_INIT_WITH_MASK
"""
fname = "new1.jpg"
img = cv2.imread(fname)
img1 = cv2.imread("new111.png")
rect = (195, 23, 713, 1321)
mask = np.zeros(img.shape[:2], np.uint8)
-sharp newmask = cv2.imread("newmask.png",0)
-sharp mask[newmask == 0] = 0
-sharp mask[newmask == 255] = 1
bgdModel = np.zeros((1,65), np.float64)
fgdModel = np.zeros((1,65), np.float64)
-sharp mask, bgdModel, fgdModel = cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_MASK)
-sharp cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)
-sharp mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype(np.uint8)
-sharp
-sharp out = img * mask2[:, :, np.newaxis]
-sharp cv2.imshow("output", out)
-sharp cv2.imwrite("new111.png", out)-sharp
-sharp cv2.waitKey()
-sharp newmask is the mask image I manually labelled
newmask = cv2.imread("newmask.png",0)
-sharp whereever it is marked white (sure foreground), change mask=1
-sharp whereever it is marked black (sure background), change mask=0
mask[newmask == 0] = 0
mask[newmask == 255] = 1
mask, bgdModel, fgdModel = cv2.grabCut(img1,mask,None,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_MASK)
mask = np.where((mask==2)|(mask==0),0,1).astype("uint8")
img = img1*mask[:,:,np.newaxis]
cv2.imwrite("done.png", img)-sharp
cv2.waitKey()
print("done!")
: