Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/Background-Subtraction/background_subtr_opencv.py
3118 views
1
import argparse
2
3
import cv2
4
5
6
def get_opencv_result(video_to_process):
7
# create VideoCapture object for further video processing
8
captured_video = cv2.VideoCapture(video_to_process)
9
# check video capture status
10
if not captured_video.isOpened:
11
print("Unable to open: " + video_to_process)
12
exit(0)
13
14
# instantiate background subtraction
15
background_subtr_method = cv2.bgsegm.createBackgroundSubtractorGSOC()
16
17
while True:
18
# read video frames
19
retval, frame = captured_video.read()
20
21
# check whether the frames have been grabbed
22
if not retval:
23
break
24
25
# resize video frames
26
frame = cv2.resize(frame, (640, 360))
27
28
# pass the frame to the background subtractor
29
foreground_mask = background_subtr_method.apply(frame)
30
# obtain the background without foreground mask
31
background_img = background_subtr_method.getBackgroundImage()
32
33
# show the current frame, foreground mask, subtracted result
34
cv2.imshow("Initial Frames", frame)
35
cv2.imshow("Foreground Masks", foreground_mask)
36
cv2.imshow("Subtraction Result", background_img)
37
38
keyboard = cv2.waitKey(10)
39
if keyboard == 27:
40
break
41
42
43
if __name__ == "__main__":
44
parser = argparse.ArgumentParser()
45
parser.add_argument(
46
"--input_video",
47
type=str,
48
help="Define the full input video path",
49
default="space_traffic.mp4",
50
)
51
52
# parse script arguments
53
args = parser.parse_args()
54
55
# start BS-pipeline
56
get_opencv_result(args.input_video)
57
58