Advertisement
Guest User

grabcut_algo.py

a guest
May 10th, 2021
762
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3.  
  4. drawn = False
  5. startx, starty = -1, -1
  6. rectangle = (0, 0, 0, 0)
  7. def load_and_resize(path):
  8.     image = cv2.imread(path)
  9.     new_size = (700, 700)
  10.     resized_image = cv2.resize(image, new_size, interpolation=cv2.INTER_AREA)
  11.     return resized_image
  12.  
  13. def select_roi(event, newx, newy, flags, params):
  14.     global startx, starty, drawn, rectangle
  15.     if event == cv2.EVENT_LBUTTONDOWN:
  16.       startx, starty = newx, newy
  17.       cv2.circle(image, (startx, starty), 4, (255, 255, 120), -1)
  18.     elif event == cv2.EVENT_LBUTTONUP:
  19.       drawn = True
  20.       rectangle = (startx, starty, newx - startx, newy - starty)
  21.       print("\nROI Selected Successfully")
  22.  
  23. def extract_foreground(image):
  24.     global drawn
  25.     cv2.namedWindow(winname='BG Subractor')
  26.     cv2.setMouseCallback('BG Subractor', select_roi)
  27.     print("\nSelect ROI from mouse pointer.")
  28.     black_mask = np.zeros(image.shape[:2], np.uint8)
  29.     background = np.zeros((1, 65), np.float64)
  30.     foreground = np.zeros((1, 65), np.float64)
  31.     while True:
  32.         if drawn:
  33.             print("\nPerforming Background Subtraction")
  34.             cv2.grabCut(image, black_mask, rectangle,background, foreground,5, cv2.GC_INIT_WITH_RECT)
  35.             #cv2.imshow('Image before multipllication',image)
  36.             mask2 = np.where((black_mask == 2) | (black_mask == 0), 0, 1).astype('uint8')
  37.             cv2.imshow('Mask', mask2)
  38.             image = image * mask2[:, :, np.newaxis]
  39.             drawn = False
  40.             print("\nExtraction complete")
  41.         cv2.imshow('BG Subractor', image)
  42.         if cv2.waitKey(1) & 0xFF == 27:
  43.              break
  44.     cv2.destroyAllWindows()
  45.  
  46.  
  47. image = load_and_resize('img.png')
  48. extract_foreground(image)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement