main.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import cv2
  2. input_video = "sample/car.mp4"
  3. # video Inference
  4. def vid_inf(vid_path):
  5. # Create a VideoCapture object
  6. cap = cv2.VideoCapture(vid_path)
  7. # get the video frames' width and height for proper saving of videos
  8. frame_width = int(cap.get(3))
  9. frame_height = int(cap.get(4))
  10. fps = int(cap.get(cv2.CAP_PROP_FPS))
  11. frame_size = (frame_width, frame_height)
  12. fourcc = cv2.VideoWriter_fourcc(*"mp4v")
  13. output_video = "output_recorded.mp4"
  14. # create the `VideoWriter()` object
  15. out = cv2.VideoWriter(output_video, fourcc, fps, frame_size)
  16. # Create Background Subtractor MOG2 object
  17. backSub = cv2.createBackgroundSubtractorMOG2()
  18. # Check if camera opened successfully
  19. if not cap.isOpened():
  20. print("Error opening video file")
  21. count = 0
  22. # Read until video is completed
  23. while cap.isOpened():
  24. # Capture frame-by-frame
  25. ret, frame = cap.read()
  26. if ret:
  27. # Apply background subtraction
  28. fg_mask = backSub.apply(frame)
  29. # apply global threshol to remove shadows
  30. retval, mask_thresh = cv2.threshold(fg_mask, 180, 255, cv2.THRESH_BINARY)
  31. # set the kernal
  32. kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
  33. # Apply erosion
  34. mask_eroded = cv2.morphologyEx(mask_thresh, cv2.MORPH_OPEN, kernel)
  35. # Find contours
  36. contours, hierarchy = cv2.findContours(mask_eroded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  37. min_contour_area = 500 # Define your minimum area threshold
  38. # filtering contours using list comprehension
  39. large_contours = [cnt for cnt in contours if cv2.contourArea(cnt) > min_contour_area]
  40. frame_out = frame.copy()
  41. for cnt in large_contours:
  42. x, y, w, h = cv2.boundingRect(cnt)
  43. frame_out = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 200), 3)
  44. # saving the video file
  45. out.write(frame_out)
  46. # Display the resulting frame
  47. cv2.imshow("Frame_final", frame_out)
  48. # Press Q on keyboard to exit
  49. if cv2.waitKey(30) & 0xFF == ord("q"):
  50. break
  51. else:
  52. break
  53. # When everything done, release the video capture and writer object
  54. cap.release()
  55. out.release()
  56. # Closes all the frames
  57. cv2.destroyAllWindows()
  58. vid_inf(input_video)