background_subtr_opencv.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import argparse
  2. import cv2
  3. def get_opencv_result(video_to_process):
  4. # create VideoCapture object for further video processing
  5. captured_video = cv2.VideoCapture(video_to_process)
  6. # check video capture status
  7. if not captured_video.isOpened:
  8. print("Unable to open: " + video_to_process)
  9. exit(0)
  10. # instantiate background subtraction
  11. background_subtr_method = cv2.bgsegm.createBackgroundSubtractorGSOC()
  12. while True:
  13. # read video frames
  14. retval, frame = captured_video.read()
  15. # check whether the frames have been grabbed
  16. if not retval:
  17. break
  18. # resize video frames
  19. frame = cv2.resize(frame, (640, 360))
  20. # pass the frame to the background subtractor
  21. foreground_mask = background_subtr_method.apply(frame)
  22. # obtain the background without foreground mask
  23. background_img = background_subtr_method.getBackgroundImage()
  24. # show the current frame, foreground mask, subtracted result
  25. cv2.imshow("Initial Frames", frame)
  26. cv2.imshow("Foreground Masks", foreground_mask)
  27. cv2.imshow("Subtraction Result", background_img)
  28. keyboard = cv2.waitKey(10)
  29. if keyboard == 27:
  30. break
  31. if __name__ == "__main__":
  32. parser = argparse.ArgumentParser()
  33. parser.add_argument(
  34. "--input_video",
  35. type=str,
  36. help="Define the full input video path",
  37. default="space_traffic.mp4",
  38. )
  39. # parse script arguments
  40. args = parser.parse_args()
  41. # start BS-pipeline
  42. get_opencv_result(args.input_video)