2017-10-19 12 views
1

Je suis en train d'obtenir l'exemple de messi au travail: https://docs.opencv.org/3.1.0/d8/d83/tutorial_py_grabcut.htmlComment obtenir grabCut travailler python OpenCV avec GC_INIT_WITH_MASK

Dans ma configuration, je veux l'ensemble du processus automatisé.

Par exemple, je prends une image à partir du Web: http://wanderlustandlipstick.com/travel-tips/opting-out-full-body-scanners/

Image Scan - imagescan.png

Et en utilisant des outils OpenCV J'AutoGenerate le masque suivant:

Image Mask - imagemask.png

noir est censé être un certain fond, White est censé être un certain premier plan, et Gray est censé être inconnu.

Après le didacticiel Messi (https://docs.opencv.org/3.1.0/d8/d83/tutorial_py_grabcut.html), voici mon code. Cependant, il ne montre que la petite zone de cercle blanc, comme si elle traite gris comme le noir (certains arrière-plan)

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() 

Le résultat est juste un masque hors du cercle, comme si la zone grise est traitée en noir .

Output is not what I want!

Répondre

1

Dans l'image de masque, vous avez essentiellement 3 couleurs: noir, blanc, gris. Dans les lignes de code suivantes, vous définissez l'arrière-plan et le premier plan, mais pas le premier plan probable.

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

Essayez d'utiliser l'aide OpenCV fourni des constantes (cv2.GC_BGD etc) pour éviter toute confusion.

# 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.