|
| 1 | +import cv2 |
| 2 | +import numpy as np |
| 3 | +import tkinter as tk |
| 4 | +from tkinter.filedialog import * |
| 5 | + |
| 6 | +# asking input from user |
| 7 | +photo = askopenfilename() |
| 8 | +img = cv2.imread(photo) |
| 9 | +imgcopy = img |
| 10 | + |
| 11 | +a,b = -1,-1 |
| 12 | +rect = (0,0,0,0) |
| 13 | +draw = False |
| 14 | +count = 0 |
| 15 | + |
| 16 | +# for selecting the required foreground portion with a rectangle |
| 17 | +def rect_draw(event, x, y, flag, param): |
| 18 | + global draw,a,b,rect,count |
| 19 | + if (event == cv2.EVENT_LBUTTONDOWN): |
| 20 | + draw = True |
| 21 | + a,b = x,y |
| 22 | + elif (event == cv2.EVENT_MOUSEMOVE): |
| 23 | + if (draw==True): |
| 24 | + rect = (a,b,x,y) |
| 25 | + elif (event == cv2.EVENT_LBUTTONUP): |
| 26 | + draw = False |
| 27 | + count = 1 |
| 28 | + cv2.rectangle(img, (a,b),(x,y), (0,255,0), 1) |
| 29 | + rect = (a,b,x,y) |
| 30 | + cv2.imshow('Mark foreground', img) |
| 31 | + cv2.waitKey(0) |
| 32 | + cv2.destroyAllWindows() |
| 33 | + |
| 34 | +cv2.namedWindow('Mark foreground') |
| 35 | +cv2.setMouseCallback('Mark foreground', rect_draw) # call back function |
| 36 | +while count==0: |
| 37 | + cv2.imshow('Mark foreground', img) |
| 38 | + if cv2.waitKey(20) & 0xFF == 27: |
| 39 | + break |
| 40 | + |
| 41 | +# Using the grabcut algorithm |
| 42 | +mask = np.zeros(imgcopy.shape[:2], np.uint8) |
| 43 | +bgdModel = np.zeros((1,65), np.float64) |
| 44 | +fgdModel = np.zeros((1,65), np.float64) |
| 45 | +cv2.grabCut(imgcopy, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT) |
| 46 | +mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8') |
| 47 | +imgcopy = imgcopy*mask2[:,:,np.newaxis] |
| 48 | + |
| 49 | +# displaying and saving the output image |
| 50 | +cv2.imshow("Output", imgcopy) |
| 51 | +cv2.imwrite("Output.png", imgcopy) |
| 52 | +cv2.waitKey(0) |
| 53 | +cv2.destroyAllWindows() |
0 commit comments