2017-10-19 98 views
1

我试图让梅西例如工作:https://docs.opencv.org/3.1.0/d8/d83/tutorial_py_grabcut.html如何获得grabCut工作OpenCV的蟒蛇与GC_INIT_WITH_MASK

在我的设置,我希望整个过程自动化。

例如,我抢的图像从网站: http://wanderlustandlipstick.com/travel-tips/opting-out-full-body-scanners/

Image Scan - imagescan.png

而且使用一些OpenCV的工具,我自动生成以下掩码:

Image Mask - imagemask.png

黑应该有一定的背景,白色应该是某种前景,灰色应该是未知的。

继梅西教程(https://docs.opencv.org/3.1.0/d8/d83/tutorial_py_grabcut.html)后,下面是我的代码。然而,它仅示出了小白色圆面积,就好像它是治疗灰色般的黑色(某些背景)

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

img = cv2.imread("imagescan.png") 
dimy = np.shape(img)[0] # seems to be backwards (x,y) 
# https://stackoverflow.com/questions/22490721/how-can-i-get-the-x-and-y-dimensions-of-a-ndarray-numpy-python 
dimx = np.shape(img)[1] 
mask = np.zeros((dimy,dimx),np.uint8) # zeroes as array/matrix size of image 
bgdModel = fgdModel = np.zeros((1,65),np.float64)  

newmask = cv2.imread('imagemask.png',0) 

# informational purposes 
removeBg = (newmask == 0) 
removeBg = np.ravel(removeBg) 
np.bincount(removeBg) 
keepFg = (newmask == 255) 
keepFg = np.ravel(keepFg) 
np.bincount(keepFg) 

#otherEl = (not (newmask == 0 or newmask == 255)) # throws error 
#otherEl = np.ravel(otherEl) 
#np.bincount(otherEl) 

# appears at least one of each elements is required 
# otherwise throws bgdSamples.empty error/fgdSamples.empty error 
mask[newmask == 0] = 0 
mask[newmask == 255] = 1 

mask, bgdModel, fgdModel = cv2.grabCut(img,mask,None,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_MASK) 

mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8') 
img2 = img*mask2[:,:,np.newaxis] 
plt.imshow(img2),plt.colorbar(),plt.show() 

结果仅仅是一个掩模关闭圆,仿佛灰色区域被视为黑。

Output is not what I want!

回答

1

在掩模图像,你基本上有3种颜色:黑,白,灰。在以下几行代码中,您正在设置背景和前景,但不是可能的前景。

mask[newmask == 0] = 0 
mask[newmask == 255] = 1 

尝试使用的OpenCV提供常数(cv2.GC_BGD等),以避免混淆使用。

# this line sets the grey areas - meaning any color not 0 and not 255 - to probable foreground. 
mask = np.where(((newmask>0) & (newmask<255)),cv2.GC_PR_FGD,0).astype('uint8') 
mask[newmask == 0] = cv2.GC_BGD 
mask[newmask == 255] = cv2.GC_FGD 

Result