Skip to content

Commit 0940721

Browse files
authored
avinashkranjan#867 Image background subractor added
1 parent a8ea1bb commit 0940721

File tree

3 files changed

+164
-0
lines changed

3 files changed

+164
-0
lines changed
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import cv2
2+
import numpy as np
3+
4+
# drawn act as a flag variable to see if ROI has been selected or not
5+
drawn = False
6+
ix, iy = -1, -1
7+
# To store ROI values
8+
rectangle = (0, 0, 0, 0)
9+
10+
11+
def open_image(path):
12+
"""
13+
It opens the image when a valid path is given.
14+
:param path: image location path
15+
:return:
16+
"""
17+
img = cv2.imread(path)
18+
dim = (512, 512)
19+
resized_image = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
20+
return resized_image
21+
22+
23+
# mouse callback function
24+
def draw_rectangle(event, x, y, flags, params):
25+
"""
26+
Its a mouse callback function called automatically whenever
27+
any event is happened on the image that is clicking any button on
28+
mouse or keyboard.
29+
"""
30+
31+
global ix, iy, drawn, rectangle
32+
if event == cv2.EVENT_LBUTTONDOWN:
33+
# When you click DOWN with left mouse button
34+
# Then we take note of where that mouse was located
35+
ix, iy = x, y
36+
cv2.circle(img, (ix, iy), 4, (0, 0, 255), -1)
37+
38+
elif event == cv2.EVENT_LBUTTONUP:
39+
# Once you lift the mouse button
40+
# we complete the rectangle ie ROI is selected.
41+
drawn = True
42+
rectangle = (ix, iy, x - ix, y - iy)
43+
print("\nROI Selected Successfully!")
44+
45+
46+
def background_sub(image):
47+
"""
48+
This function:
49+
1. Takes image as input and
50+
2. Asks user to select ROI by dragging mouse pointer.
51+
3. Performs background subtraction.
52+
4. Displaying the updated image.
53+
5. Saving the processed image in your current directory.
54+
55+
GrabCut Algorithm is used
56+
link : https://www.geeksforgeeks.org/python-foreground-extraction-in-an-image-using-grabcut-algorithm/
57+
58+
:param image: Image on which Background subtraction is to be performed.
59+
:return:
60+
"""
61+
62+
# To check if ROI has been selected or not
63+
global drawn
64+
65+
# This names the window so we can reference it
66+
cv2.namedWindow(winname='BG Subractor')
67+
# Connects the mouse button to our callback function
68+
cv2.setMouseCallback('BG Subractor', draw_rectangle)
69+
70+
print("\nSelect ROI from mouse pointer.")
71+
72+
# Creating mask, background and foregound models for Grabcut Algorithm
73+
black_mask = np.zeros(image.shape[:2], np.uint8)
74+
background = np.zeros((1, 65), np.float64)
75+
foreground = np.zeros((1, 65), np.float64)
76+
77+
while True: # Runs forever until we break with Esc key on keyboard
78+
79+
# If ROI is selected
80+
if drawn:
81+
print("\nPerforming Background Subtraction")
82+
# Using Grabcut Algorithm only when ROI is drawn and saved in
83+
# variable named rectangle
84+
cv2.grabCut(image, black_mask, rectangle,
85+
background, foreground,
86+
5, cv2.GC_INIT_WITH_RECT)
87+
88+
# mask with 1 and 4 denotes foreground
89+
# mask with 2 and 0 denotes background so converting the bg pixels into black
90+
mask2 = np.where((black_mask == 2) | (black_mask == 0), 0, 1).astype('uint8')
91+
92+
# multiplying mask2 with original image so that we can get our resultant
93+
image = image * mask2[:, :, np.newaxis]
94+
95+
# For saving the file
96+
cv2.imwrite('Bg_removed.jpg', image)
97+
print(f'\nBg_removed.jpg saved in your current directory!')
98+
print('Great Success!!!')
99+
100+
# Once the processing has been done setting drawn to False
101+
drawn = False
102+
103+
# Shows the resultant image in image window
104+
cv2.imshow('BG Subractor', image)
105+
106+
# Press ESC to exit
107+
if cv2.waitKey(1) & 0xFF == 27:
108+
break
109+
110+
# It closes all windows (just in case you have multiple windows called)
111+
cv2.destroyAllWindows()
112+
113+
114+
if __name__ == '__main__':
115+
loc = input('Enter image path: ')
116+
img = open_image(loc)
117+
background_sub(img)
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Image Background Subtraction using OpenCV.
2+
3+
This python script lets you remove background form image by keeping only foreground in focus.
4+
By using [Grabcut Algorithm](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_grabcut/py_grabcut.html) it makes easy to do the task.
5+
6+
We make use of OpenCV, numpy libraries of Python.
7+
8+
This Script:
9+
1. Takes image as input and
10+
2. Asks user to select ROI by dragging mouse pointer.
11+
3. Performs background subtraction.
12+
4. Displaying the updated image.
13+
5. Saving the processed image in your current directory.
14+
15+
![Gif](https://media.giphy.com/media/DZCjZKyNHzsOktHqvI/giphy.gif)
16+
17+
## Setting up:
18+
19+
- Create a virtual environment and activate it.
20+
21+
- Install the requirements
22+
23+
```sh
24+
$ pip install -r requirements.txt
25+
```
26+
27+
## Running the script:
28+
29+
```sh
30+
$ python BG_Subtractor.py
31+
```
32+
33+
1. Enter valid file location/path.
34+
2. Select ROI by using mouse pointer on the window <b>BG Subractor</b>.
35+
3. Then script will process the image.
36+
4. Image <b>Bg_removed.jpg</b> will be stored in your current directory.
37+
38+
![Gif](https://media.giphy.com/media/GVxM1xt46gDS5biPSr/giphy.gif)
39+
40+
41+
## Output:
42+
![Image](https://i.imgur.com/SCf4XRj.jpg)
43+
44+
## Author
45+
[🛡 Akhil Bhalerao 🛡 ](https://linktr.ee/iamakkkhil)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
numpy==1.20.1
2+
opencv-python==4.5.1.48

0 commit comments

Comments
 (0)