In [2]:
%pylab inline


Populating the interactive namespace from numpy and matplotlib

In [3]:
import cv2
import cv
import numpy as np
import pylab as pl

In [91]:
img = cv2.imread("graph_cut.jpg")
img_grey = cv2.cvtColor(img, cv.CV_BGR2GRAY)
pl.imshow(img)


Out[91]:
<matplotlib.image.AxesImage at 0x8b761d0>

In [146]:
_, proba_mask = cv2.threshold(img_grey, -1, cv2.GC_PR_FGD, cv.CV_THRESH_BINARY_INV | cv.CV_THRESH_OTSU)

sure_mask = cv2.erode(proba_mask, None,iterations=6)

proba_mask = cv2.dilate(proba_mask, None,iterations=7)
proba_mask[sure_mask==cv2.GC_PR_FGD] = cv2.GC_FGD

pl.imshow(proba_mask*100)


Out[146]:
<matplotlib.image.AxesImage at 0xbfa7250>

In [99]:
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

In [103]:
cv2.grabCut(img, proba_mask,None, bgdModel,fgdModel,5,cv2.GC_INIT_WITH_MASK)

#mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
#img = img*mask2[:,:,np.newaxis]

mask2 = np.where((proba_mask==2)|(proba_mask==0),0,1).astype('uint8')
img_f = img_grey*mask2

plt.imshow(mask2)
plt.colorbar()
plt.show()



In [418]:
img = cv2.imread("graph_cut.jpg")
img_grey = cv2.cvtColor(img, cv.CV_BGR2GRAY)
pl.imshow(img)


Out[418]:
<matplotlib.image.AxesImage at 0x3022a590>

In [419]:
_, kmask = cv2.threshold(img_grey, -1, 1, cv.CV_THRESH_BINARY_INV | cv.CV_THRESH_OTSU)

kmask = cv2.erode(kmask, None,iterations=6)

kmask = cv2.dilate(kmask, None,iterations=40)
#proba_mask[sure_mask==cv2.GC_PR_FGD] = cv2.GC_FGD

pl.imshow(kmask)


Out[419]:
<matplotlib.image.AxesImage at 0x3049d310>

In [426]:
plt.imshow(img_grey)

grey = img_grey.flatten().astype(np.float32)

grey_lap = cv2.Laplacian(img_grey, cv2.CV_32F,5).flatten().astype(np.float32)

x = np.fromfunction(lambda i,j: j, img_grey.shape, dtype=np.float32).flatten(0)
y = np.fromfunction(lambda i,j: i, img_grey.shape, dtype=np.float32).flatten(0)

def center_red(a):
    return a - np.mean(a) / np.std(a) 

x, y, grey = x/max(x),y/max(y), center_red(grey)

data =  np.column_stack((grey*100,x, y))
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)

data_masked = data[kmask.flatten()==1, :]
_, labs_masked, centre = cv2.kmeans(data_masked, 4 , criteria, 10, cv2.KMEANS_PP_CENTERS)
labs = np.zeros(grey.shape, np.uint8)
labs[kmask.flatten()==1] = labs_masked +1
plt.imshow(labs.reshape(img_grey.shape))
#plt.imshow(dist.reshape(img_grey.shape))


Out[426]:
<matplotlib.image.AxesImage at 0x313a0350>

In [327]:


In [326]:


In [195]:


In [ ]: