3
===============================================================================
4
Interactive Image Segmentation using GrabCut algorithm.
6
This sample shows interactive image segmentation using grabcut algorithm.
9
python grabcut.py <filename>
12
Two windows will show up, one for input and one for output.
14
At first, in input window, draw a rectangle around the object using
15
mouse right button. Then press 'n' to segment the object (once or a few times)
16
For any finer touch-ups, you can press any of the keys below and draw lines on
17
the areas you want. Then again press 'n' for updating the output.
19
Key '0' - To select areas of sure background
20
Key '1' - To select areas of sure foreground
21
Key '2' - To select areas of probable background
22
Key '3' - To select areas of probable foreground
24
Key 'n' - To update the segmentation
25
Key 'r' - To reset the setup
26
Key 's' - To save the results
27
===============================================================================
30
# Python 2/3 compatibility
31
from __future__ import print_function
37
BLUE = [255,0,0] # rectangle color
38
RED = [0,0,255] # PR BG
39
GREEN = [0,255,0] # PR FG
40
BLACK = [0,0,0] # sure BG
41
WHITE = [255,255,255] # sure FG
43
DRAW_BG = {'color' : BLACK, 'val' : 0}
44
DRAW_FG = {'color' : WHITE, 'val' : 1}
45
DRAW_PR_FG = {'color' : GREEN, 'val' : 3}
46
DRAW_PR_BG = {'color' : RED, 'val' : 2}
50
drawing = False # flag for drawing curves
51
rectangle = False # flag for drawing rect
52
rect_over = False # flag to check if rect drawn
53
rect_or_mask = 100 # flag for selecting rect or mask mode
54
value = DRAW_FG # drawing initialized to FG
55
thickness = 3 # brush thickness
57
def onmouse(event,x,y,flags,param):
58
global img,img2,drawing,value,mask,rectangle,rect,rect_or_mask,ix,iy,rect_over
61
if event == cv2.EVENT_RBUTTONDOWN:
65
elif event == cv2.EVENT_MOUSEMOVE:
68
cv2.rectangle(img,(ix,iy),(x,y),BLUE,2)
69
rect = (min(ix,x),min(iy,y),abs(ix-x),abs(iy-y))
72
elif event == cv2.EVENT_RBUTTONUP:
75
cv2.rectangle(img,(ix,iy),(x,y),BLUE,2)
76
rect = (min(ix,x),min(iy,y),abs(ix-x),abs(iy-y))
78
print(" Now press the key 'n' a few times until no further change \n")
82
if event == cv2.EVENT_LBUTTONDOWN:
83
if rect_over == False:
84
print("first draw rectangle \n")
87
cv2.circle(img,(x,y),thickness,value['color'],-1)
88
cv2.circle(mask,(x,y),thickness,value['val'],-1)
90
elif event == cv2.EVENT_MOUSEMOVE:
92
cv2.circle(img,(x,y),thickness,value['color'],-1)
93
cv2.circle(mask,(x,y),thickness,value['val'],-1)
95
elif event == cv2.EVENT_LBUTTONUP:
98
cv2.circle(img,(x,y),thickness,value['color'],-1)
99
cv2.circle(mask,(x,y),thickness,value['val'],-1)
101
if __name__ == '__main__':
103
# print documentation
107
if len(sys.argv) == 2:
108
filename = sys.argv[1] # for drawing purposes
110
print("No input image given, so loading default image, ../data/lena.jpg \n")
111
print("Correct Usage: python grabcut.py <filename> \n")
112
filename = '../data/lena.jpg'
114
img = cv2.imread(filename)
115
img2 = img.copy() # a copy of original image
116
mask = np.zeros(img.shape[:2],dtype = np.uint8) # mask initialized to PR_BG
117
output = np.zeros(img.shape,np.uint8) # output image to be shown
119
# input and output windows
120
cv2.namedWindow('output')
121
cv2.namedWindow('input')
122
cv2.setMouseCallback('input',onmouse)
123
cv2.moveWindow('input',img.shape[1]+10,90)
125
print(" Instructions: \n")
126
print(" Draw a rectangle around the object using right mouse button \n")
130
cv2.imshow('output',output)
131
cv2.imshow('input',img)
132
k = 0xFF & cv2.waitKey(1)
135
if k == 27: # esc to exit
137
elif k == ord('0'): # BG drawing
138
print(" mark background regions with left mouse button \n")
140
elif k == ord('1'): # FG drawing
141
print(" mark foreground regions with left mouse button \n")
143
elif k == ord('2'): # PR_BG drawing
145
elif k == ord('3'): # PR_FG drawing
147
elif k == ord('s'): # save image
148
bar = np.zeros((img.shape[0],5,3),np.uint8)
149
res = np.hstack((img2,bar,img,bar,output))
150
cv2.imwrite('grabcut_output.png',res)
151
print(" Result saved as image \n")
152
elif k == ord('r'): # reset everything
153
print("resetting \n")
161
mask = np.zeros(img.shape[:2],dtype = np.uint8) # mask initialized to PR_BG
162
output = np.zeros(img.shape,np.uint8) # output image to be shown
163
elif k == ord('n'): # segment the image
164
print(""" For finer touchups, mark foreground and background after pressing keys 0-3
165
and again press 'n' \n""")
166
if (rect_or_mask == 0): # grabcut with rect
167
bgdmodel = np.zeros((1,65),np.float64)
168
fgdmodel = np.zeros((1,65),np.float64)
169
cv2.grabCut(img2,mask,rect,bgdmodel,fgdmodel,1,cv2.GC_INIT_WITH_RECT)
171
elif rect_or_mask == 1: # grabcut with mask
172
bgdmodel = np.zeros((1,65),np.float64)
173
fgdmodel = np.zeros((1,65),np.float64)
174
cv2.grabCut(img2,mask,rect,bgdmodel,fgdmodel,1,cv2.GC_INIT_WITH_MASK)
176
mask2 = np.where((mask==1) + (mask==3),255,0).astype('uint8')
177
output = cv2.bitwise_and(img2,img2,mask=mask2)
179
cv2.destroyAllWindows()